blob: 7e6c3dd9d59ea23f0243fb2f19a74c13d4f6acff [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"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010021#include "absl/strings/match.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "api/jsepicecandidate.h"
23#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020026#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080028#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020029#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "logging/rtc_event_log/rtc_event_log.h"
31#include "media/sctp/sctptransport.h"
32#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080033#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "pc/channelmanager.h"
35#include "pc/dtmfsender.h"
36#include "pc/mediastream.h"
37#include "pc/mediastreamobserver.h"
38#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080039#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "pc/rtpreceiver.h"
41#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080042#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080043#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "pc/streamcollection.h"
Amit Hilbuchae3df542019-01-07 12:13:08 -080045#include "pc/unique_id_generator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "pc/videocapturertracksource.h"
47#include "pc/videotrack.h"
48#include "rtc_base/bind.h"
49#include "rtc_base/checks.h"
50#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010051#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020053#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/trace_event.h"
55#include "system_wrappers/include/clock.h"
56#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070057#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
Steve Anton75737c02017-11-06 10:37:17 -080059using cricket::ContentInfo;
60using cricket::ContentInfos;
61using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080063using cricket::SessionDescription;
64using cricket::SimulcastLayerList;
Steve Anton75737c02017-11-06 10:37:17 -080065using cricket::TransportInfo;
66
67using cricket::LOCAL_PORT_TYPE;
68using cricket::STUN_PORT_TYPE;
69using cricket::RELAY_PORT_TYPE;
70using cricket::PRFLX_PORT_TYPE;
71
Steve Antonba818672017-11-06 10:21:57 -080072namespace webrtc {
73
Steve Anton75737c02017-11-06 10:37:17 -080074// Error messages
75const char kBundleWithoutRtcpMux[] =
76 "rtcp-mux must be enabled when BUNDLE "
77 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080078const char kInvalidCandidates[] = "Description contains invalid candidates.";
79const char kInvalidSdp[] = "Invalid session description.";
80const char kMlineMismatchInAnswer[] =
81 "The order of m-lines in answer doesn't match order in offer. Rejecting "
82 "answer.";
83const char kMlineMismatchInSubsequentOffer[] =
84 "The order of m-lines in subsequent offer doesn't match order from "
85 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080086const char kSdpWithoutDtlsFingerprint[] =
87 "Called with SDP without DTLS fingerprint.";
88const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
89const char kSdpWithoutIceUfragPwd[] =
90 "Called with SDP without ice-ufrag and ice-pwd.";
91const char kSessionError[] = "Session error code: ";
92const char kSessionErrorDesc[] = "Session error description: ";
93const char kDtlsSrtpSetupFailureRtp[] =
94 "Couldn't set up DTLS-SRTP on RTP channel.";
95const char kDtlsSrtpSetupFailureRtcp[] =
96 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Steve Anton75737c02017-11-06 10:37:17 -080098namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099
Seth Hampson845e8782018-03-02 11:34:10 -0800100static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800101static const char kDefaultAudioSenderId[] = "defaulta0";
102static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700103
zhihuang8f65cdf2016-05-06 18:40:30 -0700104// The length of RTCP CNAMEs.
105static const int kRtcpCnameLength = 16;
106
Steve Antonad182762018-09-05 20:22:40 +0000107enum {
108 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
109 MSG_SET_SESSIONDESCRIPTION_FAILED,
110 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
111 MSG_GETSTATS,
112 MSG_FREE_DATACHANNELS,
113 MSG_REPORT_USAGE_PATTERN,
114};
115
Harald Alvestrand19793842018-06-25 12:03:50 +0200116static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
117
Steve Antonad182762018-09-05 20:22:40 +0000118struct SetSessionDescriptionMsg : public rtc::MessageData {
119 explicit SetSessionDescriptionMsg(
120 webrtc::SetSessionDescriptionObserver* observer)
121 : observer(observer) {}
122
123 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
124 RTCError error;
125};
126
127struct CreateSessionDescriptionMsg : public rtc::MessageData {
128 explicit CreateSessionDescriptionMsg(
129 webrtc::CreateSessionDescriptionObserver* observer)
130 : observer(observer) {}
131
132 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
133 RTCError error;
134};
135
136struct GetStatsMsg : public rtc::MessageData {
137 GetStatsMsg(webrtc::StatsObserver* observer,
138 webrtc::MediaStreamTrackInterface* track)
139 : observer(observer), track(track) {}
140 rtc::scoped_refptr<webrtc::StatsObserver> observer;
141 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
142};
143
deadbeefab9b2d12015-10-14 11:33:11 -0700144// Check if we can send |new_stream| on a PeerConnection.
145bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
146 webrtc::MediaStreamInterface* new_stream) {
147 if (!new_stream || !current_streams) {
148 return false;
149 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700150 if (current_streams->find(new_stream->id()) != nullptr) {
151 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100152 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700153 return false;
154 }
155 return true;
156}
157
deadbeef5e97fb52015-10-15 12:49:08 -0700158// If the direction is "recvonly" or "inactive", treat the description
159// as containing no streams.
160// See: https://code.google.com/p/webrtc/issues/detail?id=5054
161std::vector<cricket::StreamParams> GetActiveStreams(
162 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800163 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700164 ? desc->streams()
165 : std::vector<cricket::StreamParams>();
166}
167
deadbeefab9b2d12015-10-14 11:33:11 -0700168bool IsValidOfferToReceiveMedia(int value) {
169 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
170 return (value >= Options::kUndefined) &&
171 (value <= Options::kMaxOfferToReceiveMedia);
172}
173
zhihuang1c378ed2017-08-17 14:10:50 -0700174// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800175void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700176 const std::vector<rtc::scoped_refptr<
177 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700178 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200179 cricket::MediaDescriptionOptions* video_media_description_options,
180 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700181 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700182 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
183 if (audio_media_description_options) {
184 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 } else {
188 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
189 if (video_media_description_options) {
190 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800191 sender->id(), sender->internal()->stream_ids(), {},
192 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700193 }
194 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700195 }
zhihuang1c378ed2017-08-17 14:10:50 -0700196}
olka3c747662017-08-17 06:50:32 -0700197
zhihuang1c378ed2017-08-17 14:10:50 -0700198// Add options to |session_options| from |rtp_data_channels|.
199void AddRtpDataChannelOptions(
200 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
201 rtp_data_channels,
202 cricket::MediaDescriptionOptions* data_media_description_options) {
203 if (!data_media_description_options) {
204 return;
205 }
deadbeefab9b2d12015-10-14 11:33:11 -0700206 // Check for data channels.
207 for (const auto& kv : rtp_data_channels) {
208 const DataChannel* channel = kv.second;
209 if (channel->state() == DataChannel::kConnecting ||
210 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700211 // Legacy RTP data channels are signaled with the track/stream ID set to
212 // the data channel's label.
213 data_media_description_options->AddRtpDataChannel(channel->label(),
214 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700215 }
216 }
217}
218
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700219uint32_t ConvertIceTransportTypeToCandidateFilter(
220 PeerConnectionInterface::IceTransportsType type) {
221 switch (type) {
222 case PeerConnectionInterface::kNone:
223 return cricket::CF_NONE;
224 case PeerConnectionInterface::kRelay:
225 return cricket::CF_RELAY;
226 case PeerConnectionInterface::kNoHost:
227 return (cricket::CF_ALL & ~cricket::CF_HOST);
228 case PeerConnectionInterface::kAll:
229 return cricket::CF_ALL;
230 default:
nissec80e7412017-01-11 05:56:46 -0800231 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700232 }
233 return cricket::CF_NONE;
234}
235
deadbeef293e9262017-01-11 12:28:30 -0800236// Helper to set an error and return from a method.
237bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
238 if (error) {
239 error->set_type(type);
240 }
241 return type == webrtc::RTCErrorType::NONE;
242}
243
Steve Anton038834f2017-07-14 15:59:59 -0700244bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700245 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700246 if (error_out) {
247 *error_out = std::move(error);
248 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700249 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700250}
251
Steve Antonba818672017-11-06 10:21:57 -0800252std::string GetSignalingStateString(
253 PeerConnectionInterface::SignalingState state) {
254 switch (state) {
255 case PeerConnectionInterface::kStable:
256 return "kStable";
257 case PeerConnectionInterface::kHaveLocalOffer:
258 return "kHaveLocalOffer";
259 case PeerConnectionInterface::kHaveLocalPrAnswer:
260 return "kHavePrAnswer";
261 case PeerConnectionInterface::kHaveRemoteOffer:
262 return "kHaveRemoteOffer";
263 case PeerConnectionInterface::kHaveRemotePrAnswer:
264 return "kHaveRemotePrAnswer";
265 case PeerConnectionInterface::kClosed:
266 return "kClosed";
267 }
268 RTC_NOTREACHED();
269 return "";
270}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700271
Steve Anton75737c02017-11-06 10:37:17 -0800272IceCandidatePairType GetIceCandidatePairCounter(
273 const cricket::Candidate& local,
274 const cricket::Candidate& remote) {
275 const auto& l = local.type();
276 const auto& r = remote.type();
277 const auto& host = LOCAL_PORT_TYPE;
278 const auto& srflx = STUN_PORT_TYPE;
279 const auto& relay = RELAY_PORT_TYPE;
280 const auto& prflx = PRFLX_PORT_TYPE;
281 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800282 bool local_hostname =
283 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
284 bool remote_hostname = !remote.address().hostname().empty() &&
285 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800286 bool local_private = IPIsPrivate(local.address().ipaddr());
287 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800288 if (local_hostname) {
289 if (remote_hostname) {
290 return kIceCandidatePairHostNameHostName;
291 } else if (remote_private) {
292 return kIceCandidatePairHostNameHostPrivate;
293 } else {
294 return kIceCandidatePairHostNameHostPublic;
295 }
296 } else if (local_private) {
297 if (remote_hostname) {
298 return kIceCandidatePairHostPrivateHostName;
299 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800300 return kIceCandidatePairHostPrivateHostPrivate;
301 } else {
302 return kIceCandidatePairHostPrivateHostPublic;
303 }
304 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800305 if (remote_hostname) {
306 return kIceCandidatePairHostPublicHostName;
307 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800308 return kIceCandidatePairHostPublicHostPrivate;
309 } else {
310 return kIceCandidatePairHostPublicHostPublic;
311 }
312 }
313 }
314 if (l == host && r == srflx)
315 return kIceCandidatePairHostSrflx;
316 if (l == host && r == relay)
317 return kIceCandidatePairHostRelay;
318 if (l == host && r == prflx)
319 return kIceCandidatePairHostPrflx;
320 if (l == srflx && r == host)
321 return kIceCandidatePairSrflxHost;
322 if (l == srflx && r == srflx)
323 return kIceCandidatePairSrflxSrflx;
324 if (l == srflx && r == relay)
325 return kIceCandidatePairSrflxRelay;
326 if (l == srflx && r == prflx)
327 return kIceCandidatePairSrflxPrflx;
328 if (l == relay && r == host)
329 return kIceCandidatePairRelayHost;
330 if (l == relay && r == srflx)
331 return kIceCandidatePairRelaySrflx;
332 if (l == relay && r == relay)
333 return kIceCandidatePairRelayRelay;
334 if (l == relay && r == prflx)
335 return kIceCandidatePairRelayPrflx;
336 if (l == prflx && r == host)
337 return kIceCandidatePairPrflxHost;
338 if (l == prflx && r == srflx)
339 return kIceCandidatePairPrflxSrflx;
340 if (l == prflx && r == relay)
341 return kIceCandidatePairPrflxRelay;
342 return kIceCandidatePairMax;
343}
344
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800345// Logic to decide if an m= section can be recycled. This means that the new
346// m= section is not rejected, but the old local or remote m= section is
347// rejected. |old_content_one| and |old_content_two| refer to the m= section
348// of the old remote and old local descriptions in no particular order.
349// We need to check both the old local and remote because either
350// could be the most current from the latest negotation.
351bool IsMediaSectionBeingRecycled(SdpType type,
352 const ContentInfo& content,
353 const ContentInfo* old_content_one,
354 const ContentInfo* old_content_two) {
355 return type == SdpType::kOffer && !content.rejected &&
356 ((old_content_one && old_content_one->rejected) ||
357 (old_content_two && old_content_two->rejected));
358}
359
Steve Anton75737c02017-11-06 10:37:17 -0800360// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800361// |current_desc|. The number of m= sections in |new_desc| should be no
362// less than |current_desc|. In the case of checking an answer's
363// |new_desc|, the |current_desc| is the last offer that was set as the
364// local or remote. In the case of checking an offer's |new_desc| we
365// check against the local and remote descriptions stored from the last
366// negotiation, because either of these could be the most up to date for
367// possible rejected m sections. These are the |current_desc| and
368// |secondary_current_desc|.
369bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
370 const SessionDescription* secondary_current_desc,
371 const SessionDescription& new_desc,
372 const SdpType type) {
373 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800377 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
378 const cricket::ContentInfo* secondary_content_info = nullptr;
379 if (secondary_current_desc &&
380 i < secondary_current_desc->contents().size()) {
381 secondary_content_info = &secondary_current_desc->contents()[i];
382 }
383 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
384 &current_desc.contents()[i],
385 secondary_content_info)) {
386 // For new offer descriptions, if the media section can be recycled, it's
387 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800388 continue;
389 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800390 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800391 return false;
392 }
393 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800394 new_desc.contents()[i].media_description();
395 const MediaContentDescription* current_desc_mdesc =
396 current_desc.contents()[i].media_description();
397 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800398 return false;
399 }
400 }
401 return true;
402}
403
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800404bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
405 const SessionDescription& desc2) {
406 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800407}
408
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700409void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
410 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200411 // Array of structs needed to map {KeyExchangeProtocolType,
412 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
413 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
414 static constexpr struct {
415 KeyExchangeProtocolType protocol_type;
416 cricket::MediaType media_type;
417 KeyExchangeProtocolMedia protocol_media;
418 } kEnumCounterKeyProtocolMediaMap[] = {
419 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
420 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
421 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
422 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
423 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
424 kEnumCounterKeyProtocolMediaTypeDtlsData},
425 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
426 kEnumCounterKeyProtocolMediaTypeSdesAudio},
427 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
428 kEnumCounterKeyProtocolMediaTypeSdesVideo},
429 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
430 kEnumCounterKeyProtocolMediaTypeSdesData},
431 };
432
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700433 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
434 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100435
Mirko Bonadeiab499822018-09-11 10:43:20 +0200436 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
437 if (i.protocol_type == protocol_type && i.media_type == media_type) {
438 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
439 i.protocol_media,
440 kEnumCounterKeyProtocolMediaTypeMax);
441 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100442 }
443}
444
Harald Alvestrand76829d72018-07-18 23:24:36 +0200445void NoteAddIceCandidateResult(int result) {
446 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
447 kAddIceCandidateMax);
448}
449
Steve Anton75737c02017-11-06 10:37:17 -0800450// Checks that each non-rejected content has SDES crypto keys or a DTLS
451// fingerprint, unless it's in a BUNDLE group, in which case only the
452// BUNDLE-tag section (first media section/description in the BUNDLE group)
453// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
454// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
455// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700456RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800457 const cricket::ContentGroup* bundle =
458 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800459 for (const cricket::ContentInfo& content_info : desc->contents()) {
460 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800461 continue;
462 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100463 // Note what media is used with each crypto protocol, for all sections.
464 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
465 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700466 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800467 const std::string& mid = content_info.name;
468 if (bundle && bundle->HasContentName(mid) &&
469 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800470 // This isn't the first media section in the BUNDLE group, so it's not
471 // required to have crypto attributes, since only the crypto attributes
472 // from the first section actually get used.
473 continue;
474 }
475
476 // If the content isn't rejected or bundled into another m= section, crypto
477 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800478 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800479 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800480 if (!media || !tinfo) {
481 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800482 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800483 }
484 if (dtls_enabled) {
485 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100486 RTC_LOG(LS_WARNING)
487 << "Session description must have DTLS fingerprint if "
488 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800489 return RTCError(RTCErrorType::INVALID_PARAMETER,
490 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800491 }
492 } else {
493 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100494 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800495 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800496 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800497 }
498 }
499 }
Steve Anton8a006912017-12-04 15:25:56 -0800500 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800501}
502
503// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
504// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
505// media section/description in the BUNDLE group) needs a ufrag and pwd.
506bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
507 const cricket::ContentGroup* bundle =
508 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800509 for (const cricket::ContentInfo& content_info : desc->contents()) {
510 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800511 continue;
512 }
Steve Anton8a006912017-12-04 15:25:56 -0800513 const std::string& mid = content_info.name;
514 if (bundle && bundle->HasContentName(mid) &&
515 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800516 // This isn't the first media section in the BUNDLE group, so it's not
517 // required to have ufrag/password, since only the ufrag/password from
518 // the first section actually get used.
519 continue;
520 }
521
522 // If the content isn't rejected or bundled into another m= section,
523 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800524 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800525 if (!tinfo) {
526 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100527 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800528 return false;
529 }
530 if (tinfo->description.ice_ufrag.empty() ||
531 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100532 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800533 return false;
534 }
535 }
536 return true;
537}
538
Steve Anton75737c02017-11-06 10:37:17 -0800539// Get the SCTP port out of a SessionDescription.
540// Return -1 if not found.
541int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800542 const cricket::DataContentDescription* data_desc =
543 GetFirstDataContentDescription(session_description);
544 RTC_DCHECK(data_desc);
545 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800546 return -1;
547 }
Steve Anton75737c02017-11-06 10:37:17 -0800548 std::string value;
549 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
550 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800551 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800552 if (!codec.Matches(match_pattern)) {
553 continue;
554 }
555 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
556 return rtc::FromString<int>(value);
557 }
558 }
559 return -1;
560}
561
Steve Anton75737c02017-11-06 10:37:17 -0800562// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
563bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
564 const SessionDescriptionInterface* new_desc,
565 const std::string& content_name) {
566 if (!old_desc) {
567 return false;
568 }
569 const SessionDescription* new_sd = new_desc->description();
570 const SessionDescription* old_sd = old_desc->description();
571 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
572 if (!cinfo || cinfo->rejected) {
573 return false;
574 }
575 // If the content isn't rejected, check if ufrag and password has changed.
576 const cricket::TransportDescription* new_transport_desc =
577 new_sd->GetTransportDescriptionByName(content_name);
578 const cricket::TransportDescription* old_transport_desc =
579 old_sd->GetTransportDescriptionByName(content_name);
580 if (!new_transport_desc || !old_transport_desc) {
581 // No transport description exists. This is not an ICE restart.
582 return false;
583 }
584 if (cricket::IceCredentialsChanged(
585 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
586 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100587 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
588 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800589 return true;
590 }
591 return false;
592}
593
Steve Anton80dd7b52018-02-16 17:08:42 -0800594// Generates a string error message for SetLocalDescription/SetRemoteDescription
595// from an RTCError.
596std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
597 SdpType type,
598 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200599 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800600 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
601 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200602 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800603}
604
Seth Hampson5b4f0752018-04-02 16:31:36 -0700605std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
606 std::string output = "streams=[";
607 const char* separator = "";
608 for (const auto& stream_id : stream_ids) {
609 output.append(separator).append(stream_id);
610 separator = ", ";
611 }
612 output.append("]");
613 return output;
614}
615
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 int rtc_configuration_parameter) {
618 if (rtc_configuration_parameter ==
619 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200620 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700621 }
622 return rtc_configuration_parameter;
623}
624
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800625cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
626 switch (type) {
627 case DataMessageType::kText:
628 return cricket::DMT_TEXT;
629 case DataMessageType::kBinary:
630 return cricket::DMT_BINARY;
631 case DataMessageType::kControl:
632 return cricket::DMT_CONTROL;
633 default:
634 return cricket::DMT_NONE;
635 }
636 return cricket::DMT_NONE;
637}
638
639DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
640 switch (type) {
641 case cricket::DMT_TEXT:
642 return DataMessageType::kText;
643 case cricket::DMT_BINARY:
644 return DataMessageType::kBinary;
645 case cricket::DMT_CONTROL:
646 return DataMessageType::kControl;
647 case cricket::DMT_NONE:
648 default:
649 RTC_NOTREACHED();
650 }
651 return DataMessageType::kControl;
652}
653
Steve Anton75737c02017-11-06 10:37:17 -0800654} // namespace
655
Henrik Boström31638672017-11-23 17:48:32 +0100656// Upon completion, posts a task to execute the callback of the
657// SetSessionDescriptionObserver asynchronously on the same thread. At this
658// point, the state of the peer connection might no longer reflect the effects
659// of the SetRemoteDescription operation, as the peer connection could have been
660// modified during the post.
661// TODO(hbos): Remove this class once we remove the version of
662// PeerConnectionInterface::SetRemoteDescription() that takes a
663// SetSessionDescriptionObserver as an argument.
664class PeerConnection::SetRemoteDescriptionObserverAdapter
665 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
666 public:
667 SetRemoteDescriptionObserverAdapter(
668 rtc::scoped_refptr<PeerConnection> pc,
669 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
670 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
671
672 // SetRemoteDescriptionObserverInterface implementation.
673 void OnSetRemoteDescriptionComplete(RTCError error) override {
674 if (error.ok())
675 pc_->PostSetSessionDescriptionSuccess(wrapper_);
676 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100677 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100678 }
679
680 private:
681 rtc::scoped_refptr<PeerConnection> pc_;
682 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
683};
684
deadbeef293e9262017-01-11 12:28:30 -0800685bool PeerConnectionInterface::RTCConfiguration::operator==(
686 const PeerConnectionInterface::RTCConfiguration& o) const {
687 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700688 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800689 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000690 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700691 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800692 BundlePolicy bundle_policy;
693 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700694 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
695 int ice_candidate_pool_size;
696 bool disable_ipv6;
697 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700698 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100699 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200701 absl::optional<int> screencast_min_bitrate;
702 absl::optional<bool> combined_audio_video_bwe;
703 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800704 TcpCandidatePolicy tcp_candidate_policy;
705 CandidateNetworkPolicy candidate_network_policy;
706 int audio_jitter_buffer_max_packets;
707 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100708 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800709 int ice_connection_receiving_timeout;
710 int ice_backup_candidate_pair_ping_interval;
711 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800712 bool prioritize_most_likely_ice_candidate_pairs;
713 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800714 bool prune_turn_ports;
715 bool presume_writable_when_fully_relayed;
716 bool enable_ice_renomination;
717 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200718 absl::optional<int> ice_check_interval_strong_connectivity;
719 absl::optional<int> ice_check_interval_weak_connectivity;
720 absl::optional<int> ice_check_min_interval;
721 absl::optional<int> ice_unwritable_timeout;
722 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800723 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200724 absl::optional<int> stun_candidate_keepalive_interval;
725 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200726 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800727 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200728 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700729 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700730 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700731 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700732 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100733 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800734 };
735 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
736 "Did you add something to RTCConfiguration and forget to "
737 "update operator==?");
738 return type == o.type && servers == o.servers &&
739 bundle_policy == o.bundle_policy &&
740 rtcp_mux_policy == o.rtcp_mux_policy &&
741 tcp_candidate_policy == o.tcp_candidate_policy &&
742 candidate_network_policy == o.candidate_network_policy &&
743 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
744 audio_jitter_buffer_fast_accelerate ==
745 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100746 audio_jitter_buffer_min_delay_ms ==
747 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800748 ice_connection_receiving_timeout ==
749 o.ice_connection_receiving_timeout &&
750 ice_backup_candidate_pair_ping_interval ==
751 o.ice_backup_candidate_pair_ping_interval &&
752 continual_gathering_policy == o.continual_gathering_policy &&
753 certificates == o.certificates &&
754 prioritize_most_likely_ice_candidate_pairs ==
755 o.prioritize_most_likely_ice_candidate_pairs &&
756 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800757 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700758 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100759 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800760 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800761 screencast_min_bitrate == o.screencast_min_bitrate &&
762 combined_audio_video_bwe == o.combined_audio_video_bwe &&
763 enable_dtls_srtp == o.enable_dtls_srtp &&
764 ice_candidate_pool_size == o.ice_candidate_pool_size &&
765 prune_turn_ports == o.prune_turn_ports &&
766 presume_writable_when_fully_relayed ==
767 o.presume_writable_when_fully_relayed &&
768 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800769 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800770 ice_check_interval_strong_connectivity ==
771 o.ice_check_interval_strong_connectivity &&
772 ice_check_interval_weak_connectivity ==
773 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700774 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700775 ice_unwritable_timeout == o.ice_unwritable_timeout &&
776 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800777 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800778 stun_candidate_keepalive_interval ==
779 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200780 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800781 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800782 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700783 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700784 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700785 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700786 use_media_transport_for_data_channels ==
787 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100788 crypto_options == o.crypto_options &&
789 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800790}
791
792bool PeerConnectionInterface::RTCConfiguration::operator!=(
793 const PeerConnectionInterface::RTCConfiguration& o) const {
794 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800795}
796
zhihuang8f65cdf2016-05-06 18:40:30 -0700797// Generate a RTCP CNAME when a PeerConnection is created.
798std::string GenerateRtcpCname() {
799 std::string cname;
800 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100801 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800802 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700803 }
804 return cname;
805}
806
zhihuang1c378ed2017-08-17 14:10:50 -0700807bool ValidateOfferAnswerOptions(
808 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
809 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
810 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700811}
812
zhihuang1c378ed2017-08-17 14:10:50 -0700813// From |rtc_options|, fill parts of |session_options| shared by all generated
814// m= sections (in other words, nothing that involves a map/array).
815void ExtractSharedMediaSessionOptions(
816 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
817 cricket::MediaSessionOptions* session_options) {
818 session_options->vad_enabled = rtc_options.voice_activity_detection;
819 session_options->bundle_enabled = rtc_options.use_rtp_mux;
820}
zhihuanga77e6bb2017-08-14 18:17:48 -0700821
zhihuang38ede132017-06-15 12:52:32 -0700822PeerConnection::PeerConnection(PeerConnectionFactory* factory,
823 std::unique_ptr<RtcEventLog> event_log,
824 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700826 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700827 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700828 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700829 remote_streams_(StreamCollection::Create()),
830 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831
832PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100833 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800834 RTC_DCHECK_RUN_ON(signaling_thread());
835
Steve Anton8af21862017-12-15 11:20:13 -0800836 // Need to stop transceivers before destroying the stats collector because
837 // AudioRtpSender has a reference to the StatsCollector it will update when
838 // stopping.
839 for (auto transceiver : transceivers_) {
840 transceiver->Stop();
841 }
Steve Anton4171afb2017-11-20 10:20:22 -0800842
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700843 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800844 if (stats_collector_) {
845 stats_collector_->WaitForPendingRequest();
846 stats_collector_ = nullptr;
847 }
Steve Anton75737c02017-11-06 10:37:17 -0800848
Steve Anton8af21862017-12-15 11:20:13 -0800849 // Don't destroy BaseChannels until after stats has been cleaned up so that
850 // the last stats request can still read from the channels.
851 DestroyAllChannels();
852
Mirko Bonadei675513b2017-11-09 11:09:25 +0100853 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800854
855 webrtc_session_desc_factory_.reset();
856 sctp_invoker_.reset();
857 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800858 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800859 transport_controller_.reset();
860
deadbeef91dd5672016-05-18 16:55:30 -0700861 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700862 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700863 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700864 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700865 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700866 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800867 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700868 event_log_.reset();
869 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870}
871
Steve Anton8af21862017-12-15 11:20:13 -0800872void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800873 // Destroy video channels first since they may have a pointer to a voice
874 // channel.
875 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800876 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800877 DestroyTransceiverChannel(transceiver);
878 }
879 }
880 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800881 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800882 DestroyTransceiverChannel(transceiver);
883 }
884 }
885 DestroyDataChannel();
886}
887
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000889 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700890 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100891 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700892
893 RTCError config_error = ValidateConfiguration(configuration);
894 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700896 return false;
897 }
898
Benjamin Wrightcab58882018-05-02 15:12:47 -0700899 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100900 RTC_LOG(LS_ERROR)
901 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100902 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800903 return false;
904 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200905
Benjamin Wrightcab58882018-05-02 15:12:47 -0700906 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800907 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100908 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100909 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800910 return false;
911 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700912
Benjamin Wrightcab58882018-05-02 15:12:47 -0700913 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700914 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700915 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700916 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800917
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200918 cricket::ServerAddresses stun_servers;
919 std::vector<cricket::RelayServerConfig> turn_servers;
920
921 RTCErrorType parse_error =
922 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
923 if (parse_error != RTCErrorType::NONE) {
924 return false;
925 }
926
deadbeef91dd5672016-05-18 16:55:30 -0700927 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700928 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700929 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200930 RTC_FROM_HERE,
931 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
932 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933 return false;
934 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200935 // If initialization was successful, note if STUN or TURN servers
936 // were supplied.
937 if (!stun_servers.empty()) {
938 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
939 }
940 if (!turn_servers.empty()) {
941 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
942 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700944 // Send information about IPv4/IPv6 status.
945 PeerConnectionAddressFamilyCounter address_family;
946 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
947 address_family = kPeerConnection_IPv6;
948 } else {
949 address_family = kPeerConnection_IPv4;
950 }
951 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
952 kPeerConnectionAddressFamilyCounter_Max);
953
Zhi Huange830e682018-03-30 10:48:35 -0700954 const PeerConnectionFactoryInterface::Options& options = factory_->options();
955
Steve Anton75737c02017-11-06 10:37:17 -0800956 // RFC 3264: The numeric value of the session id and version in the
957 // o line MUST be representable with a "64 bit signed integer".
958 // Due to this constraint session id |session_id_| is max limited to
959 // LLONG_MAX.
960 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700961 JsepTransportController::Config config;
962 config.redetermine_role_on_ice_restart =
963 configuration.redetermine_role_on_ice_restart;
964 config.ssl_max_version = factory_->options().ssl_max_version;
965 config.disable_encryption = options.disable_encryption;
966 config.bundle_policy = configuration.bundle_policy;
967 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700968 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
969 // stub.
970 config.crypto_options = configuration.crypto_options.has_value()
971 ? *configuration.crypto_options
972 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700973 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700974 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700975#if defined(ENABLE_EXTERNAL_AUTH)
976 config.enable_external_auth = true;
977#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700978 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700979
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700980 if (configuration.use_media_transport ||
981 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700982 if (!factory_->media_transport_factory()) {
983 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700984 << "PeerConnecton is initialized with use_media_transport = true or "
985 << "use_media_transport_for_data_channels = true "
986 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700987 return false;
988 }
989
990 config.media_transport_factory = factory_->media_transport_factory();
991 }
992
Zhi Huange830e682018-03-30 10:48:35 -0700993 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700994 signaling_thread(), network_thread(), port_allocator_.get(),
995 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700996 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +0000997 this, &PeerConnection::OnTransportControllerConnectionState);
998 transport_controller_->SignalStandardizedIceConnectionState.connect(
999 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001000 transport_controller_->SignalConnectionState.connect(
1001 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001002 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001003 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001004 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001005 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001006 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001007 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1008 transport_controller_->SignalDtlsHandshakeError.connect(
1009 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1010
1011 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001012
deadbeefab9b2d12015-10-14 11:33:11 -07001013 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001014 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015
Steve Antonba818672017-11-06 10:21:57 -08001016 configuration_ = configuration;
1017
Steve Anton75737c02017-11-06 10:37:17 -08001018 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1019 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1020 if (!configuration.certificates.empty()) {
1021 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1022 // just picking the first one. The decision should be made based on the DTLS
1023 // handshake. The DTLS negotiations need to know about all certificates.
1024 certificate = configuration.certificates[0];
1025 }
1026
Steve Antond25da372017-11-06 14:50:29 -08001027 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001028
1029 if (options.disable_encryption) {
1030 dtls_enabled_ = false;
1031 } else {
1032 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001033 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001034 // |configuration| can override the default |dtls_enabled_| value.
1035 if (configuration.enable_dtls_srtp) {
1036 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1037 }
1038 }
1039
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001040 if (configuration.use_media_transport_for_data_channels) {
1041 if (configuration.enable_rtp_data_channel) {
1042 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1043 "use_media_transport_for_data_channels are "
1044 "incompatible and cannot both be set to true";
1045 return false;
1046 }
1047 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1048 } else if (configuration.enable_rtp_data_channel) {
1049 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1050 // set. It takes precendence over the disable_sctp_data_channels
1051 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001052 data_channel_type_ = cricket::DCT_RTP;
1053 } else {
1054 // DTLS has to be enabled to use SCTP.
1055 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1056 data_channel_type_ = cricket::DCT_SCTP;
1057 }
1058 }
1059
1060 video_options_.screencast_min_bitrate_kbps =
1061 configuration.screencast_min_bitrate;
1062 audio_options_.combined_audio_video_bwe =
1063 configuration.combined_audio_video_bwe;
1064
1065 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001066 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001067
1068 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001069 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001070
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001071 audio_options_.audio_jitter_buffer_min_delay_ms =
1072 configuration.audio_jitter_buffer_min_delay_ms;
1073
Steve Anton75737c02017-11-06 10:37:17 -08001074 // Whether the certificate generator/certificate is null or not determines
1075 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1076 // the right instructions by clearing the variables if needed.
1077 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001078 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001079 certificate = nullptr;
1080 } else if (certificate) {
1081 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001082 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001083 }
1084
1085 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1086 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001087 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001088 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1089 this, &PeerConnection::OnCertificateReady);
1090
1091 if (options.disable_encryption) {
1092 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1093 }
1094
1095 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001096 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001097 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098
Steve Anton4171afb2017-11-20 10:20:22 -08001099 // Add default audio/video transceivers for Plan B SDP.
1100 if (!IsUnifiedPlan()) {
1101 transceivers_.push_back(
1102 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1103 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1104 transceivers_.push_back(
1105 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1106 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1107 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001108 int delay_ms =
1109 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001110 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1111 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 return true;
1113}
1114
Steve Anton038834f2017-07-14 15:59:59 -07001115RTCError PeerConnection::ValidateConfiguration(
1116 const RTCConfiguration& config) const {
1117 if (config.ice_regather_interval_range &&
1118 config.continual_gathering_policy == GATHER_ONCE) {
1119 return RTCError(RTCErrorType::INVALID_PARAMETER,
1120 "ice_regather_interval_range specified but continual "
1121 "gathering policy is GATHER_ONCE");
1122 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001123 auto result =
1124 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1125 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001126}
1127
Yves Gerey665174f2018-06-19 15:03:05 +02001128rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001129 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1130 "Plan SdpSemantics. Please use GetSenders "
1131 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001132 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133}
1134
Yves Gerey665174f2018-06-19 15:03:05 +02001135rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001136 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1137 "Plan SdpSemantics. Please use GetReceivers "
1138 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001139 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001140}
1141
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001142bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001143 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1144 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001145 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146 if (IsClosed()) {
1147 return false;
1148 }
deadbeefab9b2d12015-10-14 11:33:11 -07001149 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001150 return false;
1151 }
deadbeefab9b2d12015-10-14 11:33:11 -07001152
1153 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001154 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1155 observer->SignalAudioTrackAdded.connect(this,
1156 &PeerConnection::OnAudioTrackAdded);
1157 observer->SignalAudioTrackRemoved.connect(
1158 this, &PeerConnection::OnAudioTrackRemoved);
1159 observer->SignalVideoTrackAdded.connect(this,
1160 &PeerConnection::OnVideoTrackAdded);
1161 observer->SignalVideoTrackRemoved.connect(
1162 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001163 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001164
deadbeefab9b2d12015-10-14 11:33:11 -07001165 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001166 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001167 }
1168 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001169 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001170 }
1171
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001172 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001173 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174 return true;
1175}
1176
1177void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001178 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1179 "Plan SdpSemantics. Please use RemoveTrack "
1180 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001181 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001182 if (!IsClosed()) {
1183 for (const auto& track : local_stream->GetAudioTracks()) {
1184 RemoveAudioTrack(track.get(), local_stream);
1185 }
1186 for (const auto& track : local_stream->GetVideoTracks()) {
1187 RemoveVideoTrack(track.get(), local_stream);
1188 }
deadbeefab9b2d12015-10-14 11:33:11 -07001189 }
deadbeefab9b2d12015-10-14 11:33:11 -07001190 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001191 stream_observers_.erase(
1192 std::remove_if(
1193 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001194 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001195 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001196 }),
1197 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001198
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001199 if (IsClosed()) {
1200 return;
1201 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001202 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203}
1204
Steve Anton2d6c76a2018-01-05 17:10:52 -08001205RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001206 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001207 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001208 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001209 if (!track) {
1210 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1211 }
1212 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1213 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1215 "Track has invalid kind: " + track->kind());
1216 }
Steve Antonf9381f02017-12-14 10:23:57 -08001217 if (IsClosed()) {
1218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1219 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001220 }
Steve Anton4171afb2017-11-20 10:20:22 -08001221 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001222 LOG_AND_RETURN_ERROR(
1223 RTCErrorType::INVALID_PARAMETER,
1224 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001225 }
Steve Antonf9381f02017-12-14 10:23:57 -08001226 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001227 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1228 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001229 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001230 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001231 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001232 }
1233 return sender_or_error;
1234}
deadbeefe1f9d832016-01-14 15:35:42 -08001235
Steve Antonf9381f02017-12-14 10:23:57 -08001236RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1237PeerConnection::AddTrackPlanB(
1238 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001239 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001240 if (stream_ids.size() > 1u) {
1241 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1242 "AddTrack with more than one stream is not "
1243 "supported with Plan B semantics.");
1244 }
1245 std::vector<std::string> adjusted_stream_ids = stream_ids;
1246 if (adjusted_stream_ids.empty()) {
1247 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1248 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001249 cricket::MediaType media_type =
1250 (track->kind() == MediaStreamTrackInterface::kAudioKind
1251 ? cricket::MEDIA_TYPE_AUDIO
1252 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001253 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001254 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001255 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001256 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001257 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001258 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001259 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001260 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001261 if (sender_info) {
1262 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001263 }
Steve Antonf9381f02017-12-14 10:23:57 -08001264 } else {
1265 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001266 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001267 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001268 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001269 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001270 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001271 if (sender_info) {
1272 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001273 }
deadbeefe1f9d832016-01-14 15:35:42 -08001274 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001275 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001276}
deadbeefe1f9d832016-01-14 15:35:42 -08001277
Steve Antonf9381f02017-12-14 10:23:57 -08001278RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1279PeerConnection::AddTrackUnifiedPlan(
1280 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001281 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001282 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1283 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001284 RTC_LOG(LS_INFO) << "Reusing an existing "
1285 << cricket::MediaTypeToString(transceiver->media_type())
1286 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001287 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001288 transceiver->internal()->set_direction(
1289 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001290 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001291 transceiver->internal()->set_direction(
1292 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001293 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001294 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001295 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001296 } else {
1297 cricket::MediaType media_type =
1298 (track->kind() == MediaStreamTrackInterface::kAudioKind
1299 ? cricket::MEDIA_TYPE_AUDIO
1300 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001301 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1302 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001303 std::string sender_id = track->id();
1304 // Avoid creating a sender with an existing ID by generating a random ID.
1305 // This can happen if this is the second time AddTrack has created a sender
1306 // for this track.
1307 if (FindSenderById(sender_id)) {
1308 sender_id = rtc::CreateRandomUuid();
1309 }
Florent Castelli892acf02018-10-01 22:47:20 +02001310 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001311 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1312 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001313 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001314 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001315 }
Steve Antonf9381f02017-12-14 10:23:57 -08001316 return transceiver->sender();
1317}
1318
1319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1320PeerConnection::FindFirstTransceiverForAddedTrack(
1321 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1322 RTC_DCHECK(track);
1323 for (auto transceiver : transceivers_) {
1324 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001325 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001326 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001327 !transceiver->internal()->has_ever_been_used_to_send() &&
1328 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001329 return transceiver;
1330 }
1331 }
1332 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001333}
1334
1335bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1336 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001337 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001338}
1339
Steve Anton24db5732018-07-23 10:27:33 -07001340RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001341 rtc::scoped_refptr<RtpSenderInterface> sender) {
1342 if (!sender) {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1344 }
deadbeefe1f9d832016-01-14 15:35:42 -08001345 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1347 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001348 }
Steve Antonf9381f02017-12-14 10:23:57 -08001349 if (IsUnifiedPlan()) {
1350 auto transceiver = FindTransceiverBySender(sender);
1351 if (!transceiver || !sender->track()) {
1352 return RTCError::OK();
1353 }
1354 sender->SetTrack(nullptr);
1355 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001356 transceiver->internal()->set_direction(
1357 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001358 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001359 transceiver->internal()->set_direction(
1360 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001361 }
Steve Anton4171afb2017-11-20 10:20:22 -08001362 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001363 bool removed;
1364 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1365 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1366 } else {
1367 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1368 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1369 }
1370 if (!removed) {
1371 LOG_AND_RETURN_ERROR(
1372 RTCErrorType::INVALID_PARAMETER,
1373 "Couldn't find sender " + sender->id() + " to remove.");
1374 }
Steve Anton4171afb2017-11-20 10:20:22 -08001375 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001376 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001377 return RTCError::OK();
1378}
1379
1380rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1381PeerConnection::FindTransceiverBySender(
1382 rtc::scoped_refptr<RtpSenderInterface> sender) {
1383 for (auto transceiver : transceivers_) {
1384 if (transceiver->sender() == sender) {
1385 return transceiver;
1386 }
1387 }
1388 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001389}
1390
Steve Anton9158ef62017-11-27 13:01:52 -08001391RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1392PeerConnection::AddTransceiver(
1393 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1394 return AddTransceiver(track, RtpTransceiverInit());
1395}
1396
1397RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1398PeerConnection::AddTransceiver(
1399 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1400 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001401 RTC_CHECK(IsUnifiedPlan())
1402 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001403 if (!track) {
1404 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1405 }
1406 cricket::MediaType media_type;
1407 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1408 media_type = cricket::MEDIA_TYPE_AUDIO;
1409 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1410 media_type = cricket::MEDIA_TYPE_VIDEO;
1411 } else {
1412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1413 "Track kind is not audio or video");
1414 }
1415 return AddTransceiver(media_type, track, init);
1416}
1417
1418RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1419PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1420 return AddTransceiver(media_type, RtpTransceiverInit());
1421}
1422
1423RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1424PeerConnection::AddTransceiver(cricket::MediaType media_type,
1425 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001426 RTC_CHECK(IsUnifiedPlan())
1427 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001428 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1429 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1431 "media type is not audio or video");
1432 }
1433 return AddTransceiver(media_type, nullptr, init);
1434}
1435
1436RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1437PeerConnection::AddTransceiver(
1438 cricket::MediaType media_type,
1439 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001440 const RtpTransceiverInit& init,
1441 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001442 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1443 media_type == cricket::MEDIA_TYPE_VIDEO));
1444 if (track) {
1445 RTC_DCHECK_EQ(media_type,
1446 (track->kind() == MediaStreamTrackInterface::kAudioKind
1447 ? cricket::MEDIA_TYPE_AUDIO
1448 : cricket::MEDIA_TYPE_VIDEO));
1449 }
1450
1451 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001452 if (init.send_encodings.size() > 1) {
1453 LOG_AND_RETURN_ERROR(
1454 RTCErrorType::UNSUPPORTED_PARAMETER,
1455 "Attempted to create an encoder with more than 1 encoding parameter.");
1456 }
1457
1458 for (const auto& encoding : init.send_encodings) {
1459 if (encoding.ssrc.has_value()) {
1460 LOG_AND_RETURN_ERROR(
1461 RTCErrorType::UNSUPPORTED_PARAMETER,
1462 "Attempted to set an unimplemented parameter of RtpParameters.");
1463 }
1464 }
1465
1466 RtpParameters parameters;
1467 parameters.encodings = init.send_encodings;
1468 if (UnimplementedRtpParameterHasValue(parameters)) {
1469 LOG_AND_RETURN_ERROR(
1470 RTCErrorType::UNSUPPORTED_PARAMETER,
1471 "Attempted to set an unimplemented parameter of RtpParameters.");
1472 }
Steve Anton9158ef62017-11-27 13:01:52 -08001473
Steve Anton3d954a62018-04-02 11:27:23 -07001474 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1475 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001476 // Set the sender ID equal to the track ID if the track is specified unless
1477 // that sender ID is already in use.
1478 std::string sender_id =
1479 (track && !FindSenderById(track->id()) ? track->id()
1480 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001481 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1482 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001483 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1484 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1485 transceiver->internal()->set_direction(init.direction);
1486
Steve Anton22da89f2018-01-25 13:58:07 -08001487 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001488 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001489 }
Steve Antonf9381f02017-12-14 10:23:57 -08001490
1491 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1492}
1493
Steve Anton02ee47c2018-01-10 16:26:06 -08001494rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1495PeerConnection::CreateSender(
1496 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001497 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001498 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001499 const std::vector<std::string>& stream_ids,
1500 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001501 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001502 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1503 RTC_DCHECK(!track ||
1504 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1505 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1506 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001507 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001508 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001509 } else {
1510 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1511 RTC_DCHECK(!track ||
1512 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1513 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001514 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001515 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001516 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001517 bool set_track_succeeded = sender->SetTrack(track);
1518 RTC_DCHECK(set_track_succeeded);
1519 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001520 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001521 return sender;
1522}
1523
1524rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1525PeerConnection::CreateReceiver(cricket::MediaType media_type,
1526 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001527 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1528 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001529 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001530 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001531 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1532 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001533 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001534 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001535 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001536 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001537 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1538 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001539 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001540 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001541 return receiver;
1542}
1543
1544rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1545PeerConnection::CreateAndAddTransceiver(
1546 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1547 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1548 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001549 // Ensure that the new sender does not have an ID that is already in use by
1550 // another sender.
1551 // Allow receiver IDs to conflict since those come from remote SDP (which
1552 // could be invalid, but should not cause a crash).
1553 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001554 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1555 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001556 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001557 transceiver->internal()->SignalNegotiationNeeded.connect(
1558 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001559 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001560}
1561
Steve Anton52d86772018-02-20 15:48:12 -08001562void PeerConnection::OnNegotiationNeeded() {
1563 RTC_DCHECK_RUN_ON(signaling_thread());
1564 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001565 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001566}
1567
deadbeeffac06552015-11-25 11:26:01 -08001568rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001569 const std::string& kind,
1570 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001571 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1572 "Plan SdpSemantics. Please use AddTransceiver "
1573 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001574 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001575 if (IsClosed()) {
1576 return nullptr;
1577 }
Steve Anton4171afb2017-11-20 10:20:22 -08001578
Seth Hampson5b4f0752018-04-02 16:31:36 -07001579 // Internally we need to have one stream with Plan B semantics, so we
1580 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001581 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001582 if (stream_id.empty()) {
1583 stream_ids.push_back(rtc::CreateRandomUuid());
1584 RTC_LOG(LS_INFO)
1585 << "No stream_id specified for sender. Generated stream ID: "
1586 << stream_ids[0];
1587 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001588 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001589 }
1590
Steve Anton4171afb2017-11-20 10:20:22 -08001591 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001592 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001593 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001594 auto* audio_sender = new AudioRtpSender(
1595 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001596 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001597 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001598 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001599 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001600 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001601 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001602 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001603 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001604 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001605 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001606 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001607 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001608 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001609 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001610 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001611 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001612
deadbeefe1f9d832016-01-14 15:35:42 -08001613 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001614}
1615
deadbeef70ab1a12015-09-28 16:53:55 -07001616std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1617 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001618 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001619 for (auto sender : GetSendersInternal()) {
1620 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001621 }
1622 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001623}
1624
Steve Anton4171afb2017-11-20 10:20:22 -08001625std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1626PeerConnection::GetSendersInternal() const {
1627 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1628 all_senders;
1629 for (auto transceiver : transceivers_) {
1630 auto senders = transceiver->internal()->senders();
1631 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1632 }
1633 return all_senders;
1634}
1635
deadbeef70ab1a12015-09-28 16:53:55 -07001636std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1637PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001638 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001639 for (const auto& receiver : GetReceiversInternal()) {
1640 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001641 }
1642 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001643}
1644
Steve Anton4171afb2017-11-20 10:20:22 -08001645std::vector<
1646 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1647PeerConnection::GetReceiversInternal() const {
1648 std::vector<
1649 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1650 all_receivers;
1651 for (auto transceiver : transceivers_) {
1652 auto receivers = transceiver->internal()->receivers();
1653 all_receivers.insert(all_receivers.end(), receivers.begin(),
1654 receivers.end());
1655 }
1656 return all_receivers;
1657}
1658
Steve Anton9158ef62017-11-27 13:01:52 -08001659std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1660PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001661 RTC_CHECK(IsUnifiedPlan())
1662 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001663 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1664 for (auto transceiver : transceivers_) {
1665 all_transceivers.push_back(transceiver);
1666 }
1667 return all_transceivers;
1668}
1669
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001670bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001671 MediaStreamTrackInterface* track,
1672 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001673 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001674 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001675 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001676 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001677 return false;
1678 }
1679
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001680 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001681 // The StatsCollector is used to tell if a track is valid because it may
1682 // remember tracks that the PeerConnection previously removed.
1683 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001684 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1685 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001686 return false;
1687 }
Steve Antonad182762018-09-05 20:22:40 +00001688 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1689 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690 return true;
1691}
1692
hbos74e1a4f2016-09-15 23:33:01 -07001693void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001694 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001695 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001696 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001697 stats_collector_->GetStatsReport(callback);
1698}
1699
Henrik Boström1df1bf82018-03-20 13:24:20 +01001700void PeerConnection::GetStats(
1701 rtc::scoped_refptr<RtpSenderInterface> selector,
1702 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1703 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1704 RTC_DCHECK(callback);
1705 RTC_DCHECK(stats_collector_);
1706 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1707 if (selector) {
1708 for (const auto& proxy_transceiver : transceivers_) {
1709 for (const auto& proxy_sender :
1710 proxy_transceiver->internal()->senders()) {
1711 if (proxy_sender == selector) {
1712 internal_sender = proxy_sender->internal();
1713 break;
1714 }
1715 }
1716 if (internal_sender)
1717 break;
1718 }
1719 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001720 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001721 // belong to the PeerConnection (in Plan B, senders can be removed from the
1722 // PeerConnection). This means that "all the stats objects representing the
1723 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1724 // produces an empty stats report.
1725 stats_collector_->GetStatsReport(internal_sender, callback);
1726}
1727
1728void PeerConnection::GetStats(
1729 rtc::scoped_refptr<RtpReceiverInterface> selector,
1730 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1731 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1732 RTC_DCHECK(callback);
1733 RTC_DCHECK(stats_collector_);
1734 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1735 if (selector) {
1736 for (const auto& proxy_transceiver : transceivers_) {
1737 for (const auto& proxy_receiver :
1738 proxy_transceiver->internal()->receivers()) {
1739 if (proxy_receiver == selector) {
1740 internal_receiver = proxy_receiver->internal();
1741 break;
1742 }
1743 }
1744 if (internal_receiver)
1745 break;
1746 }
1747 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001748 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001749 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1750 // the PeerConnection). This means that "all the stats objects representing
1751 // the selector" is an empty set. Invoking GetStatsReport() with a null
1752 // selector produces an empty stats report.
1753 stats_collector_->GetStatsReport(internal_receiver, callback);
1754}
1755
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001756PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1757 return signaling_state_;
1758}
1759
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001760PeerConnectionInterface::IceConnectionState
1761PeerConnection::ice_connection_state() {
1762 return ice_connection_state_;
1763}
1764
Alex Loiko9289eda2018-11-23 16:18:59 +00001765PeerConnectionInterface::IceConnectionState
1766PeerConnection::standardized_ice_connection_state() {
1767 return standardized_ice_connection_state_;
1768}
1769
Jonas Olsson635474e2018-10-18 15:58:17 +02001770PeerConnectionInterface::PeerConnectionState
1771PeerConnection::peer_connection_state() {
1772 return connection_state_;
1773}
1774
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775PeerConnectionInterface::IceGatheringState
1776PeerConnection::ice_gathering_state() {
1777 return ice_gathering_state_;
1778}
1779
Yves Gerey665174f2018-06-19 15:03:05 +02001780rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001781 const std::string& label,
1782 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001783 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001784
deadbeefab9b2d12015-10-14 11:33:11 -07001785 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001786
kwibergd1fe2812016-04-27 06:47:29 -07001787 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001788 if (config) {
1789 internal_config.reset(new InternalDataChannelInit(*config));
1790 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001791 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001792 InternalCreateDataChannel(label, internal_config.get()));
1793 if (!channel.get()) {
1794 return nullptr;
1795 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001797 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1798 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001799 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001800 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001801 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001802 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 return DataChannelProxy::Create(signaling_thread(), channel.get());
1804}
1805
1806void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001807 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001808 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001809
nisse7ce109a2017-01-31 00:57:56 -08001810 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001811 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001812 return;
1813 }
deadbeefab9b2d12015-10-14 11:33:11 -07001814
Steve Anton8d3444d2017-10-20 15:30:51 -07001815 if (IsClosed()) {
1816 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001817 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001818 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001819 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001820 return;
1821 }
1822
zhihuang1c378ed2017-08-17 14:10:50 -07001823 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001824 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001825 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001826 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001827 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001828 return;
1829 }
1830
Steve Anton22da89f2018-01-25 13:58:07 -08001831 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1832 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1833 if (IsUnifiedPlan()) {
1834 RTCError error = HandleLegacyOfferOptions(options);
1835 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001836 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001837 return;
1838 }
1839 }
1840
zhihuang1c378ed2017-08-17 14:10:50 -07001841 cricket::MediaSessionOptions session_options;
1842 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001843 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844}
1845
Steve Anton22da89f2018-01-25 13:58:07 -08001846RTCError PeerConnection::HandleLegacyOfferOptions(
1847 const RTCOfferAnswerOptions& options) {
1848 RTC_DCHECK(IsUnifiedPlan());
1849
1850 if (options.offer_to_receive_audio == 0) {
1851 RemoveRecvDirectionFromReceivingTransceiversOfType(
1852 cricket::MEDIA_TYPE_AUDIO);
1853 } else if (options.offer_to_receive_audio == 1) {
1854 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1855 } else if (options.offer_to_receive_audio > 1) {
1856 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1857 "offer_to_receive_audio > 1 is not supported.");
1858 }
1859
1860 if (options.offer_to_receive_video == 0) {
1861 RemoveRecvDirectionFromReceivingTransceiversOfType(
1862 cricket::MEDIA_TYPE_VIDEO);
1863 } else if (options.offer_to_receive_video == 1) {
1864 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1865 } else if (options.offer_to_receive_video > 1) {
1866 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1867 "offer_to_receive_video > 1 is not supported.");
1868 }
1869
1870 return RTCError::OK();
1871}
1872
1873void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1874 cricket::MediaType media_type) {
1875 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001876 RtpTransceiverDirection new_direction =
1877 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1878 if (new_direction != transceiver->direction()) {
1879 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1880 << " transceiver (MID="
1881 << transceiver->mid().value_or("<not set>") << ") from "
1882 << RtpTransceiverDirectionToString(
1883 transceiver->direction())
1884 << " to "
1885 << RtpTransceiverDirectionToString(new_direction)
1886 << " since CreateOffer specified offer_to_receive=0";
1887 transceiver->internal()->set_direction(new_direction);
1888 }
Steve Anton22da89f2018-01-25 13:58:07 -08001889 }
1890}
1891
1892void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1893 cricket::MediaType media_type) {
1894 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001895 RTC_LOG(LS_INFO)
1896 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1897 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001898 RtpTransceiverInit init;
1899 init.direction = RtpTransceiverDirection::kRecvOnly;
1900 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1901 }
1902}
1903
1904std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1905PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1906 std::vector<
1907 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1908 receiving_transceivers;
1909 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001910 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001911 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1912 receiving_transceivers.push_back(transceiver);
1913 }
1914 }
1915 return receiving_transceivers;
1916}
1917
htaa2a49d92016-03-04 02:51:39 -08001918void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1919 const RTCOfferAnswerOptions& options) {
1920 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001921 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001922 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001923 return;
1924 }
1925
Steve Antondffead82018-02-06 10:31:29 -08001926 if (!(signaling_state_ == kHaveRemoteOffer ||
1927 signaling_state_ == kHaveLocalPrAnswer)) {
1928 std::string error =
1929 "PeerConnection cannot create an answer in a state other than "
1930 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001931 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001932 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001933 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001934 return;
1935 }
1936
Steve Antondffead82018-02-06 10:31:29 -08001937 // The remote description should be set if we're in the right state.
1938 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001939
Steve Anton22da89f2018-01-25 13:58:07 -08001940 if (IsUnifiedPlan()) {
1941 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1942 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1943 "supported with Unified Plan semantics. Use the "
1944 "RtpTransceiver API instead.";
1945 }
1946 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1947 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1948 "supported with Unified Plan semantics. Use the "
1949 "RtpTransceiver API instead.";
1950 }
1951 }
1952
htaa2a49d92016-03-04 02:51:39 -08001953 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001954 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001955
Steve Antond25da372017-11-06 14:50:29 -08001956 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001957}
1958
1959void PeerConnection::SetLocalDescription(
1960 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001961 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001962 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001963
Steve Anton80dd7b52018-02-16 17:08:42 -08001964 // The SetLocalDescription contract is that we take ownership of the session
1965 // description regardless of the outcome, so wrap it in a unique_ptr right
1966 // away. Ideally, SetLocalDescription's signature will be changed to take the
1967 // description as a unique_ptr argument to formalize this agreement.
1968 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1969
nisse7ce109a2017-01-31 00:57:56 -08001970 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001971 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 return;
1973 }
Steve Anton8a006912017-12-04 15:25:56 -08001974
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001976 PostSetSessionDescriptionFailure(
1977 observer,
1978 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001979 return;
1980 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001981
Steve Anton80dd7b52018-02-16 17:08:42 -08001982 // If a session error has occurred the PeerConnection is in a possibly
1983 // inconsistent state so fail right away.
1984 if (session_error() != SessionError::kNone) {
1985 std::string error_message = GetSessionErrorMsg();
1986 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001987 PostSetSessionDescriptionFailure(
1988 observer,
1989 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001990 return;
1991 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001992
Steve Anton80dd7b52018-02-16 17:08:42 -08001993 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1994 if (!error.ok()) {
1995 std::string error_message = GetSetDescriptionErrorMessage(
1996 cricket::CS_LOCAL, desc->GetType(), error);
1997 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001998 PostSetSessionDescriptionFailure(
1999 observer,
2000 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002001 return;
2002 }
2003
2004 // Grab the description type before moving ownership to ApplyLocalDescription,
2005 // which may destroy it before returning.
2006 const SdpType type = desc->GetType();
2007
2008 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002009 // |desc| may be destroyed at this point.
2010
2011 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002012 // If ApplyLocalDescription fails, the PeerConnection could be in an
2013 // inconsistent state, so act conservatively here and set the session error
2014 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2015 SetSessionError(SessionError::kContent, error.message());
2016 std::string error_message =
2017 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2018 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002019 PostSetSessionDescriptionFailure(
2020 observer,
2021 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002022 return;
2023 }
Steve Anton8a006912017-12-04 15:25:56 -08002024 RTC_DCHECK(local_description());
2025
2026 PostSetSessionDescriptionSuccess(observer);
2027
Steve Antonad182762018-09-05 20:22:40 +00002028 // MaybeStartGathering needs to be called after posting
2029 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2030 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002031 transport_controller_->MaybeStartGathering();
2032
Steve Antona3a92c22017-12-07 10:27:41 -08002033 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002034 // TODO(deadbeef): We already had to hop to the network thread for
2035 // MaybeStartGathering...
2036 network_thread()->Invoke<void>(
2037 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2038 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002039 // Make UMA notes about what was agreed to.
2040 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002041 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002042 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002043}
2044
2045RTCError PeerConnection::ApplyLocalDescription(
2046 std::unique_ptr<SessionDescriptionInterface> desc) {
2047 RTC_DCHECK_RUN_ON(signaling_thread());
2048 RTC_DCHECK(desc);
2049
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002050 // Update stats here so that we have the most recent stats for tracks and
2051 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002052 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002053
Steve Antondcc3c022017-12-22 16:02:54 -08002054 // Take a reference to the old local description since it's used below to
2055 // compare against the new local description. When setting the new local
2056 // description, grab ownership of the replaced session description in case it
2057 // is the same as |old_local_description|, to keep it alive for the duration
2058 // of the method.
2059 const SessionDescriptionInterface* old_local_description =
2060 local_description();
2061 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002062 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002063 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002064 replaced_local_description = pending_local_description_
2065 ? std::move(pending_local_description_)
2066 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002067 current_local_description_ = std::move(desc);
2068 pending_local_description_ = nullptr;
2069 current_remote_description_ = std::move(pending_remote_description_);
2070 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002071 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002072 pending_local_description_ = std::move(desc);
2073 }
2074 // The session description to apply now must be accessed by
2075 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002076 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002077
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002078 if (!is_caller_) {
2079 if (remote_description()) {
2080 // Remote description was applied first, so this PC is the callee.
2081 is_caller_ = false;
2082 } else {
2083 // Local description is applied first, so this PC is the caller.
2084 is_caller_ = true;
2085 }
2086 }
2087
Zhi Huange830e682018-03-30 10:48:35 -07002088 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2089 if (!error.ok()) {
2090 return error;
2091 }
2092
Steve Antondcc3c022017-12-22 16:02:54 -08002093 if (IsUnifiedPlan()) {
2094 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002095 cricket::CS_LOCAL, *local_description(), old_local_description,
2096 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002097 if (!error.ok()) {
2098 return error;
2099 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002100 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2101 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002102 for (auto transceiver : transceivers_) {
2103 const ContentInfo* content =
2104 FindMediaSectionForTransceiver(transceiver, local_description());
2105 if (!content) {
2106 continue;
2107 }
2108 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002109 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2110 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002111 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002112 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2113 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2114 // "recvonly", process the removal of a remote track for the media
2115 // description, given transceiver, removeList, and muteTracks.
2116 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2117 (transceiver->internal()->fired_direction() &&
2118 RtpTransceiverDirectionHasRecv(
2119 *transceiver->internal()->fired_direction()))) {
2120 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2121 &removed_streams);
2122 }
2123 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2124 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002125 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002126 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002127 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002128 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002129 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002130 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002131 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002132 }
2133 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002134 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002135 }
2136 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002137 // Media channels will be created only when offer is set. These may use new
2138 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002139 if (type == SdpType::kOffer) {
2140 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2141 // description is applied. Restore back to old description.
2142 RTCError error = CreateChannels(*local_description()->description());
2143 if (!error.ok()) {
2144 return error;
2145 }
2146 }
Steve Antondcc3c022017-12-22 16:02:54 -08002147 // Remove unused channels if MediaContentDescription is rejected.
2148 RemoveUnusedChannels(local_description()->description());
2149 }
Steve Anton8a006912017-12-04 15:25:56 -08002150
Zhi Huange830e682018-03-30 10:48:35 -07002151 error = UpdateSessionState(type, cricket::CS_LOCAL,
2152 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002153 if (!error.ok()) {
2154 return error;
2155 }
Steve Antondcc3c022017-12-22 16:02:54 -08002156
Steve Anton8a006912017-12-04 15:25:56 -08002157 if (remote_description()) {
2158 // Now that we have a local description, we can push down remote candidates.
2159 UseCandidatesInSessionDescription(remote_description());
2160 }
2161
2162 pending_ice_restarts_.clear();
2163 if (session_error() != SessionError::kNone) {
2164 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2165 }
2166
deadbeefab9b2d12015-10-14 11:33:11 -07002167 // If setting the description decided our SSL role, allocate any necessary
2168 // SCTP sids.
2169 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002170 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002171 AllocateSctpSids(role);
2172 }
2173
Steve Antond3679212018-01-17 17:41:02 -08002174 if (IsUnifiedPlan()) {
2175 for (auto transceiver : transceivers_) {
2176 const ContentInfo* content =
2177 FindMediaSectionForTransceiver(transceiver, local_description());
2178 if (!content) {
2179 continue;
2180 }
Steve Anton74255ff2018-01-24 18:32:57 -08002181 const auto& streams = content->media_description()->streams();
2182 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002183 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002184 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002185 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002186 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002187 } else {
2188 // 0 is a special value meaning "this sender has no associated send
2189 // stream". Need to call this so the sender won't attempt to configure
2190 // a no longer existing stream and run into DCHECKs in the lower
2191 // layers.
2192 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002193 }
2194 }
2195 } else {
2196 // Plan B semantics.
2197
Steve Antondcc3c022017-12-22 16:02:54 -08002198 // Update state and SSRC of local MediaStreams and DataChannels based on the
2199 // local session description.
2200 const cricket::ContentInfo* audio_content =
2201 GetFirstAudioContent(local_description()->description());
2202 if (audio_content) {
2203 if (audio_content->rejected) {
2204 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2205 } else {
2206 const cricket::AudioContentDescription* audio_desc =
2207 audio_content->media_description()->as_audio();
2208 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2209 }
deadbeeffaac4972015-11-12 15:33:07 -08002210 }
deadbeefab9b2d12015-10-14 11:33:11 -07002211
Steve Antondcc3c022017-12-22 16:02:54 -08002212 const cricket::ContentInfo* video_content =
2213 GetFirstVideoContent(local_description()->description());
2214 if (video_content) {
2215 if (video_content->rejected) {
2216 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2217 } else {
2218 const cricket::VideoContentDescription* video_desc =
2219 video_content->media_description()->as_video();
2220 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2221 }
deadbeeffaac4972015-11-12 15:33:07 -08002222 }
deadbeefab9b2d12015-10-14 11:33:11 -07002223 }
2224
2225 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002226 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002227 if (data_content) {
2228 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002229 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002230 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002231 cricket::kMediaProtocolRtpPrefix)) {
2232 UpdateLocalRtpDataChannels(data_desc->streams());
2233 }
2234 }
2235
Steve Anton8a006912017-12-04 15:25:56 -08002236 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002237}
2238
Steve Anton06817cd2018-12-18 15:55:30 -08002239// The SDP parser used to populate these values by default for the 'content
2240// name' if an a=mid line was absent.
2241static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2242 switch (media_type) {
2243 case cricket::MEDIA_TYPE_AUDIO:
2244 return cricket::CN_AUDIO;
2245 case cricket::MEDIA_TYPE_VIDEO:
2246 return cricket::CN_VIDEO;
2247 case cricket::MEDIA_TYPE_DATA:
2248 return cricket::CN_DATA;
2249 }
2250 RTC_NOTREACHED();
2251 return "";
2252}
2253
2254void PeerConnection::FillInMissingRemoteMids(
2255 cricket::SessionDescription* remote_description) {
2256 RTC_DCHECK(remote_description);
2257 const cricket::ContentInfos& local_contents =
2258 (local_description() ? local_description()->description()->contents()
2259 : cricket::ContentInfos());
Steve Anton06817cd2018-12-18 15:55:30 -08002260 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2261 cricket::ContentInfo& content = remote_description->contents()[i];
2262 if (!content.name.empty()) {
2263 continue;
2264 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002265 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002266 absl::string_view source_explanation;
2267 if (IsUnifiedPlan()) {
2268 if (i < local_contents.size()) {
2269 new_mid = local_contents[i].name;
2270 source_explanation = "from the matching local media section";
2271 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002272 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002273 source_explanation = "generated just now";
2274 }
2275 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002276 new_mid = std::string(
2277 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002278 source_explanation = "to match pre-existing behavior";
2279 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002280 content.name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002281 remote_description->transport_infos()[i].content_name =
2282 std::string(new_mid);
2283 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2284 << " is missing an a=mid line. Filling in the value '"
2285 << new_mid << "' " << source_explanation << ".";
2286 }
2287}
2288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002289void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002290 SetSessionDescriptionObserver* observer,
2291 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002292 SetRemoteDescription(
2293 std::unique_ptr<SessionDescriptionInterface>(desc),
2294 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2295 new SetRemoteDescriptionObserverAdapter(this, observer)));
2296}
2297
2298void PeerConnection::SetRemoteDescription(
2299 std::unique_ptr<SessionDescriptionInterface> desc,
2300 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002301 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002302
nisse7ce109a2017-01-31 00:57:56 -08002303 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002304 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002305 return;
2306 }
Steve Anton8a006912017-12-04 15:25:56 -08002307
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002309 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002310 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002311 return;
2312 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002313
Steve Anton80dd7b52018-02-16 17:08:42 -08002314 // If a session error has occurred the PeerConnection is in a possibly
2315 // inconsistent state so fail right away.
2316 if (session_error() != SessionError::kNone) {
2317 std::string error_message = GetSessionErrorMsg();
2318 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2319 observer->OnSetRemoteDescriptionComplete(
2320 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2321 return;
2322 }
Steve Anton71439a62018-02-15 11:53:06 -08002323
Steve Antonba42e992018-04-09 14:10:01 -07002324 if (desc->GetType() == SdpType::kOffer) {
2325 // Report to UMA the format of the received offer.
2326 ReportSdpFormatReceived(*desc);
2327 }
2328
Steve Anton06817cd2018-12-18 15:55:30 -08002329 // Handle remote descriptions missing a=mid lines for interop with legacy end
2330 // points.
2331 FillInMissingRemoteMids(desc->description());
2332
Steve Anton80dd7b52018-02-16 17:08:42 -08002333 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002334 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002335 std::string error_message = GetSetDescriptionErrorMessage(
2336 cricket::CS_REMOTE, desc->GetType(), error);
2337 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002338 observer->OnSetRemoteDescriptionComplete(
2339 RTCError(error.type(), std::move(error_message)));
2340 return;
2341 }
Steve Anton71439a62018-02-15 11:53:06 -08002342
Steve Anton80dd7b52018-02-16 17:08:42 -08002343 // Grab the description type before moving ownership to
2344 // ApplyRemoteDescription, which may destroy it before returning.
2345 const SdpType type = desc->GetType();
2346
2347 error = ApplyRemoteDescription(std::move(desc));
2348 // |desc| may be destroyed at this point.
2349
2350 if (!error.ok()) {
2351 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2352 // inconsistent state, so act conservatively here and set the session error
2353 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2354 SetSessionError(SessionError::kContent, error.message());
2355 std::string error_message =
2356 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2357 RTC_LOG(LS_ERROR) << error_message;
2358 observer->OnSetRemoteDescriptionComplete(
2359 RTCError(error.type(), std::move(error_message)));
2360 return;
2361 }
2362 RTC_DCHECK(remote_description());
2363
2364 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002365 // TODO(deadbeef): We already had to hop to the network thread for
2366 // MaybeStartGathering...
2367 network_thread()->Invoke<void>(
2368 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2369 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002370 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002371 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002372 }
2373
2374 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002375 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002376}
2377
2378RTCError PeerConnection::ApplyRemoteDescription(
2379 std::unique_ptr<SessionDescriptionInterface> desc) {
2380 RTC_DCHECK_RUN_ON(signaling_thread());
2381 RTC_DCHECK(desc);
2382
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002383 // Update stats here so that we have the most recent stats for tracks and
2384 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002385 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002386
Steve Antondcc3c022017-12-22 16:02:54 -08002387 // Take a reference to the old remote description since it's used below to
2388 // compare against the new remote description. When setting the new remote
2389 // description, grab ownership of the replaced session description in case it
2390 // is the same as |old_remote_description|, to keep it alive for the duration
2391 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002392 const SessionDescriptionInterface* old_remote_description =
2393 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002394 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002395 SdpType type = desc->GetType();
2396 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002397 replaced_remote_description = pending_remote_description_
2398 ? std::move(pending_remote_description_)
2399 : std::move(current_remote_description_);
2400 current_remote_description_ = std::move(desc);
2401 pending_remote_description_ = nullptr;
2402 current_local_description_ = std::move(pending_local_description_);
2403 } else {
2404 replaced_remote_description = std::move(pending_remote_description_);
2405 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406 }
Steve Anton8a006912017-12-04 15:25:56 -08002407 // The session description to apply now must be accessed by
2408 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002409 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002410
Zhi Huange830e682018-03-30 10:48:35 -07002411 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2412 if (!error.ok()) {
2413 return error;
2414 }
Steve Anton8a006912017-12-04 15:25:56 -08002415 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002416 if (IsUnifiedPlan()) {
2417 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002418 cricket::CS_REMOTE, *remote_description(), local_description(),
2419 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002420 if (!error.ok()) {
2421 return error;
2422 }
Steve Antondcc3c022017-12-22 16:02:54 -08002423 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002424 // Media channels will be created only when offer is set. These may use new
2425 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002426 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002427 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002428 // description is applied. Restore back to old description.
2429 RTCError error = CreateChannels(*remote_description()->description());
2430 if (!error.ok()) {
2431 return error;
2432 }
2433 }
Steve Antondcc3c022017-12-22 16:02:54 -08002434 // Remove unused channels if MediaContentDescription is rejected.
2435 RemoveUnusedChannels(remote_description()->description());
2436 }
Steve Anton8a006912017-12-04 15:25:56 -08002437
Zhi Huange830e682018-03-30 10:48:35 -07002438 // NOTE: Candidates allocation will be initiated only when
2439 // SetLocalDescription is called.
2440 error = UpdateSessionState(type, cricket::CS_REMOTE,
2441 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002442 if (!error.ok()) {
2443 return error;
2444 }
2445
2446 if (local_description() &&
2447 !UseCandidatesInSessionDescription(remote_description())) {
2448 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2449 }
2450
2451 if (old_remote_description) {
2452 for (const cricket::ContentInfo& content :
2453 old_remote_description->description()->contents()) {
2454 // Check if this new SessionDescription contains new ICE ufrag and
2455 // password that indicates the remote peer requests an ICE restart.
2456 // TODO(deadbeef): When we start storing both the current and pending
2457 // remote description, this should reset pending_ice_restarts and compare
2458 // against the current description.
2459 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2460 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002461 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002462 pending_ice_restarts_.insert(content.name);
2463 }
2464 } else {
2465 // We retain all received candidates only if ICE is not restarted.
2466 // When ICE is restarted, all previous candidates belong to an old
2467 // generation and should not be kept.
2468 // TODO(deadbeef): This goes against the W3C spec which says the remote
2469 // description should only contain candidates from the last set remote
2470 // description plus any candidates added since then. We should remove
2471 // this once we're sure it won't break anything.
2472 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2473 old_remote_description, content.name, mutable_remote_description());
2474 }
2475 }
2476 }
2477
2478 if (session_error() != SessionError::kNone) {
2479 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2480 }
2481
2482 // Set the the ICE connection state to connecting since the connection may
2483 // become writable with peer reflexive candidates before any remote candidate
2484 // is signaled.
2485 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2486 // is to have a new signal the indicates a change in checking state from the
2487 // transport and expose a new checking() member from transport that can be
2488 // read to determine the current checking state. The existing SignalConnecting
2489 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002490 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002491 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002492 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2493 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2494 }
2495
deadbeefab9b2d12015-10-14 11:33:11 -07002496 // If setting the description decided our SSL role, allocate any necessary
2497 // SCTP sids.
2498 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002499 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002500 AllocateSctpSids(role);
2501 }
2502
Steve Antondcc3c022017-12-22 16:02:54 -08002503 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002504 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002505 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002506 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002507 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002508 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002509 for (auto transceiver : transceivers_) {
2510 const ContentInfo* content =
2511 FindMediaSectionForTransceiver(transceiver, remote_description());
2512 if (!content) {
2513 continue;
2514 }
2515 const MediaContentDescription* media_desc = content->media_description();
2516 RtpTransceiverDirection local_direction =
2517 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002518 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2519 // RTCSessionDescription: Set the associated remote streams given
2520 // transceiver.[[Receiver]], msids, addList, and removeList".
2521 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2522 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2523 std::vector<std::string> stream_ids;
2524 if (!media_desc->streams().empty()) {
2525 // The remote description has signaled the stream IDs.
2526 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002527 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002528 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2529 << " (" << GetStreamIdsString(stream_ids) << ").";
2530 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2531 stream_ids, &added_streams,
2532 &removed_streams);
2533 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2534 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2535 // and transceiver's current direction is neither sendrecv nor recvonly,
2536 // process the addition of a remote track for the media description.
2537 if (!transceiver->fired_direction() ||
2538 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2539 RTC_LOG(LS_INFO)
2540 << "Processing the addition of a remote track for MID="
2541 << content->name << ".";
2542 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002543 }
Steve Antondcc3c022017-12-22 16:02:54 -08002544 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002545 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2546 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2547 // removal of a remote track for the media description, given transceiver,
2548 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002549 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002550 (transceiver->fired_direction() &&
2551 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2552 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2553 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002554 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002555 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2556 transceiver->internal()->set_fired_direction(local_direction);
2557 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2558 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002559 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002560 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2561 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002562 transceiver->internal()->set_current_direction(local_direction);
2563 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002564 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2565 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002566 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002567 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2568 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002569 transceiver->Stop();
2570 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002571 if (!content->rejected &&
2572 RtpTransceiverDirectionHasRecv(local_direction)) {
2573 // Set ssrc to 0 in the case of an unsignalled ssrc.
2574 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002575 if (!media_desc->streams().empty() &&
2576 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002577 ssrc = media_desc->streams()[0].first_ssrc();
2578 }
2579 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002580 }
Steve Antondcc3c022017-12-22 16:02:54 -08002581 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002582 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002583 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002584 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002585 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002586 observer->OnTrack(transceiver);
2587 observer->OnAddTrack(transceiver->receiver(),
2588 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002589 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002590 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002591 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002592 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002593 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002594 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002595 }
2596 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002597 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002598 }
Steve Antondcc3c022017-12-22 16:02:54 -08002599 }
2600
Henrik Boströmfdb92012017-11-09 19:55:44 +01002601 const cricket::ContentInfo* audio_content =
2602 GetFirstAudioContent(remote_description()->description());
2603 const cricket::ContentInfo* video_content =
2604 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002605 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002606 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002607 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002608 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002609 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002610 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002611
2612 // Check if the descriptions include streams, just in case the peer supports
2613 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002614 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002615 (audio_desc && !audio_desc->streams().empty()) ||
2616 (video_desc && !video_desc->streams().empty())) {
2617 remote_peer_supports_msid_ = true;
2618 }
deadbeefab9b2d12015-10-14 11:33:11 -07002619
2620 // We wait to signal new streams until we finish processing the description,
2621 // since only at that point will new streams have all their tracks.
2622 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2623
Steve Antondcc3c022017-12-22 16:02:54 -08002624 if (!IsUnifiedPlan()) {
2625 // TODO(steveanton): When removing RTP senders/receivers in response to a
2626 // rejected media section, there is some cleanup logic that expects the
2627 // voice/ video channel to still be set. But in this method the voice/video
2628 // channel would have been destroyed by the SetRemoteDescription caller
2629 // above so the cleanup that relies on them fails to run. The RemoveSenders
2630 // calls should be moved to right before the DestroyChannel calls to fix
2631 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002632
Steve Antondcc3c022017-12-22 16:02:54 -08002633 // Find all audio rtp streams and create corresponding remote AudioTracks
2634 // and MediaStreams.
2635 if (audio_content) {
2636 if (audio_content->rejected) {
2637 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2638 } else {
2639 bool default_audio_track_needed =
2640 !remote_peer_supports_msid_ &&
2641 RtpTransceiverDirectionHasSend(audio_desc->direction());
2642 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2643 default_audio_track_needed, audio_desc->type(),
2644 new_streams);
2645 }
deadbeeffaac4972015-11-12 15:33:07 -08002646 }
deadbeefab9b2d12015-10-14 11:33:11 -07002647
Steve Antondcc3c022017-12-22 16:02:54 -08002648 // Find all video rtp streams and create corresponding remote VideoTracks
2649 // and MediaStreams.
2650 if (video_content) {
2651 if (video_content->rejected) {
2652 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2653 } else {
2654 bool default_video_track_needed =
2655 !remote_peer_supports_msid_ &&
2656 RtpTransceiverDirectionHasSend(video_desc->direction());
2657 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2658 default_video_track_needed, video_desc->type(),
2659 new_streams);
2660 }
deadbeeffaac4972015-11-12 15:33:07 -08002661 }
deadbeefab9b2d12015-10-14 11:33:11 -07002662
Steve Antondcc3c022017-12-22 16:02:54 -08002663 // Update the DataChannels with the information from the remote peer.
2664 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002665 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002666 cricket::kMediaProtocolRtpPrefix)) {
2667 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2668 }
deadbeefab9b2d12015-10-14 11:33:11 -07002669 }
deadbeefab9b2d12015-10-14 11:33:11 -07002670
Steve Antondcc3c022017-12-22 16:02:54 -08002671 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002672 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002673 for (size_t i = 0; i < new_streams->count(); ++i) {
2674 MediaStreamInterface* new_stream = new_streams->at(i);
2675 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002676 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002677 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2678 }
deadbeefab9b2d12015-10-14 11:33:11 -07002679
Steve Antondcc3c022017-12-22 16:02:54 -08002680 UpdateEndedRemoteMediaStreams();
2681 }
deadbeefab9b2d12015-10-14 11:33:11 -07002682
Steve Anton8a006912017-12-04 15:25:56 -08002683 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002684}
2685
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002686void PeerConnection::SetAssociatedRemoteStreams(
2687 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2688 const std::vector<std::string>& stream_ids,
2689 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2690 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2691 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2692 for (const std::string& stream_id : stream_ids) {
2693 rtc::scoped_refptr<MediaStreamInterface> stream =
2694 remote_streams_->find(stream_id);
2695 if (!stream) {
2696 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2697 MediaStream::Create(stream_id));
2698 remote_streams_->AddStream(stream);
2699 added_streams->push_back(stream);
2700 }
2701 media_streams.push_back(stream);
2702 }
2703 // Special case: "a=msid" missing, use random stream ID.
2704 if (media_streams.empty() &&
2705 !(remote_description()->description()->msid_signaling() &
2706 cricket::kMsidSignalingMediaSection)) {
2707 if (!missing_msid_default_stream_) {
2708 missing_msid_default_stream_ = MediaStreamProxy::Create(
2709 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2710 added_streams->push_back(missing_msid_default_stream_);
2711 }
2712 media_streams.push_back(missing_msid_default_stream_);
2713 }
2714 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2715 receiver->streams();
2716 // SetStreams() will add/remove the receiver's track to/from the streams. This
2717 // differs from the spec - the spec uses an "addList" and "removeList" to
2718 // update the stream-track relationships in a later step. We do this earlier,
2719 // changing the order of things, but the end-result is the same.
2720 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2721 // instead. https://crbug.com/webrtc/9480
2722 receiver->SetStreams(media_streams);
2723 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2724}
2725
Steve Anton0f5400a2018-07-17 14:25:36 -07002726void PeerConnection::ProcessRemovalOfRemoteTrack(
2727 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2728 transceiver,
2729 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2730 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2731 RTC_DCHECK(transceiver->mid());
2732 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2733 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002734 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002735 transceiver->internal()->receiver_internal()->streams();
2736 // This will remove the remote track from the streams.
2737 transceiver->internal()->receiver_internal()->set_stream_ids({});
2738 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002739 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2740}
2741
2742void PeerConnection::RemoveRemoteStreamsIfEmpty(
2743 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2744 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2745 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2746 // streams, see if the stream was removed by checking if this was the last
2747 // receiver with that stream ID.
2748 for (auto remote_stream : remote_streams) {
2749 if (remote_stream->GetAudioTracks().empty() &&
2750 remote_stream->GetVideoTracks().empty()) {
2751 remote_streams_->RemoveStream(remote_stream);
2752 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002753 }
2754 }
2755}
2756
Steve Antondcc3c022017-12-22 16:02:54 -08002757RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2758 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002759 const SessionDescriptionInterface& new_session,
2760 const SessionDescriptionInterface* old_local_description,
2761 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002762 RTC_DCHECK(IsUnifiedPlan());
2763
Steve Anton7464fca2018-01-19 11:10:37 -08002764 const cricket::ContentGroup* bundle_group = nullptr;
2765 if (new_session.GetType() == SdpType::kOffer) {
2766 auto bundle_group_or_error =
2767 GetEarlyBundleGroup(*new_session.description());
2768 if (!bundle_group_or_error.ok()) {
2769 return bundle_group_or_error.MoveError();
2770 }
2771 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002772 }
Steve Antondcc3c022017-12-22 16:02:54 -08002773
Steve Antondcc3c022017-12-22 16:02:54 -08002774 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002775 for (size_t i = 0; i < new_contents.size(); ++i) {
2776 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002777 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002778 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002779 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2780 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002781 const cricket::ContentInfo* old_local_content = nullptr;
2782 if (old_local_description &&
2783 i < old_local_description->description()->contents().size()) {
2784 old_local_content =
2785 &old_local_description->description()->contents()[i];
2786 }
2787 const cricket::ContentInfo* old_remote_content = nullptr;
2788 if (old_remote_description &&
2789 i < old_remote_description->description()->contents().size()) {
2790 old_remote_content =
2791 &old_remote_description->description()->contents()[i];
2792 }
Steve Antondcc3c022017-12-22 16:02:54 -08002793 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002794 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2795 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002796 if (!transceiver_or_error.ok()) {
2797 return transceiver_or_error.MoveError();
2798 }
2799 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002800 RTCError error =
2801 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2802 if (!error.ok()) {
2803 return error;
2804 }
2805 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002806 if (GetDataMid() && new_content.name != *GetDataMid()) {
2807 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002808 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2809 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002810 continue;
2811 }
2812 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2813 if (!error.ok()) {
2814 return error;
2815 }
Steve Antondcc3c022017-12-22 16:02:54 -08002816 } else {
2817 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2818 "Unknown section type.");
2819 }
2820 }
2821
2822 return RTCError::OK();
2823}
2824
2825RTCError PeerConnection::UpdateTransceiverChannel(
2826 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2827 transceiver,
2828 const cricket::ContentInfo& content,
2829 const cricket::ContentGroup* bundle_group) {
2830 RTC_DCHECK(IsUnifiedPlan());
2831 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002832 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002833 if (content.rejected) {
2834 if (channel) {
2835 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002836 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002837 }
2838 } else {
2839 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002840 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002841 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002842 } else {
Steve Anton69470252018-02-09 11:43:08 -08002843 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002844 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002845 }
2846 if (!channel) {
2847 LOG_AND_RETURN_ERROR(
2848 RTCErrorType::INTERNAL_ERROR,
2849 "Failed to create channel for mid=" + content.name);
2850 }
2851 transceiver->internal()->SetChannel(channel);
2852 }
2853 }
2854 return RTCError::OK();
2855}
2856
Steve Antonfa2260d2017-12-28 16:38:23 -08002857RTCError PeerConnection::UpdateDataChannel(
2858 cricket::ContentSource source,
2859 const cricket::ContentInfo& content,
2860 const cricket::ContentGroup* bundle_group) {
2861 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002862 // If data channels are disabled, ignore this media section. CreateAnswer
2863 // will take care of rejecting it.
2864 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002865 }
2866 if (content.rejected) {
2867 DestroyDataChannel();
2868 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002869 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002870 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002871 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2872 "Failed to create data channel.");
2873 }
2874 }
2875 if (source == cricket::CS_REMOTE) {
2876 const MediaContentDescription* data_desc = content.media_description();
2877 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2878 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2879 }
2880 }
2881 }
2882 return RTCError::OK();
2883}
2884
Steve Antondcc3c022017-12-22 16:02:54 -08002885RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2886PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002887 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002888 size_t mline_index,
2889 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002890 const ContentInfo* old_local_content,
2891 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002892 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002893 // If this is an offer then the m= section might be recycled. If the m=
2894 // section is being recycled (defined as: rejected in the current local or
2895 // remote description and not rejected in new description), dissociate the
2896 // currently associated RtpTransceiver by setting its mid property to null,
2897 // and discard the mapping between the transceiver and its m= section index.
2898 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2899 old_remote_content)) {
2900 // We want to dissociate the transceiver that has the rejected mid.
2901 const std::string& old_mid =
2902 (old_local_content && old_local_content->rejected)
2903 ? old_local_content->name
2904 : old_remote_content->name;
2905 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002906 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002907 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2908 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002909 old_transceiver->internal()->set_mid(absl::nullopt);
2910 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002911 }
2912 }
2913 const MediaContentDescription* media_desc = content.media_description();
2914 auto transceiver = GetAssociatedTransceiver(content.name);
2915 if (source == cricket::CS_LOCAL) {
2916 // Find the RtpTransceiver that corresponds to this m= section, using the
2917 // mapping between transceivers and m= section indices established when
2918 // creating the offer.
2919 if (!transceiver) {
2920 transceiver = GetTransceiverByMLineIndex(mline_index);
2921 }
2922 if (!transceiver) {
2923 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2924 "Unknown transceiver");
2925 }
2926 } else {
2927 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2928 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2929 // of the same type...
2930 if (!transceiver &&
2931 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2932 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2933 }
2934 // If no RtpTransceiver was found in the previous step, create one with a
2935 // recvonly direction.
2936 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002937 RTC_LOG(LS_INFO) << "Adding "
2938 << cricket::MediaTypeToString(media_desc->type())
2939 << " transceiver for MID=" << content.name
2940 << " at i=" << mline_index
2941 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002942 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002943 auto sender =
2944 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002945 std::string receiver_id;
2946 if (!media_desc->streams().empty()) {
2947 receiver_id = media_desc->streams()[0].id;
2948 } else {
2949 receiver_id = rtc::CreateRandomUuid();
2950 }
2951 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002952 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002953 transceiver->internal()->set_direction(
2954 RtpTransceiverDirection::kRecvOnly);
2955 }
2956 }
2957 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002958 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002959 LOG_AND_RETURN_ERROR(
2960 RTCErrorType::INVALID_PARAMETER,
2961 "Transceiver type does not match media description type.");
2962 }
2963 // Associate the found or created RtpTransceiver with the m= section by
2964 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2965 // section, and establish a mapping between the transceiver and the index of
2966 // the m= section.
2967 transceiver->internal()->set_mid(content.name);
2968 transceiver->internal()->set_mline_index(mline_index);
2969 return std::move(transceiver);
2970}
2971
2972rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2973PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2974 RTC_DCHECK(IsUnifiedPlan());
2975 for (auto transceiver : transceivers_) {
2976 if (transceiver->mid() == mid) {
2977 return transceiver;
2978 }
2979 }
2980 return nullptr;
2981}
2982
2983rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2984PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2985 RTC_DCHECK(IsUnifiedPlan());
2986 for (auto transceiver : transceivers_) {
2987 if (transceiver->internal()->mline_index() == mline_index) {
2988 return transceiver;
2989 }
2990 }
2991 return nullptr;
2992}
2993
2994rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2995PeerConnection::FindAvailableTransceiverToReceive(
2996 cricket::MediaType media_type) const {
2997 RTC_DCHECK(IsUnifiedPlan());
2998 // From JSEP section 5.10 (Applying a Remote Description):
2999 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3000 // the same type that were added to the PeerConnection by addTrack and are not
3001 // associated with any m= section and are not stopped, find the first such
3002 // RtpTransceiver.
3003 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003004 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003005 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3006 !transceiver->stopped()) {
3007 return transceiver;
3008 }
3009 }
3010 return nullptr;
3011}
3012
Steve Antoned10bd92017-12-05 10:52:59 -08003013const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3014 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3015 transceiver,
3016 const SessionDescriptionInterface* sdesc) const {
3017 RTC_DCHECK(transceiver);
3018 RTC_DCHECK(sdesc);
3019 if (IsUnifiedPlan()) {
3020 if (!transceiver->internal()->mid()) {
3021 // This transceiver is not associated with a media section yet.
3022 return nullptr;
3023 }
3024 return sdesc->description()->GetContentByName(
3025 *transceiver->internal()->mid());
3026 } else {
3027 // Plan B only allows at most one audio and one video section, so use the
3028 // first media section of that type.
3029 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003030 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003031 }
3032}
3033
deadbeef46c73892016-11-16 19:42:04 -08003034PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3035 return configuration_;
3036}
3037
deadbeef293e9262017-01-11 12:28:30 -08003038bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3039 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003040 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003041 if (IsClosed()) {
3042 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3043 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3044 }
3045
Qingsi Wanga2d60672018-04-11 16:57:45 -07003046 // According to JSEP, after setLocalDescription, changing the candidate pool
3047 // size is not allowed, and changing the set of ICE servers will not result
3048 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003049 if (local_description() && configuration.ice_candidate_pool_size !=
3050 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003051 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3052 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003053 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003054 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003055
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003056 if (local_description() &&
3057 configuration.use_media_transport != configuration_.use_media_transport) {
3058 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3059 "SetLocalDescription.";
3060 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3061 }
3062
3063 if (remote_description() &&
3064 configuration.use_media_transport != configuration_.use_media_transport) {
3065 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3066 "SetRemoteDescription.";
3067 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3068 }
3069
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003070 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003071 configuration.use_media_transport_for_data_channels !=
3072 configuration_.use_media_transport_for_data_channels) {
3073 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3074 "after calling SetLocalDescription.";
3075 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3076 }
3077
3078 if (remote_description() &&
3079 configuration.use_media_transport_for_data_channels !=
3080 configuration_.use_media_transport_for_data_channels) {
3081 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3082 "after calling SetRemoteDescription.";
3083 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3084 }
3085
3086 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003087 configuration.crypto_options != configuration_.crypto_options) {
3088 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3089 "SetLocalDescription.";
3090 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3091 }
3092
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003093 if (configuration.use_media_transport_for_data_channels ||
3094 configuration.use_media_transport) {
3095 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3096 << "Media transport requires MaxBundle policy.";
3097 }
3098
deadbeef293e9262017-01-11 12:28:30 -08003099 // The simplest (and most future-compatible) way to tell if the config was
3100 // modified in an invalid way is to copy each property we do support
3101 // modifying, then use operator==. There are far more properties we don't
3102 // support modifying than those we do, and more could be added.
3103 RTCConfiguration modified_config = configuration_;
3104 modified_config.servers = configuration.servers;
3105 modified_config.type = configuration.type;
3106 modified_config.ice_candidate_pool_size =
3107 configuration.ice_candidate_pool_size;
3108 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003109 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003110 modified_config.ice_check_interval_strong_connectivity =
3111 configuration.ice_check_interval_strong_connectivity;
3112 modified_config.ice_check_interval_weak_connectivity =
3113 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003114 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3115 modified_config.ice_unwritable_min_checks =
3116 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003117 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003118 modified_config.stun_candidate_keepalive_interval =
3119 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003120 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003121 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003122 modified_config.active_reset_srtp_params =
3123 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003124 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003125 modified_config.use_media_transport_for_data_channels =
3126 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003127 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003128 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003129 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3130 }
3131
Steve Anton038834f2017-07-14 15:59:59 -07003132 // Validate the modified configuration.
3133 RTCError validate_error = ValidateConfiguration(modified_config);
3134 if (!validate_error.ok()) {
3135 return SafeSetError(std::move(validate_error), error);
3136 }
3137
deadbeef293e9262017-01-11 12:28:30 -08003138 // Note that this isn't possible through chromium, since it's an unsigned
3139 // short in WebIDL.
3140 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003141 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003142 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3143 }
3144
3145 // Parse ICE servers before hopping to network thread.
3146 cricket::ServerAddresses stun_servers;
3147 std::vector<cricket::RelayServerConfig> turn_servers;
3148 RTCErrorType parse_error =
3149 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3150 if (parse_error != RTCErrorType::NONE) {
3151 return SafeSetError(parse_error, error);
3152 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003153 // Note if STUN or TURN servers were supplied.
3154 if (!stun_servers.empty()) {
3155 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3156 }
3157 if (!turn_servers.empty()) {
3158 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3159 }
deadbeef293e9262017-01-11 12:28:30 -08003160
3161 // In theory this shouldn't fail.
3162 if (!network_thread()->Invoke<bool>(
3163 RTC_FROM_HERE,
3164 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3165 stun_servers, turn_servers, modified_config.type,
3166 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003167 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003168 modified_config.turn_customizer,
3169 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003170 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003171 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3172 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003173
deadbeefd1a38b52016-12-10 13:15:33 -08003174 // As described in JSEP, calling setConfiguration with new ICE servers or
3175 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3176 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003177 if (modified_config.servers != configuration_.servers ||
3178 modified_config.type != configuration_.type ||
3179 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003180 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003181 }
skvladd1f5fda2017-02-03 16:54:05 -08003182
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003183 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003184 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003185 modified_config.use_media_transport ||
3186 modified_config.use_media_transport_for_data_channels
3187 ? factory_->media_transport_factory()
3188 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003189
Zhi Huangb57e1692018-06-12 11:41:11 -07003190 if (configuration_.active_reset_srtp_params !=
3191 modified_config.active_reset_srtp_params) {
3192 transport_controller_->SetActiveResetSrtpParams(
3193 modified_config.active_reset_srtp_params);
3194 }
3195
deadbeef293e9262017-01-11 12:28:30 -08003196 configuration_ = modified_config;
3197 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003198}
3199
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003200bool PeerConnection::AddIceCandidate(
3201 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003202 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003203 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003204 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003205 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003206 return false;
3207 }
Steve Antond25da372017-11-06 14:50:29 -08003208
3209 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003210 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003211 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003212 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003213 return false;
3214 }
3215
3216 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003217 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003218 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003219 return false;
3220 }
3221
3222 bool valid = false;
3223 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3224 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003225 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003226 return false;
3227 }
3228
3229 // Add this candidate to the remote session description.
3230 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003231 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003232 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003233 return false;
3234 }
3235
3236 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003237 bool result = UseCandidate(ice_candidate);
3238 if (result) {
3239 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3240 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3241 } else {
3242 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3243 }
3244 return result;
Steve Antond25da372017-11-06 14:50:29 -08003245 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003246 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003247 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003248 return true;
3249 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003250}
3251
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003252bool PeerConnection::RemoveIceCandidates(
3253 const std::vector<cricket::Candidate>& candidates) {
3254 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003255 if (IsClosed()) {
3256 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3257 return false;
3258 }
3259
Steve Antond25da372017-11-06 14:50:29 -08003260 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003261 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3262 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003263 return false;
3264 }
3265
3266 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003267 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003268 return false;
3269 }
3270
3271 size_t number_removed =
3272 mutable_remote_description()->RemoveCandidates(candidates);
3273 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003274 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003275 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003276 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003277 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003278 }
3279
3280 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003281 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3282 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003283 RTC_LOG(LS_ERROR)
3284 << "RemoveIceCandidates: Error when removing remote candidates: "
3285 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003286 }
3287 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003288}
3289
Niels Möller0c4f7be2018-05-07 14:01:37 +02003290RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003291 if (!worker_thread()->IsCurrent()) {
3292 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003293 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003294 }
3295
Niels Möller0c4f7be2018-05-07 14:01:37 +02003296 const bool has_min = bitrate.min_bitrate_bps.has_value();
3297 const bool has_start = bitrate.start_bitrate_bps.has_value();
3298 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003299 if (has_min && *bitrate.min_bitrate_bps < 0) {
3300 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3301 "min_bitrate_bps <= 0");
3302 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003303 if (has_start) {
3304 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003306 "start_bitrate_bps < min_bitrate_bps");
3307 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003308 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3309 "curent_bitrate_bps < 0");
3310 }
3311 }
3312 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003313 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003314 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003315 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003316 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3318 "max_bitrate_bps < min_bitrate_bps");
3319 } else if (*bitrate.max_bitrate_bps < 0) {
3320 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3321 "max_bitrate_bps < 0");
3322 }
3323 }
3324
zstein4b979802017-06-02 14:37:37 -07003325 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003326 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003327
3328 return RTCError::OK();
3329}
3330
Alex Narest78609d52017-10-20 10:37:47 +02003331void PeerConnection::SetBitrateAllocationStrategy(
3332 std::unique_ptr<rtc::BitrateAllocationStrategy>
3333 bitrate_allocation_strategy) {
3334 rtc::Thread* worker_thread = factory_->worker_thread();
3335 if (!worker_thread->IsCurrent()) {
3336 rtc::BitrateAllocationStrategy* strategy_raw =
3337 bitrate_allocation_strategy.release();
3338 auto functor = [this, strategy_raw]() {
3339 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003340 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003341 };
3342 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3343 return;
3344 }
3345 RTC_DCHECK(call_.get());
3346 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3347}
3348
henrika5f6bf242017-11-01 11:06:56 +01003349void PeerConnection::SetAudioPlayout(bool playout) {
3350 if (!worker_thread()->IsCurrent()) {
3351 worker_thread()->Invoke<void>(
3352 RTC_FROM_HERE,
3353 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3354 return;
3355 }
3356 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003357 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003358 audio_state->SetPlayout(playout);
3359}
3360
3361void PeerConnection::SetAudioRecording(bool recording) {
3362 if (!worker_thread()->IsCurrent()) {
3363 worker_thread()->Invoke<void>(
3364 RTC_FROM_HERE,
3365 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3366 return;
3367 }
3368 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003369 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003370 audio_state->SetRecording(recording);
3371}
3372
Steve Anton8c0f7a72017-10-03 10:03:10 -07003373std::unique_ptr<rtc::SSLCertificate>
3374PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003375 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3376 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003377 return nullptr;
3378 }
Steve Antonf25303e2018-10-16 15:23:31 -07003379 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003380}
3381
Zhi Huang70b820f2018-01-27 14:16:15 -08003382std::unique_ptr<rtc::SSLCertChain>
3383PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003384 auto audio_transceiver = GetFirstAudioTransceiver();
3385 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003386 return nullptr;
3387 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003388 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003389 audio_transceiver->internal()->channel()->transport_name());
3390}
3391
3392rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3393PeerConnection::GetFirstAudioTransceiver() const {
3394 for (auto transceiver : transceivers_) {
3395 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3396 return transceiver;
3397 }
3398 }
3399 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003400}
3401
ivoc14d5dbe2016-07-04 07:06:55 -07003402bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3403 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003404 // TODO(eladalon): It would be better to not allow negative values into PC.
3405 const size_t max_size = (max_size_bytes < 0)
3406 ? RtcEventLog::kUnlimitedOutput
3407 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003408 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3409 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3410 output_period_ms = 5000;
3411 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003412 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003413 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003414 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003415}
3416
Bjorn Tereliusde939432017-11-20 17:38:14 +01003417bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3418 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003419 // TODO(eladalon): In C++14, this can be done with a lambda.
3420 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003421 bool operator()() {
3422 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3423 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003424 PeerConnection* const pc;
3425 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003426 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003427 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003428 return worker_thread()->Invoke<bool>(
3429 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003430}
3431
3432void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003433 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003434 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3435}
3436
Harald Alvestrandad88c882018-11-28 16:47:46 +01003437rtc::scoped_refptr<DtlsTransportInterface>
3438PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3439 return transport_controller_->LookupDtlsTransportByMid(mid);
3440}
3441
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003442const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003443 return pending_local_description_ ? pending_local_description_.get()
3444 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003445}
3446
3447const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003448 return pending_remote_description_ ? pending_remote_description_.get()
3449 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003450}
3451
deadbeeffe4a8a42016-12-20 17:56:17 -08003452const SessionDescriptionInterface* PeerConnection::current_local_description()
3453 const {
Steve Anton75737c02017-11-06 10:37:17 -08003454 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003455}
3456
3457const SessionDescriptionInterface* PeerConnection::current_remote_description()
3458 const {
Steve Anton75737c02017-11-06 10:37:17 -08003459 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003460}
3461
3462const SessionDescriptionInterface* PeerConnection::pending_local_description()
3463 const {
Steve Anton75737c02017-11-06 10:37:17 -08003464 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003465}
3466
3467const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3468 const {
Steve Anton75737c02017-11-06 10:37:17 -08003469 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003470}
3471
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003472void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003473 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003474 // Update stats here so that we have the most recent stats for tracks and
3475 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003476 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003477
Steve Anton75737c02017-11-06 10:37:17 -08003478 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003479 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003480
Steve Anton8af21862017-12-15 11:20:13 -08003481 for (auto transceiver : transceivers_) {
3482 transceiver->Stop();
3483 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003484
3485 // Ensure that all asynchronous stats requests are completed before destroying
3486 // the transport controller below.
3487 if (stats_collector_) {
3488 stats_collector_->WaitForPendingRequest();
3489 }
3490
3491 // Don't destroy BaseChannels until after stats has been cleaned up so that
3492 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003493 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003494
Qingsi Wang93a84392018-01-30 17:13:09 -08003495 // The event log is used in the transport controller, which must be outlived
3496 // by the former. CreateOffer by the peer connection is implemented
3497 // asynchronously and if the peer connection is closed without resetting the
3498 // WebRTC session description factory, the session description factory would
3499 // call the transport controller.
3500 webrtc_session_desc_factory_.reset();
3501 transport_controller_.reset();
3502
deadbeef42a42632017-03-10 15:18:00 -08003503 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003504 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3505 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003506
Steve Anton978b8762017-09-29 12:15:02 -07003507 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003508 call_.reset();
3509 // The event log must outlive call (and any other object that uses it).
3510 event_log_.reset();
3511 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003512 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003513 // The .h file says that observer can be discarded after close() returns.
3514 // Make sure this is true.
3515 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003516}
3517
Steve Antonad182762018-09-05 20:22:40 +00003518void PeerConnection::OnMessage(rtc::Message* msg) {
3519 switch (msg->message_id) {
3520 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3521 SetSessionDescriptionMsg* param =
3522 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3523 param->observer->OnSuccess();
3524 delete param;
3525 break;
3526 }
3527 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3528 SetSessionDescriptionMsg* param =
3529 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3530 param->observer->OnFailure(std::move(param->error));
3531 delete param;
3532 break;
3533 }
3534 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3535 CreateSessionDescriptionMsg* param =
3536 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3537 param->observer->OnFailure(std::move(param->error));
3538 delete param;
3539 break;
3540 }
3541 case MSG_GETSTATS: {
3542 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3543 StatsReports reports;
3544 stats_->GetStats(param->track, &reports);
3545 param->observer->OnComplete(reports);
3546 delete param;
3547 break;
3548 }
3549 case MSG_FREE_DATACHANNELS: {
3550 sctp_data_channels_to_free_.clear();
3551 break;
3552 }
3553 case MSG_REPORT_USAGE_PATTERN: {
3554 ReportUsagePattern();
3555 break;
3556 }
3557 default:
3558 RTC_NOTREACHED() << "Not implemented";
3559 break;
3560 }
3561}
3562
Steve Antonafb0bb72018-02-20 11:35:37 -08003563cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3564 RTC_DCHECK(!IsUnifiedPlan());
3565 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3566 GetAudioTransceiver()->internal()->channel());
3567 if (voice_channel) {
3568 return voice_channel->media_channel();
3569 } else {
3570 return nullptr;
3571 }
3572}
3573
3574cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3575 RTC_DCHECK(!IsUnifiedPlan());
3576 auto* video_channel = static_cast<cricket::VideoChannel*>(
3577 GetVideoTransceiver()->internal()->channel());
3578 if (video_channel) {
3579 return video_channel->media_channel();
3580 } else {
3581 return nullptr;
3582 }
3583}
3584
Steve Anton4171afb2017-11-20 10:20:22 -08003585void PeerConnection::CreateAudioReceiver(
3586 MediaStreamInterface* stream,
3587 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003588 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3589 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003590 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3591 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003592 auto* audio_receiver = new AudioRtpReceiver(
3593 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003594 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003595 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3596 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3597 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003598 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003599 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003600 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003601}
3602
Steve Anton4171afb2017-11-20 10:20:22 -08003603void PeerConnection::CreateVideoReceiver(
3604 MediaStreamInterface* stream,
3605 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003606 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3607 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003608 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3609 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003610 auto* video_receiver = new VideoRtpReceiver(
3611 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003612 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003613 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3614 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3615 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003616 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003617 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003618 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003619}
3620
deadbeef70ab1a12015-09-28 16:53:55 -07003621// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3622// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003623rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003624 const RtpSenderInfo& remote_sender_info) {
3625 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3626 if (!receiver) {
3627 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3628 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003629 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003630 }
Steve Anton4171afb2017-11-20 10:20:22 -08003631 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3632 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3633 } else {
3634 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3635 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003636 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003637}
3638
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003639void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3640 MediaStreamInterface* stream) {
3641 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003642 RTC_DCHECK(track);
3643 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003644 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003645 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003646 // We already have a sender for this track, so just change the stream_id
3647 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003648 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003649 return;
3650 }
3651
3652 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003653 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003654 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003655 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003656 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003657 // If the sender has already been configured in SDP, we call SetSsrc,
3658 // which will connect the sender to the underlying transport. This can
3659 // occur if a local session description that contains the ID of the sender
3660 // is set before AddStream is called. It can also occur if the local
3661 // session description is not changed and RemoveStream is called, and
3662 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003663 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003664 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003665 if (sender_info) {
3666 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003667 }
3668}
3669
3670// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3671// indefinitely, when we have unified plan SDP.
3672void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3673 MediaStreamInterface* stream) {
3674 RTC_DCHECK(!IsClosed());
3675 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003676 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003677 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3678 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003679 return;
3680 }
Steve Anton4171afb2017-11-20 10:20:22 -08003681 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003682}
3683
3684void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3685 MediaStreamInterface* stream) {
3686 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003687 RTC_DCHECK(track);
3688 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003689 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003690 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003691 // We already have a sender for this track, so just change the stream_id
3692 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003693 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003694 return;
3695 }
3696
3697 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003698 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003699 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003700 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003701 GetVideoTransceiver()->internal()->AddSender(new_sender);
3702 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003703 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003704 if (sender_info) {
3705 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003706 }
3707}
3708
3709void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3710 MediaStreamInterface* stream) {
3711 RTC_DCHECK(!IsClosed());
3712 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003713 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003714 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3715 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003716 return;
3717 }
Steve Anton4171afb2017-11-20 10:20:22 -08003718 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003719}
3720
Steve Antonba818672017-11-06 10:21:57 -08003721void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003722 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003723 if (ice_connection_state_ == new_state) {
3724 return;
3725 }
3726
deadbeefcbecd352015-09-23 11:50:27 -07003727 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003728 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003729 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003730 return;
3731 }
Steve Antonba818672017-11-06 10:21:57 -08003732
Mirko Bonadei675513b2017-11-09 11:09:25 +01003733 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3734 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003735 RTC_DCHECK(ice_connection_state_ !=
3736 PeerConnectionInterface::kIceConnectionClosed);
3737
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003738 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003739 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003740}
3741
Alex Loiko9289eda2018-11-23 16:18:59 +00003742void PeerConnection::SetStandardizedIceConnectionState(
3743 PeerConnectionInterface::IceConnectionState new_state) {
3744 RTC_DCHECK(signaling_thread()->IsCurrent());
3745 if (standardized_ice_connection_state_ == new_state)
3746 return;
3747 if (IsClosed())
3748 return;
3749 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003750 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003751}
3752
Jonas Olsson635474e2018-10-18 15:58:17 +02003753void PeerConnection::SetConnectionState(
3754 PeerConnectionInterface::PeerConnectionState new_state) {
3755 RTC_DCHECK(signaling_thread()->IsCurrent());
3756 if (connection_state_ == new_state)
3757 return;
3758 if (IsClosed())
3759 return;
3760 connection_state_ = new_state;
3761 Observer()->OnConnectionChange(new_state);
3762}
3763
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003764void PeerConnection::OnIceGatheringChange(
3765 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003766 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003767 if (IsClosed()) {
3768 return;
3769 }
3770 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003771 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003772}
3773
jbauch81bf7b02017-03-25 08:31:12 -07003774void PeerConnection::OnIceCandidate(
3775 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003776 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003777 if (IsClosed()) {
3778 return;
3779 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003780 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003781 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3782 candidate->candidate().address().IsPrivateIP()) {
3783 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3784 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003785 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003786}
3787
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003788void PeerConnection::OnIceCandidatesRemoved(
3789 const std::vector<cricket::Candidate>& candidates) {
3790 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003791 if (IsClosed()) {
3792 return;
3793 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003794 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003795}
3796
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003797void PeerConnection::ChangeSignalingState(
3798 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003799 RTC_DCHECK(signaling_thread()->IsCurrent());
3800 if (signaling_state_ == signaling_state) {
3801 return;
3802 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003803 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3804 << GetSignalingStateString(signaling_state_)
3805 << " New state: "
3806 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003807 signaling_state_ = signaling_state;
3808 if (signaling_state == kClosed) {
3809 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003810 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003811 standardized_ice_connection_state_ =
3812 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003813 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3814 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003815 if (ice_gathering_state_ != kIceGatheringComplete) {
3816 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003817 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003818 }
3819 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003820 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003821}
3822
deadbeefeb459812015-12-15 19:24:43 -08003823void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3824 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003825 if (IsClosed()) {
3826 return;
3827 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003828 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003829 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003830}
3831
deadbeefeb459812015-12-15 19:24:43 -08003832void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3833 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003834 if (IsClosed()) {
3835 return;
3836 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003837 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003838 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003839}
3840
3841void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3842 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003843 if (IsClosed()) {
3844 return;
3845 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003846 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003847 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003848}
3849
3850void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3851 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003852 if (IsClosed()) {
3853 return;
3854 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003855 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003856 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003857}
3858
Henrik Boström31638672017-11-23 17:48:32 +01003859void PeerConnection::PostSetSessionDescriptionSuccess(
3860 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003861 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3862 signaling_thread()->Post(RTC_FROM_HERE, this,
3863 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003864}
3865
deadbeefab9b2d12015-10-14 11:33:11 -07003866void PeerConnection::PostSetSessionDescriptionFailure(
3867 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003868 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003869 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003870 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3871 msg->error = std::move(error);
3872 signaling_thread()->Post(RTC_FROM_HERE, this,
3873 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003874}
3875
3876void PeerConnection::PostCreateSessionDescriptionFailure(
3877 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003878 RTCError error) {
3879 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003880 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3881 msg->error = std::move(error);
3882 signaling_thread()->Post(RTC_FROM_HERE, this,
3883 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003884}
3885
zhihuang1c378ed2017-08-17 14:10:50 -07003886void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003887 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003888 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003889 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003890
Steve Antondcc3c022017-12-22 16:02:54 -08003891 if (IsUnifiedPlan()) {
3892 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3893 } else {
3894 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3895 }
3896
Steve Antonfa2260d2017-12-28 16:38:23 -08003897 // Intentionally unset the data channel type for RTP data channel with the
3898 // second condition. Otherwise the RTP data channels would be successfully
3899 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3900 // when building with chromium. We want to leave RTP data channels broken, so
3901 // people won't try to use them.
3902 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3903 session_options->data_channel_type = data_channel_type();
3904 }
3905
Steve Antondcc3c022017-12-22 16:02:54 -08003906 // Apply ICE restart flag and renomination flag.
3907 for (auto& options : session_options->media_description_options) {
3908 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3909 options.transport_options.enable_ice_renomination =
3910 configuration_.enable_ice_renomination;
3911 }
3912
3913 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003914 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003915 session_options->pooled_ice_credentials =
3916 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3917 RTC_FROM_HERE,
3918 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3919 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003920 session_options->offer_extmap_allow_mixed =
3921 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003922}
3923
3924void PeerConnection::GetOptionsForPlanBOffer(
3925 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3926 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003927 // Figure out transceiver directional preferences.
3928 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3929 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3930
3931 // By default, generate sendrecv/recvonly m= sections.
3932 bool recv_audio = true;
3933 bool recv_video = true;
3934
3935 // By default, only offer a new m= section if we have media to send with it.
3936 bool offer_new_audio_description = send_audio;
3937 bool offer_new_video_description = send_video;
3938 bool offer_new_data_description = HasDataChannels();
3939
3940 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003941 if (offer_answer_options.offer_to_receive_audio !=
3942 RTCOfferAnswerOptions::kUndefined) {
3943 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003944 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003945 offer_new_audio_description ||
3946 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003947 }
Steve Antondcc3c022017-12-22 16:02:54 -08003948 if (offer_answer_options.offer_to_receive_video !=
3949 RTCOfferAnswerOptions::kUndefined) {
3950 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003951 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003952 offer_new_video_description ||
3953 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003954 }
3955
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003956 absl::optional<size_t> audio_index;
3957 absl::optional<size_t> video_index;
3958 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003959 // If a current description exists, generate m= sections in the same order,
3960 // using the first audio/video/data section that appears and rejecting
3961 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003962 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003963 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003964 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003965 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3966 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3967 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003968 }
3969
zhihuang1c378ed2017-08-17 14:10:50 -07003970 // Add audio/video/data m= sections to the end if needed.
3971 if (!audio_index && offer_new_audio_description) {
3972 session_options->media_description_options.push_back(
3973 cricket::MediaDescriptionOptions(
3974 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003975 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3976 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003977 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003978 }
zhihuang1c378ed2017-08-17 14:10:50 -07003979 if (!video_index && offer_new_video_description) {
3980 session_options->media_description_options.push_back(
3981 cricket::MediaDescriptionOptions(
3982 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003983 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3984 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003985 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003986 }
zhihuang1c378ed2017-08-17 14:10:50 -07003987 if (!data_index && offer_new_data_description) {
3988 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003989 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003990 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003991 }
3992
3993 cricket::MediaDescriptionOptions* audio_media_description_options =
3994 !audio_index ? nullptr
3995 : &session_options->media_description_options[*audio_index];
3996 cricket::MediaDescriptionOptions* video_media_description_options =
3997 !video_index ? nullptr
3998 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003999
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004000 AddPlanBRtpSenderOptions(GetSendersInternal(),
4001 audio_media_description_options,
4002 video_media_description_options,
4003 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004004}
4005
Steve Antondcc3c022017-12-22 16:02:54 -08004006static cricket::MediaDescriptionOptions
4007GetMediaDescriptionOptionsForTransceiver(
4008 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4009 transceiver,
4010 const std::string& mid) {
4011 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004012 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004013 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004014 // This behavior is specified in JSEP. The gist is that:
4015 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4016 // sendrecv.
4017 // 2. If the MSID is included, then it must be included in any subsequent
4018 // offer/answer exactly the same until the RtpTransceiver is stopped.
4019 if (!transceiver->stopped() &&
4020 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
4021 transceiver->internal()->has_ever_been_used_to_send())) {
4022 cricket::SenderOptions sender_options;
4023 sender_options.track_id = transceiver->sender()->id();
4024 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02004025 int num_send_encoding_layers =
4026 transceiver->sender()->init_send_encodings().size();
4027 sender_options.num_sim_layers =
4028 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08004029 media_description_options.sender_options.push_back(sender_options);
4030 }
Steve Antondcc3c022017-12-22 16:02:54 -08004031 return media_description_options;
4032}
4033
Steve Anton5c72e712018-12-10 14:25:30 -08004034// Returns the ContentInfo at mline index |i|, or null if none exists.
4035static const ContentInfo* GetContentByIndex(
4036 const SessionDescriptionInterface* sdesc,
4037 size_t i) {
4038 if (!sdesc) {
4039 return nullptr;
4040 }
4041 const ContentInfos& contents = sdesc->description()->contents();
4042 return (i < contents.size() ? &contents[i] : nullptr);
4043}
4044
Steve Antondcc3c022017-12-22 16:02:54 -08004045void PeerConnection::GetOptionsForUnifiedPlanOffer(
4046 const RTCOfferAnswerOptions& offer_answer_options,
4047 cricket::MediaSessionOptions* session_options) {
4048 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4049 // Offers) and 5.2.2 (Subsequent Offers).
4050 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4051 const ContentInfos& local_contents =
4052 (local_description() ? local_description()->description()->contents()
4053 : ContentInfos());
4054 const ContentInfos& remote_contents =
4055 (remote_description() ? remote_description()->description()->contents()
4056 : ContentInfos());
4057 // The mline indices that can be recycled. New transceivers should reuse these
4058 // slots first.
4059 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004060 // First, go through each media section that exists in either the local or
4061 // remote description and generate a media section in this offer for the
4062 // associated transceiver. If a media section can be recycled, generate a
4063 // default, rejected media section here that can be later overwritten.
4064 for (size_t i = 0;
4065 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4066 // Either |local_content| or |remote_content| is non-null.
4067 const ContentInfo* local_content =
4068 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004069 const ContentInfo* current_local_content =
4070 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004071 const ContentInfo* remote_content =
4072 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004073 const ContentInfo* current_remote_content =
4074 GetContentByIndex(current_remote_description(), i);
4075 bool had_been_rejected =
4076 (current_local_content && current_local_content->rejected) ||
4077 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004078 const std::string& mid =
4079 (local_content ? local_content->name : remote_content->name);
4080 cricket::MediaType media_type =
4081 (local_content ? local_content->media_description()->type()
4082 : remote_content->media_description()->type());
4083 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4084 media_type == cricket::MEDIA_TYPE_VIDEO) {
4085 auto transceiver = GetAssociatedTransceiver(mid);
4086 RTC_CHECK(transceiver);
4087 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004088 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004089 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004090 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004091 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4092 RtpTransceiverDirection::kInactive,
4093 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004094 recycleable_mline_indices.push(i);
4095 } else {
4096 session_options->media_description_options.push_back(
4097 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4098 // CreateOffer shouldn't really cause any state changes in
4099 // PeerConnection, but we need a way to match new transceivers to new
4100 // media sections in SetLocalDescription and JSEP specifies this is done
4101 // by recording the index of the media section generated for the
4102 // transceiver in the offer.
4103 transceiver->internal()->set_mline_index(i);
4104 }
4105 } else {
4106 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004107 RTC_CHECK(GetDataMid());
4108 if (had_been_rejected || mid != *GetDataMid()) {
4109 session_options->media_description_options.push_back(
4110 GetMediaDescriptionOptionsForRejectedData(mid));
4111 } else {
4112 session_options->media_description_options.push_back(
4113 GetMediaDescriptionOptionsForActiveData(mid));
4114 }
Steve Antondcc3c022017-12-22 16:02:54 -08004115 }
4116 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004117
Steve Antondcc3c022017-12-22 16:02:54 -08004118 // Next, look for transceivers that are newly added (that is, are not stopped
4119 // and not associated). Reuse media sections marked as recyclable first,
4120 // otherwise append to the end of the offer. New media sections should be
4121 // added in the order they were added to the PeerConnection.
4122 for (auto transceiver : transceivers_) {
4123 if (transceiver->mid() || transceiver->stopped()) {
4124 continue;
4125 }
4126 size_t mline_index;
4127 if (!recycleable_mline_indices.empty()) {
4128 mline_index = recycleable_mline_indices.front();
4129 recycleable_mline_indices.pop();
4130 session_options->media_description_options[mline_index] =
4131 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004132 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004133 } else {
4134 mline_index = session_options->media_description_options.size();
4135 session_options->media_description_options.push_back(
4136 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004137 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004138 }
4139 // See comment above for why CreateOffer changes the transceiver's state.
4140 transceiver->internal()->set_mline_index(mline_index);
4141 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004142 // Lastly, add a m-section if we have local data channels and an m section
4143 // does not already exist.
4144 if (!GetDataMid() && HasDataChannels()) {
4145 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004146 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004147 }
Steve Antondcc3c022017-12-22 16:02:54 -08004148}
4149
4150void PeerConnection::GetOptionsForAnswer(
4151 const RTCOfferAnswerOptions& offer_answer_options,
4152 cricket::MediaSessionOptions* session_options) {
4153 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4154
4155 if (IsUnifiedPlan()) {
4156 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4157 } else {
4158 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4159 }
4160
Steve Antonfa2260d2017-12-28 16:38:23 -08004161 // Intentionally unset the data channel type for RTP data channel. Otherwise
4162 // the RTP data channels would be successfully negotiated by default and the
4163 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4164 // We want to leave RTP data channels broken, so people won't try to use them.
4165 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4166 session_options->data_channel_type = data_channel_type();
4167 }
4168
Steve Antondcc3c022017-12-22 16:02:54 -08004169 // Apply ICE renomination flag.
4170 for (auto& options : session_options->media_description_options) {
4171 options.transport_options.enable_ice_renomination =
4172 configuration_.enable_ice_renomination;
4173 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004174
4175 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004176 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004177 session_options->pooled_ice_credentials =
4178 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4179 RTC_FROM_HERE,
4180 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4181 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004182}
4183
Steve Antondcc3c022017-12-22 16:02:54 -08004184void PeerConnection::GetOptionsForPlanBAnswer(
4185 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004186 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004187 // Figure out transceiver directional preferences.
4188 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4189 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4190
4191 // By default, generate sendrecv/recvonly m= sections. The direction is also
4192 // restricted by the direction in the offer.
4193 bool recv_audio = true;
4194 bool recv_video = true;
4195
4196 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004197 if (offer_answer_options.offer_to_receive_audio !=
4198 RTCOfferAnswerOptions::kUndefined) {
4199 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004200 }
Steve Antondcc3c022017-12-22 16:02:54 -08004201 if (offer_answer_options.offer_to_receive_video !=
4202 RTCOfferAnswerOptions::kUndefined) {
4203 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004204 }
4205
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004206 absl::optional<size_t> audio_index;
4207 absl::optional<size_t> video_index;
4208 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004209
4210 // Generate m= sections that match those in the offer.
4211 // Note that mediasession.cc will handle intersection our preferred
4212 // direction with the offered direction.
4213 GenerateMediaDescriptionOptions(
4214 remote_description(),
4215 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4216 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4217 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004218
4219 cricket::MediaDescriptionOptions* audio_media_description_options =
4220 !audio_index ? nullptr
4221 : &session_options->media_description_options[*audio_index];
4222 cricket::MediaDescriptionOptions* video_media_description_options =
4223 !video_index ? nullptr
4224 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004225
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004226 AddPlanBRtpSenderOptions(GetSendersInternal(),
4227 audio_media_description_options,
4228 video_media_description_options,
4229 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004230}
zhihuangaf388472016-11-02 16:49:48 -07004231
Steve Antondcc3c022017-12-22 16:02:54 -08004232void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4233 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4234 cricket::MediaSessionOptions* session_options) {
4235 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4236 // Answers) and 5.3.2 (Subsequent Answers).
4237 RTC_DCHECK(remote_description());
4238 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4239 for (const ContentInfo& content :
4240 remote_description()->description()->contents()) {
4241 cricket::MediaType media_type = content.media_description()->type();
4242 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4243 media_type == cricket::MEDIA_TYPE_VIDEO) {
4244 auto transceiver = GetAssociatedTransceiver(content.name);
4245 RTC_CHECK(transceiver);
4246 session_options->media_description_options.push_back(
4247 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4248 } else {
4249 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004250 // Reject all data sections if data channels are disabled.
4251 // Reject a data section if it has already been rejected.
4252 // Reject all data sections except for the first one.
4253 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4254 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004255 session_options->media_description_options.push_back(
4256 GetMediaDescriptionOptionsForRejectedData(content.name));
4257 } else {
4258 session_options->media_description_options.push_back(
4259 GetMediaDescriptionOptionsForActiveData(content.name));
4260 }
Steve Antondcc3c022017-12-22 16:02:54 -08004261 }
4262 }
htaa2a49d92016-03-04 02:51:39 -08004263}
4264
zhihuang1c378ed2017-08-17 14:10:50 -07004265void PeerConnection::GenerateMediaDescriptionOptions(
4266 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004267 RtpTransceiverDirection audio_direction,
4268 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004269 absl::optional<size_t>* audio_index,
4270 absl::optional<size_t>* video_index,
4271 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004272 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004273 for (const cricket::ContentInfo& content :
4274 session_desc->description()->contents()) {
4275 if (IsAudioContent(&content)) {
4276 // If we already have an audio m= section, reject this extra one.
4277 if (*audio_index) {
4278 session_options->media_description_options.push_back(
4279 cricket::MediaDescriptionOptions(
4280 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004281 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004282 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004283 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004284 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004285 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4286 content.name, audio_direction,
4287 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004288 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004289 }
4290 } else if (IsVideoContent(&content)) {
4291 // If we already have an video m= section, reject this extra one.
4292 if (*video_index) {
4293 session_options->media_description_options.push_back(
4294 cricket::MediaDescriptionOptions(
4295 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004296 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004297 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004298 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004299 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004300 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4301 content.name, video_direction,
4302 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004303 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004304 }
4305 } else {
4306 RTC_DCHECK(IsDataContent(&content));
4307 // If we already have an data m= section, reject this extra one.
4308 if (*data_index) {
4309 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004310 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004311 } else {
4312 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004313 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004314 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004315 }
4316 }
htaa2a49d92016-03-04 02:51:39 -08004317 }
deadbeefab9b2d12015-10-14 11:33:11 -07004318}
4319
Steve Antonfa2260d2017-12-28 16:38:23 -08004320cricket::MediaDescriptionOptions
4321PeerConnection::GetMediaDescriptionOptionsForActiveData(
4322 const std::string& mid) const {
4323 // Direction for data sections is meaningless, but legacy endpoints might
4324 // expect sendrecv.
4325 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4326 RtpTransceiverDirection::kSendRecv,
4327 /*stopped=*/false);
4328 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4329 return options;
4330}
4331
4332cricket::MediaDescriptionOptions
4333PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4334 const std::string& mid) const {
4335 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4336 RtpTransceiverDirection::kInactive,
4337 /*stopped=*/true);
4338 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4339 return options;
4340}
4341
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004342absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004343 switch (data_channel_type_) {
4344 case cricket::DCT_RTP:
4345 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004346 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004347 }
4348 return rtp_data_channel_->content_name();
4349 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004350 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004351 case cricket::DCT_MEDIA_TRANSPORT:
4352 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004353 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004354 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004355 }
4356}
4357
Steve Anton4171afb2017-11-20 10:20:22 -08004358void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4359 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4360 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004361 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004362}
4363
Steve Anton4171afb2017-11-20 10:20:22 -08004364void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004365 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004366 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004367 cricket::MediaType media_type,
4368 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004369 RTC_DCHECK(!IsUnifiedPlan());
4370
Steve Anton4171afb2017-11-20 10:20:22 -08004371 std::vector<RtpSenderInfo>* current_senders =
4372 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004373
Steve Anton4171afb2017-11-20 10:20:22 -08004374 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004375 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004376 for (auto sender_it = current_senders->begin();
4377 sender_it != current_senders->end();
4378 /* incremented manually */) {
4379 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004380 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004381 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004382 std::string params_stream_id;
4383 if (params) {
4384 params_stream_id =
4385 (!params->first_stream_id().empty() ? params->first_stream_id()
4386 : kDefaultStreamId);
4387 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004388 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004389 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004390 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004391 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004392 sender_exists) {
4393 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004394 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004395 OnRemoteSenderRemoved(info, media_type);
4396 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004397 }
4398 }
4399
Steve Anton4171afb2017-11-20 10:20:22 -08004400 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004401 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004402 if (!params.has_ssrcs()) {
4403 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4404 // sender, this means it is coming from a Unified Plan endpoint,so we just
4405 // create a default.
4406 default_sender_needed = true;
4407 break;
4408 }
4409
Seth Hampson845e8782018-03-02 11:34:10 -08004410 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004411 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004412 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4413 // not supported in Plan B, we just take the first here and create the
4414 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004415 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004416 (!params.first_stream_id().empty() ? params.first_stream_id()
4417 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004418 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004419 uint32_t ssrc = params.first_ssrc();
4420
4421 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004422 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004423 if (!stream) {
4424 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004425 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004426 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004427 remote_streams_->AddStream(stream);
4428 new_streams->AddStream(stream);
4429 }
4430
Steve Anton4171afb2017-11-20 10:20:22 -08004431 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004432 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004433 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004434 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004435 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004436 }
4437 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004438
Steve Anton4171afb2017-11-20 10:20:22 -08004439 // Add default sender if necessary.
4440 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004441 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004442 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004443 if (!default_stream) {
4444 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004445 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004446 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004447 remote_streams_->AddStream(default_stream);
4448 new_streams->AddStream(default_stream);
4449 }
Steve Anton4171afb2017-11-20 10:20:22 -08004450 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4451 ? kDefaultAudioSenderId
4452 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004453 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004454 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004455 if (!default_sender_info) {
4456 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004457 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004458 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004459 }
4460 }
deadbeefab9b2d12015-10-14 11:33:11 -07004461}
4462
Steve Anton4171afb2017-11-20 10:20:22 -08004463void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4464 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004465 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4466 << " receiver for track_id=" << sender_info.sender_id
4467 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004468
Steve Anton3d954a62018-04-02 11:27:23 -07004469 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004470 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004471 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004472 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004473 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004474 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004475 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004476 }
4477}
4478
Steve Anton4171afb2017-11-20 10:20:22 -08004479void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4480 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004481 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4482 << " receiver for track_id=" << sender_info.sender_id
4483 << " and stream_id=" << sender_info.stream_id;
4484
Seth Hampson845e8782018-03-02 11:34:10 -08004485 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004486
Henrik Boström933d8b02017-10-10 10:05:16 -07004487 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004488 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004489 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4490 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004491 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004492 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004493 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004494 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004495 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004496 }
4497 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004498 // Stopping or destroying a VideoRtpReceiver will end the
4499 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004500 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004501 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004502 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004503 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004504 // There's no guarantee the track is still available, e.g. the track may
4505 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004506 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004507 }
4508 } else {
nisseede5da42017-01-12 05:15:36 -08004509 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004510 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004511 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004512 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004513 }
deadbeefab9b2d12015-10-14 11:33:11 -07004514}
4515
4516void PeerConnection::UpdateEndedRemoteMediaStreams() {
4517 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4518 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4519 MediaStreamInterface* stream = remote_streams_->at(i);
4520 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4521 streams_to_remove.push_back(stream);
4522 }
4523 }
4524
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004525 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004526 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004527 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004528 }
4529}
4530
Steve Anton4171afb2017-11-20 10:20:22 -08004531void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004532 const std::vector<cricket::StreamParams>& streams,
4533 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004534 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004535
Seth Hampson845e8782018-03-02 11:34:10 -08004536 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004537 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004538 for (auto sender_it = current_senders->begin();
4539 sender_it != current_senders->end();
4540 /* incremented manually */) {
4541 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004542 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004543 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4544 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004545 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004546 OnLocalSenderRemoved(info, media_type);
4547 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004548 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004549 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004550 }
4551 }
4552
Steve Anton4171afb2017-11-20 10:20:22 -08004553 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004554 for (const cricket::StreamParams& params : streams) {
4555 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004556 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004557 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004558 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004559 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004560 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004561 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004562 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004563 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004564 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004565 }
4566 }
4567}
4568
Steve Anton4171afb2017-11-20 10:20:22 -08004569void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4570 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004571 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004572 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004573 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004574 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4575 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004576 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004577 return;
4578 }
4579
deadbeeffac06552015-11-25 11:26:01 -08004580 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004581 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004582 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004583 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004584 }
deadbeeffac06552015-11-25 11:26:01 -08004585
Seth Hampson5b4f0752018-04-02 16:31:36 -07004586 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004587 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004588}
4589
Steve Anton4171afb2017-11-20 10:20:22 -08004590void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4591 cricket::MediaType media_type) {
4592 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004593 if (!sender) {
4594 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004595 // SessionDescriptions has been renegotiated.
4596 return;
4597 }
deadbeeffac06552015-11-25 11:26:01 -08004598
4599 // A sender has been removed from the SessionDescription but it's still
4600 // associated with the PeerConnection. This only occurs if the SDP doesn't
4601 // match with the calls to CreateSender, AddStream and RemoveStream.
4602 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004603 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004604 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004605 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004606 }
deadbeeffac06552015-11-25 11:26:01 -08004607
Steve Anton4171afb2017-11-20 10:20:22 -08004608 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004609}
4610
4611void PeerConnection::UpdateLocalRtpDataChannels(
4612 const cricket::StreamParamsVec& streams) {
4613 std::vector<std::string> existing_channels;
4614
4615 // Find new and active data channels.
4616 for (const cricket::StreamParams& params : streams) {
4617 // |it->sync_label| is actually the data channel label. The reason is that
4618 // we use the same naming of data channels as we do for
4619 // MediaStreams and Tracks.
4620 // For MediaStreams, the sync_label is the MediaStream label and the
4621 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004622 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004623 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004624 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004625 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004626 continue;
4627 }
4628 // Set the SSRC the data channel should use for sending.
4629 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4630 existing_channels.push_back(data_channel_it->first);
4631 }
4632
4633 UpdateClosingRtpDataChannels(existing_channels, true);
4634}
4635
4636void PeerConnection::UpdateRemoteRtpDataChannels(
4637 const cricket::StreamParamsVec& streams) {
4638 std::vector<std::string> existing_channels;
4639
4640 // Find new and active data channels.
4641 for (const cricket::StreamParams& params : streams) {
4642 // The data channel label is either the mslabel or the SSRC if the mslabel
4643 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004644 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004645 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004646 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004647 auto data_channel_it = rtp_data_channels_.find(label);
4648 if (data_channel_it == rtp_data_channels_.end()) {
4649 // This is a new data channel.
4650 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4651 } else {
4652 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4653 }
4654 existing_channels.push_back(label);
4655 }
4656
4657 UpdateClosingRtpDataChannels(existing_channels, false);
4658}
4659
4660void PeerConnection::UpdateClosingRtpDataChannels(
4661 const std::vector<std::string>& active_channels,
4662 bool is_local_update) {
4663 auto it = rtp_data_channels_.begin();
4664 while (it != rtp_data_channels_.end()) {
4665 DataChannel* data_channel = it->second;
4666 if (std::find(active_channels.begin(), active_channels.end(),
4667 data_channel->label()) != active_channels.end()) {
4668 ++it;
4669 continue;
4670 }
4671
4672 if (is_local_update) {
4673 data_channel->SetSendSsrc(0);
4674 } else {
4675 data_channel->RemotePeerRequestClose();
4676 }
4677
4678 if (data_channel->state() == DataChannel::kClosed) {
4679 rtp_data_channels_.erase(it);
4680 it = rtp_data_channels_.begin();
4681 } else {
4682 ++it;
4683 }
4684 }
4685}
4686
4687void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4688 uint32_t remote_ssrc) {
4689 rtc::scoped_refptr<DataChannel> channel(
4690 InternalCreateDataChannel(label, nullptr));
4691 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004692 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004693 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004694 return;
4695 }
4696 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004697 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4698 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004699 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004700}
4701
4702rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4703 const std::string& label,
4704 const InternalDataChannelInit* config) {
4705 if (IsClosed()) {
4706 return nullptr;
4707 }
Steve Anton75737c02017-11-06 10:37:17 -08004708 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004709 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004710 << "InternalCreateDataChannel: Data is not supported in this call.";
4711 return nullptr;
4712 }
4713 InternalDataChannelInit new_config =
4714 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004715 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004716 if (new_config.id < 0) {
4717 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004718 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004719 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004720 RTC_LOG(LS_ERROR)
4721 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004722 return nullptr;
4723 }
4724 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004725 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004726 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004727 return nullptr;
4728 }
4729 }
4730
Steve Anton75737c02017-11-06 10:37:17 -08004731 rtc::scoped_refptr<DataChannel> channel(
4732 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004733 if (!channel) {
4734 sid_allocator_.ReleaseSid(new_config.id);
4735 return nullptr;
4736 }
4737
4738 if (channel->data_channel_type() == cricket::DCT_RTP) {
4739 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004740 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4741 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004742 return nullptr;
4743 }
4744 rtp_data_channels_[channel->label()] = channel;
4745 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004746 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004747 sctp_data_channels_.push_back(channel);
4748 channel->SignalClosed.connect(this,
4749 &PeerConnection::OnSctpDataChannelClosed);
4750 }
4751
Steve Anton2d8609c2018-01-23 16:38:46 -08004752 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004753 return channel;
4754}
4755
4756bool PeerConnection::HasDataChannels() const {
4757 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4758}
4759
4760void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4761 for (const auto& channel : sctp_data_channels_) {
4762 if (channel->id() < 0) {
4763 int sid;
4764 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004765 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004766 continue;
4767 }
4768 channel->SetSctpSid(sid);
4769 }
4770 }
4771}
4772
4773void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004774 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004775 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4776 ++it) {
4777 if (it->get() == channel) {
4778 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004779 // After the closing procedure is done, it's safe to use this ID for
4780 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004781 sid_allocator_.ReleaseSid(channel->id());
4782 }
deadbeefbd292462015-12-14 18:15:29 -08004783 // Since this method is triggered by a signal from the DataChannel,
4784 // we can't free it directly here; we need to free it asynchronously.
4785 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004786 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004787 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4788 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004789 return;
4790 }
4791 }
4792}
4793
deadbeefab9b2d12015-10-14 11:33:11 -07004794void PeerConnection::OnDataChannelDestroyed() {
4795 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4796 // DataChannel may callback to us and try to modify the list.
4797 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4798 temp_rtp_dcs.swap(rtp_data_channels_);
4799 for (const auto& kv : temp_rtp_dcs) {
4800 kv.second->OnTransportChannelDestroyed();
4801 }
4802
4803 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4804 temp_sctp_dcs.swap(sctp_data_channels_);
4805 for (const auto& channel : temp_sctp_dcs) {
4806 channel->OnTransportChannelDestroyed();
4807 }
4808}
4809
4810void PeerConnection::OnDataChannelOpenMessage(
4811 const std::string& label,
4812 const InternalDataChannelInit& config) {
4813 rtc::scoped_refptr<DataChannel> channel(
4814 InternalCreateDataChannel(label, &config));
4815 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004816 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004817 return;
4818 }
4819
deadbeefa601f5c2016-06-06 14:27:39 -07004820 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4821 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004822 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004823 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004824}
4825
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004826bool PeerConnection::HandleOpenMessage_s(
4827 const cricket::ReceiveDataParams& params,
4828 const rtc::CopyOnWriteBuffer& buffer) {
4829 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4830 // Received OPEN message; parse and signal that a new data channel should
4831 // be created.
4832 std::string label;
4833 InternalDataChannelInit config;
4834 config.id = params.ssrc;
4835 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4836 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4837 << params.ssrc;
4838 return true;
4839 }
4840 config.open_handshake_role = InternalDataChannelInit::kAcker;
4841 OnDataChannelOpenMessage(label, config);
4842 return true;
4843 }
4844 return false;
4845}
4846
Steve Anton4171afb2017-11-20 10:20:22 -08004847rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4848PeerConnection::GetAudioTransceiver() const {
4849 // This method only works with Plan B SDP, where there is a single
4850 // audio/video transceiver.
4851 RTC_DCHECK(!IsUnifiedPlan());
4852 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004853 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004854 return transceiver;
4855 }
4856 }
4857 RTC_NOTREACHED();
4858 return nullptr;
4859}
4860
4861rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4862PeerConnection::GetVideoTransceiver() const {
4863 // This method only works with Plan B SDP, where there is a single
4864 // audio/video transceiver.
4865 RTC_DCHECK(!IsUnifiedPlan());
4866 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004867 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004868 return transceiver;
4869 }
4870 }
4871 RTC_NOTREACHED();
4872 return nullptr;
4873}
4874
4875// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4876// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004877bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004878 switch (type) {
4879 case cricket::MEDIA_TYPE_AUDIO:
4880 return !GetAudioTransceiver()->internal()->senders().empty();
4881 case cricket::MEDIA_TYPE_VIDEO:
4882 return !GetVideoTransceiver()->internal()->senders().empty();
4883 case cricket::MEDIA_TYPE_DATA:
4884 return false;
4885 }
4886 RTC_NOTREACHED();
4887 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004888}
4889
Steve Anton4171afb2017-11-20 10:20:22 -08004890rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4891PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4892 for (auto transceiver : transceivers_) {
4893 for (auto sender : transceiver->internal()->senders()) {
4894 if (sender->track() == track) {
4895 return sender;
4896 }
4897 }
4898 }
4899 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004900}
4901
Steve Anton4171afb2017-11-20 10:20:22 -08004902rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4903PeerConnection::FindSenderById(const std::string& sender_id) const {
4904 for (auto transceiver : transceivers_) {
4905 for (auto sender : transceiver->internal()->senders()) {
4906 if (sender->id() == sender_id) {
4907 return sender;
4908 }
4909 }
4910 }
4911 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004912}
4913
Steve Anton4171afb2017-11-20 10:20:22 -08004914rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4915PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4916 for (auto transceiver : transceivers_) {
4917 for (auto receiver : transceiver->internal()->receivers()) {
4918 if (receiver->id() == receiver_id) {
4919 return receiver;
4920 }
4921 }
4922 }
4923 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004924}
4925
Steve Anton4171afb2017-11-20 10:20:22 -08004926std::vector<PeerConnection::RtpSenderInfo>*
4927PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4928 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4929 media_type == cricket::MEDIA_TYPE_VIDEO);
4930 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4931 ? &remote_audio_sender_infos_
4932 : &remote_video_sender_infos_;
4933}
4934
4935std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004936 cricket::MediaType media_type) {
4937 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4938 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004939 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4940 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004941}
4942
Steve Anton4171afb2017-11-20 10:20:22 -08004943const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4944 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004945 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004946 const std::string sender_id) const {
4947 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004948 if (sender_info.stream_id == stream_id &&
4949 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004950 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004951 }
4952 }
4953 return nullptr;
4954}
4955
4956DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4957 for (const auto& channel : sctp_data_channels_) {
4958 if (channel->id() == sid) {
4959 return channel;
4960 }
4961 }
4962 return nullptr;
4963}
4964
deadbeef91dd5672016-05-18 16:55:30 -07004965bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004966 const cricket::ServerAddresses& stun_servers,
4967 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004968 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004969 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004970 // To handle both internal and externally created port allocator, we will
4971 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004972 port_allocator_flags_ = port_allocator_->flags();
4973 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4974 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4975 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004976 // If the disable-IPv6 flag was specified, we'll not override it
4977 // by experiment.
4978 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004979 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004980 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4981 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004982 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004983 }
4984
zhihuangb09b3f92017-03-07 14:40:51 -08004985 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004986 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004987 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004988 }
4989
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004990 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004991 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004992 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004993 }
4994
honghaiz60347052016-05-31 18:29:12 -07004995 if (configuration.candidate_network_policy ==
4996 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004997 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004998 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004999 }
5000
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005001 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005002 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005003 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5004 }
5005
Qingsi Wanga2d60672018-04-11 16:57:45 -07005006 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005007 // No step delay is used while allocating ports.
5008 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5009 port_allocator_->set_candidate_filter(
5010 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005011 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005012
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005013 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005014 for (auto& turn_server : turn_servers_copy) {
5015 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005016 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005017 // Call this last since it may create pooled allocator sessions using the
5018 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005019 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005020 stun_servers, std::move(turn_servers_copy),
5021 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5022 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005023 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005024 return true;
5025}
5026
deadbeef91dd5672016-05-18 16:55:30 -07005027bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005028 const cricket::ServerAddresses& stun_servers,
5029 const std::vector<cricket::RelayServerConfig>& turn_servers,
5030 IceTransportsType type,
5031 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005032 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005033 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005034 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005035 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005036 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005037 // According to JSEP, after setLocalDescription, changing the candidate pool
5038 // size is not allowed, and changing the set of ICE servers will not result
5039 // in new candidates being gathered.
5040 if (local_description()) {
5041 port_allocator_->FreezeCandidatePool();
5042 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005043 // Add the custom tls turn servers if they exist.
5044 auto turn_servers_copy = turn_servers;
5045 for (auto& turn_server : turn_servers_copy) {
5046 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5047 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005048 // Call this last since it may create pooled allocator sessions using the
5049 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005050 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005051 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5052 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005053}
5054
Steve Antonba818672017-11-06 10:21:57 -08005055cricket::ChannelManager* PeerConnection::channel_manager() const {
5056 return factory_->channel_manager();
5057}
5058
Elad Alon99c3fe52017-10-13 16:29:40 +02005059bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005060 std::unique_ptr<RtcEventLogOutput> output,
5061 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005062 if (!event_log_) {
5063 return false;
5064 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005065 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005066}
5067
5068void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005069 if (event_log_) {
5070 event_log_->StopLogging();
5071 }
ivoc14d5dbe2016-07-04 07:06:55 -07005072}
nisseeaabdf62017-05-05 02:23:02 -07005073
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005074cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005075 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005076 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005077 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005078 if (channel && channel->content_name() == content_name) {
5079 return channel;
5080 }
Steve Anton75737c02017-11-06 10:37:17 -08005081 }
5082 if (rtp_data_channel() &&
5083 rtp_data_channel()->content_name() == content_name) {
5084 return rtp_data_channel();
5085 }
5086 return nullptr;
5087}
5088
5089bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005090 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005091 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005092 RTC_LOG(LS_INFO)
5093 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005094 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005095 return false;
5096 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005097 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005098 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005099 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005100 return false;
5101 }
5102
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005103 absl::optional<rtc::SSLRole> dtls_role;
5104 if (sctp_mid_) {
5105 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5106 } else if (is_caller_) {
5107 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5108 }
Zhi Huange830e682018-03-30 10:48:35 -07005109 if (dtls_role) {
5110 *role = *dtls_role;
5111 return true;
5112 }
5113 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005114}
5115
5116bool PeerConnection::GetSslRole(const std::string& content_name,
5117 rtc::SSLRole* role) {
5118 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005119 RTC_LOG(LS_INFO)
5120 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005121 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005122 return false;
5123 }
5124
Zhi Huange830e682018-03-30 10:48:35 -07005125 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5126 if (dtls_role) {
5127 *role = *dtls_role;
5128 return true;
5129 }
5130 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005131}
5132
Steve Antonf8470812017-12-04 10:46:21 -08005133void PeerConnection::SetSessionError(SessionError error,
5134 const std::string& error_desc) {
5135 RTC_DCHECK_RUN_ON(signaling_thread());
5136 if (error != session_error_) {
5137 session_error_ = error;
5138 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005139 }
5140}
5141
Zhi Huange830e682018-03-30 10:48:35 -07005142RTCError PeerConnection::UpdateSessionState(
5143 SdpType type,
5144 cricket::ContentSource source,
5145 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005146 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005147
5148 // If there's already a pending error then no state transition should happen.
5149 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005150 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005151
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005152 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005153 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005154 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005155 }
5156
5157 // Update the signaling state according to the specified state machine (see
5158 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005159 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005160 ChangeSignalingState(source == cricket::CS_LOCAL
5161 ? PeerConnectionInterface::kHaveLocalOffer
5162 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005163 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005164 ChangeSignalingState(source == cricket::CS_LOCAL
5165 ? PeerConnectionInterface::kHaveLocalPrAnswer
5166 : PeerConnectionInterface::kHaveRemotePrAnswer);
5167 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005168 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005169 ChangeSignalingState(PeerConnectionInterface::kStable);
5170 }
5171
5172 // Update internal objects according to the session description's media
5173 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005174 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005175 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005176 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005177 }
5178
Steve Anton8a006912017-12-04 15:25:56 -08005179 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005180}
5181
Steve Anton8a006912017-12-04 15:25:56 -08005182RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005183 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005184 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005185 const SessionDescriptionInterface* sdesc =
5186 (source == cricket::CS_LOCAL ? local_description()
5187 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005188 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005189
5190 // Push down the new SDP media section for each audio/video transceiver.
5191 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005192 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005193 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005194 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005195 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005196 continue;
5197 }
5198 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005199 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005200 if (!content_desc) {
5201 continue;
5202 }
5203 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005204 bool success = (source == cricket::CS_LOCAL)
5205 ? channel->SetLocalContent(content_desc, type, &error)
5206 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005207 if (!success) {
5208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5209 }
5210 }
5211
5212 // If using the RtpDataChannel, push down the new SDP section for it too.
5213 if (rtp_data_channel_) {
5214 const ContentInfo* data_content =
5215 cricket::GetFirstDataContent(sdesc->description());
5216 if (data_content && !data_content->rejected) {
5217 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005218 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005219 if (data_desc) {
5220 std::string error;
5221 bool success =
5222 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005223 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005224 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005225 if (!success) {
5226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5227 std::move(error));
5228 }
Steve Anton75737c02017-11-06 10:37:17 -08005229 }
5230 }
5231 }
Steve Antoned10bd92017-12-05 10:52:59 -08005232
Steve Anton75737c02017-11-06 10:37:17 -08005233 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5234 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5235 if (sctp_transport_ && local_description() && remote_description() &&
5236 cricket::GetFirstDataContent(local_description()->description()) &&
5237 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005238 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005239 RTC_FROM_HERE,
5240 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005241 if (!success) {
5242 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5243 "Failed to push down SCTP parameters.");
5244 }
Steve Anton75737c02017-11-06 10:37:17 -08005245 }
Steve Antoned10bd92017-12-05 10:52:59 -08005246
Steve Anton8a006912017-12-04 15:25:56 -08005247 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005248}
5249
5250bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5251 RTC_DCHECK(network_thread()->IsCurrent());
5252 RTC_DCHECK(local_description());
5253 RTC_DCHECK(remote_description());
5254 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5255 // When we support "max-message-size", that would also be pushed down here.
5256 return sctp_transport_->Start(
5257 GetSctpPort(local_description()->description()),
5258 GetSctpPort(remote_description()->description()));
5259}
5260
Steve Anton8a006912017-12-04 15:25:56 -08005261RTCError PeerConnection::PushdownTransportDescription(
5262 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005263 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005264 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005265
Zhi Huange830e682018-03-30 10:48:35 -07005266 if (source == cricket::CS_LOCAL) {
5267 const SessionDescriptionInterface* sdesc = local_description();
5268 RTC_DCHECK(sdesc);
5269 return transport_controller_->SetLocalDescription(type,
5270 sdesc->description());
5271 } else {
5272 const SessionDescriptionInterface* sdesc = remote_description();
5273 RTC_DCHECK(sdesc);
5274 return transport_controller_->SetRemoteDescription(type,
5275 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005276 }
Steve Anton75737c02017-11-06 10:37:17 -08005277}
5278
5279bool PeerConnection::GetTransportDescription(
5280 const SessionDescription* description,
5281 const std::string& content_name,
5282 cricket::TransportDescription* tdesc) {
5283 if (!description || !tdesc) {
5284 return false;
5285 }
5286 const TransportInfo* transport_info =
5287 description->GetTransportInfoByName(content_name);
5288 if (!transport_info) {
5289 return false;
5290 }
5291 *tdesc = transport_info->description;
5292 return true;
5293}
5294
Steve Anton75737c02017-11-06 10:37:17 -08005295cricket::IceConfig PeerConnection::ParseIceConfig(
5296 const PeerConnectionInterface::RTCConfiguration& config) const {
5297 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005298 switch (config.continual_gathering_policy) {
5299 case PeerConnectionInterface::GATHER_ONCE:
5300 gathering_policy = cricket::GATHER_ONCE;
5301 break;
5302 case PeerConnectionInterface::GATHER_CONTINUALLY:
5303 gathering_policy = cricket::GATHER_CONTINUALLY;
5304 break;
5305 default:
5306 RTC_NOTREACHED();
5307 gathering_policy = cricket::GATHER_ONCE;
5308 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005309
Steve Anton75737c02017-11-06 10:37:17 -08005310 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005311 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5312 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005313 ice_config.prioritize_most_likely_candidate_pairs =
5314 config.prioritize_most_likely_ice_candidate_pairs;
5315 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005316 RTCConfigurationToIceConfigOptionalInt(
5317 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005318 ice_config.continual_gathering_policy = gathering_policy;
5319 ice_config.presume_writable_when_fully_relayed =
5320 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005321 ice_config.ice_check_interval_strong_connectivity =
5322 config.ice_check_interval_strong_connectivity;
5323 ice_config.ice_check_interval_weak_connectivity =
5324 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005325 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005326 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5327 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005328 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005329 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005330 ice_config.regather_all_networks_interval_range =
5331 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005332 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005333 return ice_config;
5334}
5335
Steve Antona41959e2018-11-28 11:15:33 -08005336static absl::string_view GetTrackIdBySsrc(
5337 const SessionDescriptionInterface* session_description,
5338 uint32_t ssrc) {
5339 if (!session_description) {
5340 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005341 }
Steve Antona41959e2018-11-28 11:15:33 -08005342 for (const cricket::ContentInfo& content :
5343 session_description->description()->contents()) {
5344 const cricket::MediaContentDescription& media =
5345 *content.media_description();
5346 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5347 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5348 const cricket::StreamParams* stream_params =
5349 cricket::GetStreamBySsrc(media.streams(), ssrc);
5350 if (stream_params) {
5351 return stream_params->id;
5352 }
5353 }
5354 }
5355 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005356}
5357
Steve Antona41959e2018-11-28 11:15:33 -08005358absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5359 return GetTrackIdBySsrc(local_description(), ssrc);
5360}
5361
5362absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5363 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005364}
5365
5366bool PeerConnection::SendData(const cricket::SendDataParams& params,
5367 const rtc::CopyOnWriteBuffer& payload,
5368 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005369 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5370 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5371 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005372 return false;
5373 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005374 if (media_transport_) {
5375 SendDataParams send_params;
5376 send_params.type = ToWebrtcDataMessageType(params.type);
5377 send_params.ordered = params.ordered;
5378 if (params.max_rtx_count >= 0) {
5379 send_params.max_rtx_count = params.max_rtx_count;
5380 } else if (params.max_rtx_ms >= 0) {
5381 send_params.max_rtx_ms = params.max_rtx_ms;
5382 }
5383 return media_transport_->SendData(params.sid, send_params, payload).ok();
5384 }
Steve Anton75737c02017-11-06 10:37:17 -08005385 return rtp_data_channel_
5386 ? rtp_data_channel_->SendData(params, payload, result)
5387 : network_thread()->Invoke<bool>(
5388 RTC_FROM_HERE,
5389 Bind(&cricket::SctpTransportInternal::SendData,
5390 sctp_transport_.get(), params, payload, result));
5391}
5392
5393bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005394 RTC_DCHECK_RUN_ON(signaling_thread());
5395 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005396 // Don't log an error here, because DataChannels are expected to call
5397 // ConnectDataChannel in this state. It's the only way to initially tell
5398 // whether or not the underlying transport is ready.
5399 return false;
5400 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005401 if (media_transport_) {
5402 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5403 &DataChannel::OnChannelReady);
5404 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5405 &DataChannel::OnDataReceived);
5406 SignalMediaTransportChannelClosing_s.connect(
5407 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5408 SignalMediaTransportChannelClosed_s.connect(
5409 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5410 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005411 rtp_data_channel_->SignalReadyToSendData.connect(
5412 webrtc_data_channel, &DataChannel::OnChannelReady);
5413 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5414 &DataChannel::OnDataReceived);
5415 } else {
5416 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5417 &DataChannel::OnChannelReady);
5418 SignalSctpDataReceived.connect(webrtc_data_channel,
5419 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005420 SignalSctpClosingProcedureStartedRemotely.connect(
5421 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5422 SignalSctpClosingProcedureComplete.connect(
5423 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005424 }
5425 return true;
5426}
5427
5428void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005429 RTC_DCHECK_RUN_ON(signaling_thread());
5430 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005431 RTC_LOG(LS_ERROR)
5432 << "DisconnectDataChannel called when rtp_data_channel_ and "
5433 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005434 return;
5435 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005436 if (media_transport_) {
5437 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5438 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5439 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5440 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5441 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005442 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5443 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5444 } else {
5445 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5446 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005447 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5448 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005449 }
5450}
5451
5452void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005453 if (media_transport_) {
5454 // No-op. Media transport does not need to add streams.
5455 return;
5456 }
Steve Anton75737c02017-11-06 10:37:17 -08005457 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005458 RTC_LOG(LS_ERROR)
5459 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005460 return;
5461 }
5462 network_thread()->Invoke<void>(
5463 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5464 sctp_transport_.get(), sid));
5465}
5466
5467void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005468 if (media_transport_) {
5469 media_transport_->CloseChannel(sid);
5470 return;
5471 }
Steve Anton75737c02017-11-06 10:37:17 -08005472 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005473 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005474 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005475 return;
5476 }
5477 network_thread()->Invoke<void>(
5478 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5479 sctp_transport_.get(), sid));
5480}
5481
5482bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005483 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005484 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005485 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005486 sctp_ready_to_send_data_;
5487}
5488
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005489void PeerConnection::OnDataReceived(int channel_id,
5490 DataMessageType type,
5491 const rtc::CopyOnWriteBuffer& buffer) {
5492 cricket::ReceiveDataParams params;
5493 params.sid = channel_id;
5494 params.type = ToCricketDataMessageType(type);
5495 media_transport_invoker_->AsyncInvoke<void>(
5496 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5497 RTC_DCHECK_RUN_ON(signaling_thread());
5498 if (!HandleOpenMessage_s(params, buffer)) {
5499 SignalMediaTransportReceivedData_s(params, buffer);
5500 }
5501 });
5502}
5503
5504void PeerConnection::OnChannelClosing(int channel_id) {
5505 media_transport_invoker_->AsyncInvoke<void>(
5506 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5507 RTC_DCHECK_RUN_ON(signaling_thread());
5508 SignalMediaTransportChannelClosing_s(channel_id);
5509 });
5510}
5511
5512void PeerConnection::OnChannelClosed(int channel_id) {
5513 media_transport_invoker_->AsyncInvoke<void>(
5514 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5515 RTC_DCHECK_RUN_ON(signaling_thread());
5516 SignalMediaTransportChannelClosed_s(channel_id);
5517 });
5518}
5519
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005520absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005521 if (sctp_mid_ && transport_controller_) {
5522 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5523 if (dtls_transport) {
5524 return dtls_transport->transport_name();
5525 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005526 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005527 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005528 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005529}
5530
Qingsi Wang72a43a12018-02-20 16:03:18 -08005531cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5532 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005533 network_thread()->Invoke<void>(
5534 RTC_FROM_HERE,
5535 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5536 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005537 return candidate_states_list;
5538}
5539
Steve Anton5dfde182018-02-06 10:34:40 -08005540std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5541 const {
5542 std::map<std::string, std::string> transport_names_by_mid;
5543 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005544 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005545 if (channel) {
5546 transport_names_by_mid[channel->content_name()] =
5547 channel->transport_name();
5548 }
Steve Anton75737c02017-11-06 10:37:17 -08005549 }
Steve Anton5dfde182018-02-06 10:34:40 -08005550 if (rtp_data_channel_) {
5551 transport_names_by_mid[rtp_data_channel_->content_name()] =
5552 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005553 }
5554 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005555 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005556 RTC_DCHECK(transport_name);
5557 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005558 }
Steve Anton5dfde182018-02-06 10:34:40 -08005559 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005560}
5561
Steve Anton5dfde182018-02-06 10:34:40 -08005562std::map<std::string, cricket::TransportStats>
5563PeerConnection::GetTransportStatsByNames(
5564 const std::set<std::string>& transport_names) {
5565 if (!network_thread()->IsCurrent()) {
5566 return network_thread()
5567 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5568 RTC_FROM_HERE,
5569 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005570 }
Steve Anton5dfde182018-02-06 10:34:40 -08005571 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5572 for (const std::string& transport_name : transport_names) {
5573 cricket::TransportStats transport_stats;
5574 bool success =
5575 transport_controller_->GetStats(transport_name, &transport_stats);
5576 if (success) {
5577 transport_stats_by_name[transport_name] = std::move(transport_stats);
5578 } else {
5579 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5580 << transport_name;
5581 }
5582 }
5583 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005584}
5585
5586bool PeerConnection::GetLocalCertificate(
5587 const std::string& transport_name,
5588 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005589 if (!certificate) {
5590 return false;
5591 }
5592 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5593 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005594}
5595
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005596std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005597 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005598 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005599}
5600
5601cricket::DataChannelType PeerConnection::data_channel_type() const {
5602 return data_channel_type_;
5603}
5604
5605bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5606 return pending_ice_restarts_.find(content_name) !=
5607 pending_ice_restarts_.end();
5608}
5609
Steve Anton75737c02017-11-06 10:37:17 -08005610bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5611 return transport_controller_->NeedsIceRestart(content_name);
5612}
5613
5614void PeerConnection::OnCertificateReady(
5615 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5616 transport_controller_->SetLocalCertificate(certificate);
5617}
5618
5619void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005620 SetSessionError(SessionError::kTransport,
5621 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005622}
5623
Alex Loiko9289eda2018-11-23 16:18:59 +00005624void PeerConnection::OnTransportControllerConnectionState(
5625 cricket::IceConnectionState state) {
5626 switch (state) {
5627 case cricket::kIceConnectionConnecting:
5628 // If the current state is Connected or Completed, then there were
5629 // writable channels but now there are not, so the next state must
5630 // be Disconnected.
5631 // kIceConnectionConnecting is currently used as the default,
5632 // un-connected state by the TransportController, so its only use is
5633 // detecting disconnections.
5634 if (ice_connection_state_ ==
5635 PeerConnectionInterface::kIceConnectionConnected ||
5636 ice_connection_state_ ==
5637 PeerConnectionInterface::kIceConnectionCompleted) {
5638 SetIceConnectionState(
5639 PeerConnectionInterface::kIceConnectionDisconnected);
5640 }
5641 break;
5642 case cricket::kIceConnectionFailed:
5643 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5644 break;
5645 case cricket::kIceConnectionConnected:
5646 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5647 "all transports are writable.";
5648 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5649 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5650 break;
5651 case cricket::kIceConnectionCompleted:
5652 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5653 "all transports are complete.";
5654 if (ice_connection_state_ !=
5655 PeerConnectionInterface::kIceConnectionConnected) {
5656 // If jumping directly from "checking" to "connected",
5657 // signal "connected" first.
5658 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5659 }
5660 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5661 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5662 ReportTransportStats();
5663 break;
5664 default:
5665 RTC_NOTREACHED();
5666 }
5667}
5668
Steve Anton75737c02017-11-06 10:37:17 -08005669void PeerConnection::OnTransportControllerCandidatesGathered(
5670 const std::string& transport_name,
5671 const cricket::Candidates& candidates) {
5672 RTC_DCHECK(signaling_thread()->IsCurrent());
5673 int sdp_mline_index;
5674 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005675 RTC_LOG(LS_ERROR)
5676 << "OnTransportControllerCandidatesGathered: content name "
5677 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005678 return;
5679 }
5680
5681 for (cricket::Candidates::const_iterator citer = candidates.begin();
5682 citer != candidates.end(); ++citer) {
5683 // Use transport_name as the candidate media id.
5684 std::unique_ptr<JsepIceCandidate> candidate(
5685 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5686 if (local_description()) {
5687 mutable_local_description()->AddCandidate(candidate.get());
5688 }
5689 OnIceCandidate(std::move(candidate));
5690 }
5691}
5692
5693void PeerConnection::OnTransportControllerCandidatesRemoved(
5694 const std::vector<cricket::Candidate>& candidates) {
5695 RTC_DCHECK(signaling_thread()->IsCurrent());
5696 // Sanity check.
5697 for (const cricket::Candidate& candidate : candidates) {
5698 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005699 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005700 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005701 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005702 return;
5703 }
5704 }
5705
5706 if (local_description()) {
5707 mutable_local_description()->RemoveCandidates(candidates);
5708 }
5709 OnIceCandidatesRemoved(candidates);
5710}
5711
5712void PeerConnection::OnTransportControllerDtlsHandshakeError(
5713 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005714 RTC_HISTOGRAM_ENUMERATION(
5715 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5716 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005717}
5718
Steve Antoned10bd92017-12-05 10:52:59 -08005719void PeerConnection::EnableSending() {
5720 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005721 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005722 if (channel && !channel->enabled()) {
5723 channel->Enable(true);
5724 }
Steve Anton75737c02017-11-06 10:37:17 -08005725 }
5726
Steve Anton4171afb2017-11-20 10:20:22 -08005727 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005728 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005729 }
Steve Anton75737c02017-11-06 10:37:17 -08005730}
5731
5732// Returns the media index for a local ice candidate given the content name.
5733bool PeerConnection::GetLocalCandidateMediaIndex(
5734 const std::string& content_name,
5735 int* sdp_mline_index) {
5736 if (!local_description() || !sdp_mline_index) {
5737 return false;
5738 }
5739
5740 bool content_found = false;
5741 const ContentInfos& contents = local_description()->description()->contents();
5742 for (size_t index = 0; index < contents.size(); ++index) {
5743 if (contents[index].name == content_name) {
5744 *sdp_mline_index = static_cast<int>(index);
5745 content_found = true;
5746 break;
5747 }
5748 }
5749 return content_found;
5750}
5751
5752bool PeerConnection::UseCandidatesInSessionDescription(
5753 const SessionDescriptionInterface* remote_desc) {
5754 if (!remote_desc) {
5755 return true;
5756 }
5757 bool ret = true;
5758
5759 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5760 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5761 for (size_t n = 0; n < candidates->count(); ++n) {
5762 const IceCandidateInterface* candidate = candidates->at(n);
5763 bool valid = false;
5764 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5765 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005766 RTC_LOG(LS_INFO)
5767 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005768 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005769 }
5770 continue;
5771 }
5772 ret = UseCandidate(candidate);
5773 if (!ret) {
5774 break;
5775 }
5776 }
5777 }
5778 return ret;
5779}
5780
5781bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5782 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5783 size_t remote_content_size =
5784 remote_description()->description()->contents().size();
5785 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005786 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005787 return false;
5788 }
5789
5790 cricket::ContentInfo content =
5791 remote_description()->description()->contents()[mediacontent_index];
5792 std::vector<cricket::Candidate> candidates;
5793 candidates.push_back(candidate->candidate());
5794 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005795 RTCError error =
5796 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005797 if (error.ok()) {
5798 // Candidates successfully submitted for checking.
5799 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5800 ice_connection_state_ ==
5801 PeerConnectionInterface::kIceConnectionDisconnected) {
5802 // If state is New, then the session has just gotten its first remote ICE
5803 // candidates, so go to Checking.
5804 // If state is Disconnected, the session is re-using old candidates or
5805 // receiving additional ones, so go to Checking.
5806 // If state is Connected, stay Connected.
5807 // TODO(bemasc): If state is Connected, and the new candidates are for a
5808 // newly added transport, then the state actually _should_ move to
5809 // checking. Add a way to distinguish that case.
5810 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5811 }
5812 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005813 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005814 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005815 }
5816 return true;
5817}
5818
5819void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005820 // Destroy video channel first since it may have a pointer to the
5821 // voice channel.
5822 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005823 if (!video_info || video_info->rejected) {
5824 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005825 }
5826
Steve Anton6fec8802017-12-04 10:37:29 -08005827 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5828 if (!audio_info || audio_info->rejected) {
5829 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005830 }
5831
5832 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5833 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005834 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005835 }
5836}
5837
Steve Antondcc3c022017-12-22 16:02:54 -08005838RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5839 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005840 const cricket::ContentGroup* bundle_group = nullptr;
5841 if (configuration_.bundle_policy ==
5842 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005843 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005844 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005845 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5846 "max-bundle configured but session description "
5847 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005848 }
5849 }
Steve Antondcc3c022017-12-22 16:02:54 -08005850 return std::move(bundle_group);
5851}
5852
5853RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005854 // Creating the media channels. Transports should already have been created
5855 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005856 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005857 if (voice && !voice->rejected &&
5858 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005859 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005860 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005861 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5862 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005863 }
5864 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5865 }
5866
Steve Antondcc3c022017-12-22 16:02:54 -08005867 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005868 if (video && !video->rejected &&
5869 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005870 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005871 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005872 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5873 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005874 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005875 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005876 }
5877
Steve Antondcc3c022017-12-22 16:02:54 -08005878 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005879 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005880 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005881 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005882 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5883 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005884 }
5885 }
5886
Steve Anton8a006912017-12-04 15:25:56 -08005887 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005888}
5889
Steve Anton4171afb2017-11-20 10:20:22 -08005890// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005891cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005892 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005893 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005894 MediaTransportInterface* media_transport = nullptr;
5895 if (configuration_.use_media_transport) {
5896 media_transport = GetMediaTransport(mid);
5897 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005898
Steve Anton75737c02017-11-06 10:37:17 -08005899 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005900 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005901 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5902 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005903 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005904 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005905 }
Steve Anton75737c02017-11-06 10:37:17 -08005906 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5907 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005908 voice_channel->SignalSentPacket.connect(this,
5909 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005910 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005911
Steve Antoneda6ccd2017-12-04 10:21:55 -08005912 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005913}
5914
Steve Anton4171afb2017-11-20 10:20:22 -08005915// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005916cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005917 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005918 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5919
5920 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005921 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005922 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005923 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5924 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005925 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005926 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005927 }
Steve Anton75737c02017-11-06 10:37:17 -08005928 video_channel->SignalDtlsSrtpSetupFailure.connect(
5929 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005930 video_channel->SignalSentPacket.connect(this,
5931 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005932 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005933
Steve Antoneda6ccd2017-12-04 10:21:55 -08005934 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005935}
5936
Zhi Huange830e682018-03-30 10:48:35 -07005937bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005938 switch (data_channel_type_) {
5939 case cricket::DCT_MEDIA_TRANSPORT:
5940 if (network_thread()->Invoke<bool>(
5941 RTC_FROM_HERE,
5942 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5943 this, mid))) {
5944 for (const auto& channel : sctp_data_channels_) {
5945 channel->OnTransportChannelCreated();
5946 }
5947 return true;
5948 }
Steve Anton75737c02017-11-06 10:37:17 -08005949 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005950 case cricket::DCT_SCTP:
5951 if (!sctp_factory_) {
5952 RTC_LOG(LS_ERROR)
5953 << "Trying to create SCTP transport, but didn't compile with "
5954 "SCTP support (HAVE_SCTP)";
5955 return false;
5956 }
5957 if (!network_thread()->Invoke<bool>(
5958 RTC_FROM_HERE,
5959 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5960 return false;
5961 }
5962 for (const auto& channel : sctp_data_channels_) {
5963 channel->OnTransportChannelCreated();
5964 }
5965 return true;
5966 case cricket::DCT_RTP:
5967 default:
5968 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5969 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5970 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5971 SrtpRequired(), GetCryptoOptions());
5972 if (!rtp_data_channel_) {
5973 return false;
5974 }
5975 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5976 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5977 rtp_data_channel_->SignalSentPacket.connect(
5978 this, &PeerConnection::OnSentPacket_w);
5979 rtp_data_channel_->SetRtpTransport(rtp_transport);
5980 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005981 }
5982
Steve Anton75737c02017-11-06 10:37:17 -08005983 return true;
5984}
5985
5986Call::Stats PeerConnection::GetCallStats() {
5987 if (!worker_thread()->IsCurrent()) {
5988 return worker_thread()->Invoke<Call::Stats>(
5989 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5990 }
5991 if (call_) {
5992 return call_->GetStats();
5993 } else {
5994 return Call::Stats();
5995 }
5996}
5997
Zhi Huange830e682018-03-30 10:48:35 -07005998bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005999 RTC_DCHECK(network_thread()->IsCurrent());
6000 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006001 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006002 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006003 RTC_DCHECK(dtls_transport);
6004 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006005 RTC_DCHECK(sctp_transport_);
6006 sctp_invoker_.reset(new rtc::AsyncInvoker());
6007 sctp_transport_->SignalReadyToSendData.connect(
6008 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6009 sctp_transport_->SignalDataReceived.connect(
6010 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006011 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6012 // another thread. Would be nice if there was a helper class similar to
6013 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6014 // code.
6015 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6016 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6017 sctp_transport_->SignalClosingProcedureComplete.connect(
6018 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006019 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006020 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006021 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006022}
6023
6024void PeerConnection::DestroySctpTransport_n() {
6025 RTC_DCHECK(network_thread()->IsCurrent());
6026 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006027 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006028 sctp_invoker_.reset(nullptr);
6029 sctp_ready_to_send_data_ = false;
6030}
6031
6032void PeerConnection::OnSctpTransportReadyToSendData_n() {
6033 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6034 RTC_DCHECK(network_thread()->IsCurrent());
6035 // Note: Cannot use rtc::Bind here because it will grab a reference to
6036 // PeerConnection and potentially cause PeerConnection to live longer than
6037 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6038 // be destroyed before PeerConnection is destroyed, and at that point all
6039 // pending tasks will be cleared.
6040 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6041 OnSctpTransportReadyToSendData_s(true);
6042 });
6043}
6044
6045void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6046 RTC_DCHECK(signaling_thread()->IsCurrent());
6047 sctp_ready_to_send_data_ = ready;
6048 SignalSctpReadyToSendData(ready);
6049}
6050
6051void PeerConnection::OnSctpTransportDataReceived_n(
6052 const cricket::ReceiveDataParams& params,
6053 const rtc::CopyOnWriteBuffer& payload) {
6054 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6055 RTC_DCHECK(network_thread()->IsCurrent());
6056 // Note: Cannot use rtc::Bind here because it will grab a reference to
6057 // PeerConnection and potentially cause PeerConnection to live longer than
6058 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6059 // be destroyed before PeerConnection is destroyed, and at that point all
6060 // pending tasks will be cleared.
6061 sctp_invoker_->AsyncInvoke<void>(
6062 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6063 OnSctpTransportDataReceived_s(params, payload);
6064 });
6065}
6066
6067void PeerConnection::OnSctpTransportDataReceived_s(
6068 const cricket::ReceiveDataParams& params,
6069 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006070 RTC_DCHECK_RUN_ON(signaling_thread());
6071 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006072 SignalSctpDataReceived(params, payload);
6073 }
6074}
6075
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006076void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006077 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6078 RTC_DCHECK(network_thread()->IsCurrent());
6079 sctp_invoker_->AsyncInvoke<void>(
6080 RTC_FROM_HERE, signaling_thread(),
6081 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006082 &SignalSctpClosingProcedureStartedRemotely, sid));
6083}
6084
6085void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6086 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6087 RTC_DCHECK(network_thread()->IsCurrent());
6088 sctp_invoker_->AsyncInvoke<void>(
6089 RTC_FROM_HERE, signaling_thread(),
6090 rtc::Bind(&sigslot::signal1<int>::operator(),
6091 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006092}
6093
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006094bool PeerConnection::SetupMediaTransportForDataChannels_n(
6095 const std::string& mid) {
6096 media_transport_ = transport_controller_->GetMediaTransport(mid);
6097 if (!media_transport_) {
6098 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6099 return false;
6100 }
6101
6102 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6103 media_transport_->SetDataSink(this);
6104 media_transport_data_mid_ = mid;
6105 transport_controller_->SignalMediaTransportStateChanged.connect(
6106 this, &PeerConnection::OnMediaTransportStateChanged_n);
6107 // Check the initial state right away, in case transport is already writable.
6108 OnMediaTransportStateChanged_n();
6109 return true;
6110}
6111
6112void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6113 if (!media_transport_) {
6114 return;
6115 }
6116 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6117 media_transport_data_mid_.reset();
6118 media_transport_->SetDataSink(nullptr);
6119 media_transport_invoker_ = nullptr;
6120 media_transport_ = nullptr;
6121}
6122
6123void PeerConnection::OnMediaTransportStateChanged_n() {
6124 if (!media_transport_data_mid_ ||
6125 transport_controller_->GetMediaTransportState(
6126 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6127 return;
6128 }
6129 media_transport_invoker_->AsyncInvoke<void>(
6130 RTC_FROM_HERE, signaling_thread(), [this] {
6131 RTC_DCHECK_RUN_ON(signaling_thread());
6132 media_transport_ready_to_send_data_ = true;
6133 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6134 });
6135}
6136
Steve Anton75737c02017-11-06 10:37:17 -08006137// Returns false if bundle is enabled and rtcp_mux is disabled.
6138bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6139 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6140 if (!bundle_enabled)
6141 return true;
6142
6143 const cricket::ContentGroup* bundle_group =
6144 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6145 RTC_DCHECK(bundle_group != NULL);
6146
6147 const cricket::ContentInfos& contents = desc->contents();
6148 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6149 citer != contents.end(); ++citer) {
6150 const cricket::ContentInfo* content = (&*citer);
6151 RTC_DCHECK(content != NULL);
6152 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006153 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006154 if (!HasRtcpMuxEnabled(content))
6155 return false;
6156 }
6157 }
6158 // RTCP-MUX is enabled in all the contents.
6159 return true;
6160}
6161
6162bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006163 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006164}
6165
Steve Anton06817cd2018-12-18 15:55:30 -08006166static RTCError ValidateMids(const cricket::SessionDescription& description) {
6167 std::set<std::string> mids;
6168 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006169 if (content.name.empty()) {
6170 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6171 "A media section is missing a MID attribute.");
6172 }
Steve Anton06817cd2018-12-18 15:55:30 -08006173 if (!mids.insert(content.name).second) {
6174 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6175 "Duplicate a=mid value '" + content.name + "'.");
6176 }
6177 }
6178 return RTCError::OK();
6179}
6180
Steve Anton8a006912017-12-04 15:25:56 -08006181RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006182 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006183 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006184 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006185 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006186 }
6187
6188 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006189 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006190 }
6191
Steve Anton3828c062017-12-06 10:34:51 -08006192 SdpType type = sdesc->GetType();
6193 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6194 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006195 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006196 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006197 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006198 }
6199
Steve Anton06817cd2018-12-18 15:55:30 -08006200 RTCError error = ValidateMids(*sdesc->description());
6201 if (!error.ok()) {
6202 return error;
6203 }
6204
Steve Anton75737c02017-11-06 10:37:17 -08006205 // Verify crypto settings.
6206 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006207 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6208 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006209 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006210 if (!crypto_error.ok()) {
6211 return crypto_error;
6212 }
Steve Anton75737c02017-11-06 10:37:17 -08006213 }
6214
6215 // Verify ice-ufrag and ice-pwd.
6216 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006217 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6218 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006219 }
6220
6221 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006222 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6223 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006224 }
6225
6226 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6227 // m-lines that do not rtcp-mux enabled.
6228
6229 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006230 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006231 // With an answer we want to compare the new answer session description with
6232 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006233 const cricket::SessionDescription* offer_desc =
6234 (source == cricket::CS_LOCAL) ? remote_description()->description()
6235 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006236 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6237 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6238 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006239 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6240 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006241 }
6242 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006243 // The re-offers should respect the order of m= sections in current
6244 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006245 // With a re-offer, either the current local or current remote descriptions
6246 // could be the most up to date, so we would like to check against both of
6247 // them if they exist. It could be the case that one of them has a 0 port
6248 // for a media section, but the other does not. This is important to check
6249 // against in the case that we are recycling an m= section.
6250 const cricket::SessionDescription* current_desc = nullptr;
6251 const cricket::SessionDescription* secondary_current_desc = nullptr;
6252 if (local_description()) {
6253 current_desc = local_description()->description();
6254 if (remote_description()) {
6255 secondary_current_desc = remote_description()->description();
6256 }
6257 } else if (remote_description()) {
6258 current_desc = remote_description()->description();
6259 }
Steve Anton75737c02017-11-06 10:37:17 -08006260 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006261 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6262 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006263 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6264 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006265 }
6266 }
6267
Steve Antonba42e992018-04-09 14:10:01 -07006268 if (IsUnifiedPlan()) {
6269 // Ensure that each audio and video media section has at most one
6270 // "StreamParams". This will return an error if receiving a session
6271 // description from a "Plan B" endpoint which adds multiple tracks of the
6272 // same type. With Unified Plan, there can only be at most one track per
6273 // media section.
6274 for (const ContentInfo& content : sdesc->description()->contents()) {
6275 const MediaContentDescription& desc = *content.description;
6276 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6277 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6278 desc.streams().size() > 1u) {
6279 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6280 "Media section has more than one track specified "
6281 "with a=ssrc lines which is not supported with "
6282 "Unified Plan.");
6283 }
6284 }
6285 }
6286
Steve Anton8a006912017-12-04 15:25:56 -08006287 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006288}
6289
Steve Anton3828c062017-12-06 10:34:51 -08006290bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006291 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006292 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006293 return (state == PeerConnectionInterface::kStable) ||
6294 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006295 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006296 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006297 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6298 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6299 }
6300}
6301
Steve Anton3828c062017-12-06 10:34:51 -08006302bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006303 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006304 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006305 return (state == PeerConnectionInterface::kStable) ||
6306 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006307 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006308 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006309 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6310 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6311 }
6312}
6313
Steve Antonf8470812017-12-04 10:46:21 -08006314const char* PeerConnection::SessionErrorToString(SessionError error) const {
6315 switch (error) {
6316 case SessionError::kNone:
6317 return "ERROR_NONE";
6318 case SessionError::kContent:
6319 return "ERROR_CONTENT";
6320 case SessionError::kTransport:
6321 return "ERROR_TRANSPORT";
6322 }
6323 RTC_NOTREACHED();
6324 return "";
6325}
6326
Steve Anton75737c02017-11-06 10:37:17 -08006327std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006328 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006329 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6330 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006331 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006332}
6333
Steve Anton8e20f172018-03-06 10:55:04 -08006334void PeerConnection::ReportSdpFormatReceived(
6335 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006336 int num_audio_mlines = 0;
6337 int num_video_mlines = 0;
6338 int num_audio_tracks = 0;
6339 int num_video_tracks = 0;
6340 for (const ContentInfo& content : remote_offer.description()->contents()) {
6341 cricket::MediaType media_type = content.media_description()->type();
6342 int num_tracks = std::max(
6343 1, static_cast<int>(content.media_description()->streams().size()));
6344 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6345 num_audio_mlines += 1;
6346 num_audio_tracks += num_tracks;
6347 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6348 num_video_mlines += 1;
6349 num_video_tracks += num_tracks;
6350 }
6351 }
6352 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6353 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6354 format = kSdpFormatReceivedComplexUnifiedPlan;
6355 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6356 format = kSdpFormatReceivedComplexPlanB;
6357 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6358 format = kSdpFormatReceivedSimple;
6359 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006360 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6361 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006362}
6363
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006364void PeerConnection::NoteUsageEvent(UsageEvent event) {
6365 RTC_DCHECK_RUN_ON(signaling_thread());
6366 usage_event_accumulator_ |= static_cast<int>(event);
6367}
6368
6369void PeerConnection::ReportUsagePattern() const {
6370 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006371 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6372 usage_event_accumulator_,
6373 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006374 const int bad_bits =
6375 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6376 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6377 const int good_bits =
6378 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6379 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6380 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6381 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6382 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006383 // If called after close(), we can't report, because observer may have
6384 // been deallocated, and therefore pointer is null. Write to log instead.
6385 if (observer_) {
6386 Observer()->OnInterestingUsage(usage_event_accumulator_);
6387 } else {
6388 RTC_LOG(LS_INFO) << "Interesting usage signature "
6389 << usage_event_accumulator_
6390 << " observed after observer shutdown";
6391 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006392 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006393}
6394
Steve Anton0ffaaa22018-02-23 10:31:30 -08006395void PeerConnection::ReportNegotiatedSdpSemantics(
6396 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006397 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006398 switch (answer.description()->msid_signaling()) {
6399 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006400 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006401 break;
6402 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006403 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006404 break;
6405 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006406 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006407 break;
6408 case cricket::kMsidSignalingMediaSection |
6409 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006410 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006411 break;
6412 default:
6413 RTC_NOTREACHED();
6414 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6416 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006417}
6418
Steve Anton75737c02017-11-06 10:37:17 -08006419// We need to check the local/remote description for the Transport instead of
6420// the session, because a new Transport added during renegotiation may have
6421// them unset while the session has them set from the previous negotiation.
6422// Not doing so may trigger the auto generation of transport description and
6423// mess up DTLS identity information, ICE credential, etc.
6424bool PeerConnection::ReadyToUseRemoteCandidate(
6425 const IceCandidateInterface* candidate,
6426 const SessionDescriptionInterface* remote_desc,
6427 bool* valid) {
6428 *valid = true;
6429
6430 const SessionDescriptionInterface* current_remote_desc =
6431 remote_desc ? remote_desc : remote_description();
6432
6433 if (!current_remote_desc) {
6434 return false;
6435 }
6436
6437 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6438 size_t remote_content_size =
6439 current_remote_desc->description()->contents().size();
6440 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006441 RTC_LOG(LS_ERROR)
6442 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6443 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006444
6445 *valid = false;
6446 return false;
6447 }
6448
6449 cricket::ContentInfo content =
6450 current_remote_desc->description()->contents()[mediacontent_index];
6451
6452 const std::string transport_name = GetTransportName(content.name);
6453 if (transport_name.empty()) {
6454 return false;
6455 }
Zhi Huange830e682018-03-30 10:48:35 -07006456 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006457}
6458
6459bool PeerConnection::SrtpRequired() const {
6460 return dtls_enabled_ ||
6461 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6462}
6463
6464void PeerConnection::OnTransportControllerGatheringState(
6465 cricket::IceGatheringState state) {
6466 RTC_DCHECK(signaling_thread()->IsCurrent());
6467 if (state == cricket::kIceGatheringGathering) {
6468 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6469 } else if (state == cricket::kIceGatheringComplete) {
6470 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6471 }
6472}
6473
6474void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006475 std::map<std::string, std::set<cricket::MediaType>>
6476 media_types_by_transport_name;
6477 for (auto transceiver : transceivers_) {
6478 if (transceiver->internal()->channel()) {
6479 const std::string& transport_name =
6480 transceiver->internal()->channel()->transport_name();
6481 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006482 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006483 }
Steve Anton75737c02017-11-06 10:37:17 -08006484 }
6485 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006486 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6487 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006488 }
Zhi Huange830e682018-03-30 10:48:35 -07006489
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006490 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006491 if (transport_name) {
6492 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006493 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006494 }
Zhi Huange830e682018-03-30 10:48:35 -07006495
Steve Antonc7b964c2018-02-01 14:39:45 -08006496 for (const auto& entry : media_types_by_transport_name) {
6497 const std::string& transport_name = entry.first;
6498 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006499 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006500 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006501 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006502 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006503 }
6504 }
6505}
6506// Walk through the ConnectionInfos to gather best connection usage
6507// for IPv4 and IPv6.
6508void PeerConnection::ReportBestConnectionState(
6509 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006510 for (const cricket::TransportChannelStats& channel_stats :
6511 stats.channel_stats) {
6512 for (const cricket::ConnectionInfo& connection_info :
6513 channel_stats.connection_infos) {
6514 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006515 continue;
6516 }
6517
Steve Antonc7b964c2018-02-01 14:39:45 -08006518 const cricket::Candidate& local = connection_info.local_candidate;
6519 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006520
6521 // Increment the counter for IceCandidatePairType.
6522 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6523 (local.type() == RELAY_PORT_TYPE &&
6524 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006525 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6526 GetIceCandidatePairCounter(local, remote),
6527 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006528 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006529 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6530 GetIceCandidatePairCounter(local, remote),
6531 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006532 } else {
6533 RTC_CHECK(0);
6534 }
Steve Anton75737c02017-11-06 10:37:17 -08006535
6536 // Increment the counter for IP type.
6537 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006538 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6539 kBestConnections_IPv4,
6540 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006541 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006542 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6543 kBestConnections_IPv6,
6544 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006545 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006546 RTC_CHECK(!local.address().hostname().empty() &&
6547 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006548 }
6549
6550 return;
6551 }
6552 }
6553}
6554
6555void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006556 const cricket::TransportStats& stats,
6557 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006558 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6559 return;
6560 }
6561
6562 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6563 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6564 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6565 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6566 return;
6567 }
6568
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006569 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6570 for (cricket::MediaType media_type : media_types) {
6571 switch (media_type) {
6572 case cricket::MEDIA_TYPE_AUDIO:
6573 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6574 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6575 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6576 break;
6577 case cricket::MEDIA_TYPE_VIDEO:
6578 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6579 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6580 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6581 break;
6582 case cricket::MEDIA_TYPE_DATA:
6583 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6584 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6585 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6586 break;
6587 default:
6588 RTC_NOTREACHED();
6589 continue;
6590 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006591 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006592 }
6593
6594 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6595 for (cricket::MediaType media_type : media_types) {
6596 switch (media_type) {
6597 case cricket::MEDIA_TYPE_AUDIO:
6598 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6599 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6600 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6601 break;
6602 case cricket::MEDIA_TYPE_VIDEO:
6603 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6604 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6605 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6606 break;
6607 case cricket::MEDIA_TYPE_DATA:
6608 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6609 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6610 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6611 break;
6612 default:
6613 RTC_NOTREACHED();
6614 continue;
6615 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006616 }
Steve Anton75737c02017-11-06 10:37:17 -08006617 }
6618}
6619
6620void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6621 RTC_DCHECK(worker_thread()->IsCurrent());
6622 RTC_DCHECK(call_);
6623 call_->OnSentPacket(sent_packet);
6624}
6625
6626const std::string PeerConnection::GetTransportName(
6627 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006628 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006629 if (channel) {
6630 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006631 }
Steve Anton6fec8802017-12-04 10:37:29 -08006632 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006633 RTC_DCHECK(sctp_mid_);
6634 if (content_name == *sctp_mid_) {
6635 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006636 }
6637 }
6638 // Return an empty string if failed to retrieve the transport name.
6639 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006640}
6641
Steve Anton6fec8802017-12-04 10:37:29 -08006642void PeerConnection::DestroyTransceiverChannel(
6643 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6644 transceiver) {
6645 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006646
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006647 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006648 if (channel) {
6649 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006650 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006651 }
6652}
6653
6654void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006655 if (rtp_data_channel_) {
6656 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006657 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006658 rtp_data_channel_ = nullptr;
6659 }
6660
6661 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6662 // grab a reference to this PeerConnection. If this is called from the
6663 // PeerConnection destructor, the RefCountedObject vtable will have already
6664 // been destroyed (since it is a subclass of PeerConnection) and using
6665 // rtc::Bind will cause "Pure virtual function called" error to appear.
6666
6667 if (sctp_transport_) {
6668 OnDataChannelDestroyed();
6669 network_thread()->Invoke<void>(RTC_FROM_HERE,
6670 [this] { DestroySctpTransport_n(); });
6671 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006672
6673 if (media_transport_) {
6674 OnDataChannelDestroyed();
6675 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6676 RTC_DCHECK_RUN_ON(network_thread());
6677 TeardownMediaTransportForDataChannels_n();
6678 });
6679 }
Steve Anton6fec8802017-12-04 10:37:29 -08006680}
6681
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006682void PeerConnection::DestroyChannelInterface(
6683 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006684 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006685 switch (channel->media_type()) {
6686 case cricket::MEDIA_TYPE_AUDIO:
6687 channel_manager()->DestroyVoiceChannel(
6688 static_cast<cricket::VoiceChannel*>(channel));
6689 break;
6690 case cricket::MEDIA_TYPE_VIDEO:
6691 channel_manager()->DestroyVideoChannel(
6692 static_cast<cricket::VideoChannel*>(channel));
6693 break;
6694 case cricket::MEDIA_TYPE_DATA:
6695 channel_manager()->DestroyRtpDataChannel(
6696 static_cast<cricket::RtpDataChannel*>(channel));
6697 break;
6698 default:
6699 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6700 break;
6701 }
Zhi Huange830e682018-03-30 10:48:35 -07006702}
Steve Anton6fec8802017-12-04 10:37:29 -08006703
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006704bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006705 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006706 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006707 cricket::DtlsTransportInternal* dtls_transport,
6708 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006709 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006710 auto base_channel = GetChannel(mid);
6711 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006712 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006713 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006714 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006715 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006716 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006717
6718 call_->MediaTransportChange(media_transport);
6719
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006720 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006721}
6722
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006723PeerConnectionObserver* PeerConnection::Observer() const {
6724 // In earlier production code, the pointer was not cleared on close,
6725 // which might have led to undefined behavior if the observer was not
6726 // deallocated, or strange crashes if it was.
6727 // We use CHECK in order to catch such behavior if it exists.
6728 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6729 RTC_CHECK(observer_);
6730 return observer_;
6731}
6732
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006733CryptoOptions PeerConnection::GetCryptoOptions() {
6734 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6735 // after it has been removed.
6736 return configuration_.crypto_options.has_value()
6737 ? *configuration_.crypto_options
6738 : factory_->options().crypto_options;
6739}
6740
Harald Alvestrand89061872018-01-02 14:08:34 +01006741void PeerConnection::ClearStatsCache() {
6742 if (stats_collector_) {
6743 stats_collector_->ClearCachedStatsReport();
6744 }
6745}
6746
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006747void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006748 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6749 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006750}
6751
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006752} // namespace webrtc