blob: 2d68c81761b97e80b7f6f7e3c50a704edeb1ef56 [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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.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"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "api/jsep_ice_candidate.h"
23#include "api/jsep_session_description.h"
24#include "api/media_stream_proxy.h"
25#include "api/media_stream_track_proxy.h"
26#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080028#include "logging/rtc_event_log/ice_logger.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"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "media/sctp/sctp_transport.h"
32#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080033#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "pc/channel_manager.h"
35#include "pc/dtmf_sender.h"
36#include "pc/media_stream.h"
37#include "pc/media_stream_observer.h"
38#include "pc/remote_audio_source.h"
39#include "pc/rtp_media_utils.h"
40#include "pc/rtp_receiver.h"
41#include "pc/rtp_sender.h"
42#include "pc/sctp_utils.h"
43#include "pc/sdp_utils.h"
44#include "pc/stream_collection.h"
Amit Hilbuchae3df542019-01-07 12:13:08 -080045#include "pc/unique_id_generator.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "pc/video_capturer_track_source.h"
47#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#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"
Steve Anton10542f22019-01-11 09:11:00 -080052#include "rtc_base/string_encode.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;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100709 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800710 int ice_connection_receiving_timeout;
711 int ice_backup_candidate_pair_ping_interval;
712 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800713 bool prioritize_most_likely_ice_candidate_pairs;
714 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800715 bool prune_turn_ports;
716 bool presume_writable_when_fully_relayed;
717 bool enable_ice_renomination;
718 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200719 absl::optional<int> ice_check_interval_strong_connectivity;
720 absl::optional<int> ice_check_interval_weak_connectivity;
721 absl::optional<int> ice_check_min_interval;
722 absl::optional<int> ice_unwritable_timeout;
723 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800724 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200725 absl::optional<int> stun_candidate_keepalive_interval;
726 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200727 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800728 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200729 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700730 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700731 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700732 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700733 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100734 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800735 };
736 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
737 "Did you add something to RTCConfiguration and forget to "
738 "update operator==?");
739 return type == o.type && servers == o.servers &&
740 bundle_policy == o.bundle_policy &&
741 rtcp_mux_policy == o.rtcp_mux_policy &&
742 tcp_candidate_policy == o.tcp_candidate_policy &&
743 candidate_network_policy == o.candidate_network_policy &&
744 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
745 audio_jitter_buffer_fast_accelerate ==
746 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100747 audio_jitter_buffer_min_delay_ms ==
748 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100749 audio_jitter_buffer_enable_rtx_handling ==
750 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800751 ice_connection_receiving_timeout ==
752 o.ice_connection_receiving_timeout &&
753 ice_backup_candidate_pair_ping_interval ==
754 o.ice_backup_candidate_pair_ping_interval &&
755 continual_gathering_policy == o.continual_gathering_policy &&
756 certificates == o.certificates &&
757 prioritize_most_likely_ice_candidate_pairs ==
758 o.prioritize_most_likely_ice_candidate_pairs &&
759 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800760 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700761 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100762 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800763 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800764 screencast_min_bitrate == o.screencast_min_bitrate &&
765 combined_audio_video_bwe == o.combined_audio_video_bwe &&
766 enable_dtls_srtp == o.enable_dtls_srtp &&
767 ice_candidate_pool_size == o.ice_candidate_pool_size &&
768 prune_turn_ports == o.prune_turn_ports &&
769 presume_writable_when_fully_relayed ==
770 o.presume_writable_when_fully_relayed &&
771 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800772 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800773 ice_check_interval_strong_connectivity ==
774 o.ice_check_interval_strong_connectivity &&
775 ice_check_interval_weak_connectivity ==
776 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700777 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700778 ice_unwritable_timeout == o.ice_unwritable_timeout &&
779 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800780 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800781 stun_candidate_keepalive_interval ==
782 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200783 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800784 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800785 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700786 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700787 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700788 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700789 use_media_transport_for_data_channels ==
790 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100791 crypto_options == o.crypto_options &&
792 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800793}
794
795bool PeerConnectionInterface::RTCConfiguration::operator!=(
796 const PeerConnectionInterface::RTCConfiguration& o) const {
797 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800798}
799
zhihuang8f65cdf2016-05-06 18:40:30 -0700800// Generate a RTCP CNAME when a PeerConnection is created.
801std::string GenerateRtcpCname() {
802 std::string cname;
803 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100804 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800805 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700806 }
807 return cname;
808}
809
zhihuang1c378ed2017-08-17 14:10:50 -0700810bool ValidateOfferAnswerOptions(
811 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
812 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
813 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700814}
815
zhihuang1c378ed2017-08-17 14:10:50 -0700816// From |rtc_options|, fill parts of |session_options| shared by all generated
817// m= sections (in other words, nothing that involves a map/array).
818void ExtractSharedMediaSessionOptions(
819 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
820 cricket::MediaSessionOptions* session_options) {
821 session_options->vad_enabled = rtc_options.voice_activity_detection;
822 session_options->bundle_enabled = rtc_options.use_rtp_mux;
823}
zhihuanga77e6bb2017-08-14 18:17:48 -0700824
zhihuang38ede132017-06-15 12:52:32 -0700825PeerConnection::PeerConnection(PeerConnectionFactory* factory,
826 std::unique_ptr<RtcEventLog> event_log,
827 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700829 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700830 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700831 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700832 remote_streams_(StreamCollection::Create()),
833 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834
835PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100836 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800837 RTC_DCHECK_RUN_ON(signaling_thread());
838
Steve Anton8af21862017-12-15 11:20:13 -0800839 // Need to stop transceivers before destroying the stats collector because
840 // AudioRtpSender has a reference to the StatsCollector it will update when
841 // stopping.
842 for (auto transceiver : transceivers_) {
843 transceiver->Stop();
844 }
Steve Anton4171afb2017-11-20 10:20:22 -0800845
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700846 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800847 if (stats_collector_) {
848 stats_collector_->WaitForPendingRequest();
849 stats_collector_ = nullptr;
850 }
Steve Anton75737c02017-11-06 10:37:17 -0800851
Steve Anton8af21862017-12-15 11:20:13 -0800852 // Don't destroy BaseChannels until after stats has been cleaned up so that
853 // the last stats request can still read from the channels.
854 DestroyAllChannels();
855
Mirko Bonadei675513b2017-11-09 11:09:25 +0100856 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800857
858 webrtc_session_desc_factory_.reset();
859 sctp_invoker_.reset();
860 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800861 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800862 transport_controller_.reset();
863
deadbeef91dd5672016-05-18 16:55:30 -0700864 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700865 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700866 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700867 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700868 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700869 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800870 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700871 event_log_.reset();
872 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873}
874
Steve Anton8af21862017-12-15 11:20:13 -0800875void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800876 // Destroy video channels first since they may have a pointer to a voice
877 // channel.
878 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800879 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800880 DestroyTransceiverChannel(transceiver);
881 }
882 }
883 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800884 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800885 DestroyTransceiverChannel(transceiver);
886 }
887 }
888 DestroyDataChannel();
889}
890
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000892 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700893 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100894 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700895
896 RTCError config_error = ValidateConfiguration(configuration);
897 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100898 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700899 return false;
900 }
901
Benjamin Wrightcab58882018-05-02 15:12:47 -0700902 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100903 RTC_LOG(LS_ERROR)
904 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100905 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800906 return false;
907 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200908
Benjamin Wrightcab58882018-05-02 15:12:47 -0700909 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800910 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100911 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100912 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800913 return false;
914 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700915
Benjamin Wrightcab58882018-05-02 15:12:47 -0700916 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700917 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700918 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700919 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800920
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200921 cricket::ServerAddresses stun_servers;
922 std::vector<cricket::RelayServerConfig> turn_servers;
923
924 RTCErrorType parse_error =
925 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
926 if (parse_error != RTCErrorType::NONE) {
927 return false;
928 }
929
deadbeef91dd5672016-05-18 16:55:30 -0700930 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700931 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700932 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200933 RTC_FROM_HERE,
934 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
935 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936 return false;
937 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200938 // If initialization was successful, note if STUN or TURN servers
939 // were supplied.
940 if (!stun_servers.empty()) {
941 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
942 }
943 if (!turn_servers.empty()) {
944 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
945 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700947 // Send information about IPv4/IPv6 status.
948 PeerConnectionAddressFamilyCounter address_family;
949 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
950 address_family = kPeerConnection_IPv6;
951 } else {
952 address_family = kPeerConnection_IPv4;
953 }
954 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
955 kPeerConnectionAddressFamilyCounter_Max);
956
Zhi Huange830e682018-03-30 10:48:35 -0700957 const PeerConnectionFactoryInterface::Options& options = factory_->options();
958
Steve Anton75737c02017-11-06 10:37:17 -0800959 // RFC 3264: The numeric value of the session id and version in the
960 // o line MUST be representable with a "64 bit signed integer".
961 // Due to this constraint session id |session_id_| is max limited to
962 // LLONG_MAX.
963 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700964 JsepTransportController::Config config;
965 config.redetermine_role_on_ice_restart =
966 configuration.redetermine_role_on_ice_restart;
967 config.ssl_max_version = factory_->options().ssl_max_version;
968 config.disable_encryption = options.disable_encryption;
969 config.bundle_policy = configuration.bundle_policy;
970 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700971 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
972 // stub.
973 config.crypto_options = configuration.crypto_options.has_value()
974 ? *configuration.crypto_options
975 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700976 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700977 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700978#if defined(ENABLE_EXTERNAL_AUTH)
979 config.enable_external_auth = true;
980#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700981 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700982
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700983 if (configuration.use_media_transport ||
984 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700985 if (!factory_->media_transport_factory()) {
986 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700987 << "PeerConnecton is initialized with use_media_transport = true or "
988 << "use_media_transport_for_data_channels = true "
989 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700990 return false;
991 }
992
993 config.media_transport_factory = factory_->media_transport_factory();
994 }
995
Zhi Huange830e682018-03-30 10:48:35 -0700996 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700997 signaling_thread(), network_thread(), port_allocator_.get(),
998 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700999 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001000 this, &PeerConnection::OnTransportControllerConnectionState);
1001 transport_controller_->SignalStandardizedIceConnectionState.connect(
1002 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001003 transport_controller_->SignalConnectionState.connect(
1004 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001005 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001006 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001007 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001008 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001009 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001010 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1011 transport_controller_->SignalDtlsHandshakeError.connect(
1012 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1013
1014 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001015
deadbeefab9b2d12015-10-14 11:33:11 -07001016 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001017 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018
Steve Antonba818672017-11-06 10:21:57 -08001019 configuration_ = configuration;
1020
Steve Anton75737c02017-11-06 10:37:17 -08001021 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1022 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1023 if (!configuration.certificates.empty()) {
1024 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1025 // just picking the first one. The decision should be made based on the DTLS
1026 // handshake. The DTLS negotiations need to know about all certificates.
1027 certificate = configuration.certificates[0];
1028 }
1029
Steve Antond25da372017-11-06 14:50:29 -08001030 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001031
1032 if (options.disable_encryption) {
1033 dtls_enabled_ = false;
1034 } else {
1035 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001036 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001037 // |configuration| can override the default |dtls_enabled_| value.
1038 if (configuration.enable_dtls_srtp) {
1039 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1040 }
1041 }
1042
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001043 if (configuration.use_media_transport_for_data_channels) {
1044 if (configuration.enable_rtp_data_channel) {
1045 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1046 "use_media_transport_for_data_channels are "
1047 "incompatible and cannot both be set to true";
1048 return false;
1049 }
1050 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1051 } else if (configuration.enable_rtp_data_channel) {
1052 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1053 // set. It takes precendence over the disable_sctp_data_channels
1054 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001055 data_channel_type_ = cricket::DCT_RTP;
1056 } else {
1057 // DTLS has to be enabled to use SCTP.
1058 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1059 data_channel_type_ = cricket::DCT_SCTP;
1060 }
1061 }
1062
1063 video_options_.screencast_min_bitrate_kbps =
1064 configuration.screencast_min_bitrate;
1065 audio_options_.combined_audio_video_bwe =
1066 configuration.combined_audio_video_bwe;
1067
1068 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001069 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001070
1071 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001072 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001073
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001074 audio_options_.audio_jitter_buffer_min_delay_ms =
1075 configuration.audio_jitter_buffer_min_delay_ms;
1076
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001077 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1078 configuration.audio_jitter_buffer_enable_rtx_handling;
1079
Steve Anton75737c02017-11-06 10:37:17 -08001080 // Whether the certificate generator/certificate is null or not determines
1081 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1082 // the right instructions by clearing the variables if needed.
1083 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001084 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001085 certificate = nullptr;
1086 } else if (certificate) {
1087 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001088 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001089 }
1090
1091 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1092 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001093 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001094 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1095 this, &PeerConnection::OnCertificateReady);
1096
1097 if (options.disable_encryption) {
1098 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1099 }
1100
1101 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001102 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001103 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104
Steve Anton4171afb2017-11-20 10:20:22 -08001105 // Add default audio/video transceivers for Plan B SDP.
1106 if (!IsUnifiedPlan()) {
1107 transceivers_.push_back(
1108 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1109 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1110 transceivers_.push_back(
1111 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1112 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1113 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001114 int delay_ms =
1115 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001116 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1117 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001118 return true;
1119}
1120
Steve Anton038834f2017-07-14 15:59:59 -07001121RTCError PeerConnection::ValidateConfiguration(
1122 const RTCConfiguration& config) const {
1123 if (config.ice_regather_interval_range &&
1124 config.continual_gathering_policy == GATHER_ONCE) {
1125 return RTCError(RTCErrorType::INVALID_PARAMETER,
1126 "ice_regather_interval_range specified but continual "
1127 "gathering policy is GATHER_ONCE");
1128 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001129 auto result =
1130 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1131 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001132}
1133
Yves Gerey665174f2018-06-19 15:03:05 +02001134rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001135 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1136 "Plan SdpSemantics. Please use GetSenders "
1137 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001138 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001139}
1140
Yves Gerey665174f2018-06-19 15:03:05 +02001141rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001142 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1143 "Plan SdpSemantics. Please use GetReceivers "
1144 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001145 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146}
1147
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001148bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001149 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1150 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001151 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 if (IsClosed()) {
1153 return false;
1154 }
deadbeefab9b2d12015-10-14 11:33:11 -07001155 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156 return false;
1157 }
deadbeefab9b2d12015-10-14 11:33:11 -07001158
1159 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001160 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1161 observer->SignalAudioTrackAdded.connect(this,
1162 &PeerConnection::OnAudioTrackAdded);
1163 observer->SignalAudioTrackRemoved.connect(
1164 this, &PeerConnection::OnAudioTrackRemoved);
1165 observer->SignalVideoTrackAdded.connect(this,
1166 &PeerConnection::OnVideoTrackAdded);
1167 observer->SignalVideoTrackRemoved.connect(
1168 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001169 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001170
deadbeefab9b2d12015-10-14 11:33:11 -07001171 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001172 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001173 }
1174 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001175 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001176 }
1177
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001178 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001179 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001180 return true;
1181}
1182
1183void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001184 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1185 "Plan SdpSemantics. Please use RemoveTrack "
1186 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001187 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001188 if (!IsClosed()) {
1189 for (const auto& track : local_stream->GetAudioTracks()) {
1190 RemoveAudioTrack(track.get(), local_stream);
1191 }
1192 for (const auto& track : local_stream->GetVideoTracks()) {
1193 RemoveVideoTrack(track.get(), local_stream);
1194 }
deadbeefab9b2d12015-10-14 11:33:11 -07001195 }
deadbeefab9b2d12015-10-14 11:33:11 -07001196 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001197 stream_observers_.erase(
1198 std::remove_if(
1199 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001200 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001201 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001202 }),
1203 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001204
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001205 if (IsClosed()) {
1206 return;
1207 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001208 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001209}
1210
Steve Anton2d6c76a2018-01-05 17:10:52 -08001211RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001212 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001213 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001214 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001215 if (!track) {
1216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1217 }
1218 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1219 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1221 "Track has invalid kind: " + track->kind());
1222 }
Steve Antonf9381f02017-12-14 10:23:57 -08001223 if (IsClosed()) {
1224 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1225 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001226 }
Steve Anton4171afb2017-11-20 10:20:22 -08001227 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001228 LOG_AND_RETURN_ERROR(
1229 RTCErrorType::INVALID_PARAMETER,
1230 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001231 }
Steve Antonf9381f02017-12-14 10:23:57 -08001232 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001233 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1234 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001235 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001236 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001237 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001238 }
1239 return sender_or_error;
1240}
deadbeefe1f9d832016-01-14 15:35:42 -08001241
Steve Antonf9381f02017-12-14 10:23:57 -08001242RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1243PeerConnection::AddTrackPlanB(
1244 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001245 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001246 if (stream_ids.size() > 1u) {
1247 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1248 "AddTrack with more than one stream is not "
1249 "supported with Plan B semantics.");
1250 }
1251 std::vector<std::string> adjusted_stream_ids = stream_ids;
1252 if (adjusted_stream_ids.empty()) {
1253 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1254 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001255 cricket::MediaType media_type =
1256 (track->kind() == MediaStreamTrackInterface::kAudioKind
1257 ? cricket::MEDIA_TYPE_AUDIO
1258 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001259 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001260 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001261 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001262 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001263 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001264 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001265 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001266 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001267 if (sender_info) {
1268 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001269 }
Steve Antonf9381f02017-12-14 10:23:57 -08001270 } else {
1271 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001272 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001273 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001274 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001275 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001276 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001277 if (sender_info) {
1278 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001279 }
deadbeefe1f9d832016-01-14 15:35:42 -08001280 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001281 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001282}
deadbeefe1f9d832016-01-14 15:35:42 -08001283
Steve Antonf9381f02017-12-14 10:23:57 -08001284RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1285PeerConnection::AddTrackUnifiedPlan(
1286 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001287 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001288 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1289 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001290 RTC_LOG(LS_INFO) << "Reusing an existing "
1291 << cricket::MediaTypeToString(transceiver->media_type())
1292 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001293 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001294 transceiver->internal()->set_direction(
1295 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001296 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001297 transceiver->internal()->set_direction(
1298 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001299 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001300 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001301 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001302 } else {
1303 cricket::MediaType media_type =
1304 (track->kind() == MediaStreamTrackInterface::kAudioKind
1305 ? cricket::MEDIA_TYPE_AUDIO
1306 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001307 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1308 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001309 std::string sender_id = track->id();
1310 // Avoid creating a sender with an existing ID by generating a random ID.
1311 // This can happen if this is the second time AddTrack has created a sender
1312 // for this track.
1313 if (FindSenderById(sender_id)) {
1314 sender_id = rtc::CreateRandomUuid();
1315 }
Florent Castelli892acf02018-10-01 22:47:20 +02001316 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001317 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1318 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001319 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001320 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001321 }
Steve Antonf9381f02017-12-14 10:23:57 -08001322 return transceiver->sender();
1323}
1324
1325rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1326PeerConnection::FindFirstTransceiverForAddedTrack(
1327 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1328 RTC_DCHECK(track);
1329 for (auto transceiver : transceivers_) {
1330 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001331 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001332 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001333 !transceiver->internal()->has_ever_been_used_to_send() &&
1334 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001335 return transceiver;
1336 }
1337 }
1338 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001339}
1340
1341bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1342 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001343 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001344}
1345
Steve Anton24db5732018-07-23 10:27:33 -07001346RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001347 rtc::scoped_refptr<RtpSenderInterface> sender) {
1348 if (!sender) {
1349 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1350 }
deadbeefe1f9d832016-01-14 15:35:42 -08001351 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001352 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1353 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001354 }
Steve Antonf9381f02017-12-14 10:23:57 -08001355 if (IsUnifiedPlan()) {
1356 auto transceiver = FindTransceiverBySender(sender);
1357 if (!transceiver || !sender->track()) {
1358 return RTCError::OK();
1359 }
1360 sender->SetTrack(nullptr);
1361 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001362 transceiver->internal()->set_direction(
1363 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001364 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001365 transceiver->internal()->set_direction(
1366 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001367 }
Steve Anton4171afb2017-11-20 10:20:22 -08001368 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001369 bool removed;
1370 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1371 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1372 } else {
1373 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1374 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1375 }
1376 if (!removed) {
1377 LOG_AND_RETURN_ERROR(
1378 RTCErrorType::INVALID_PARAMETER,
1379 "Couldn't find sender " + sender->id() + " to remove.");
1380 }
Steve Anton4171afb2017-11-20 10:20:22 -08001381 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001382 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001383 return RTCError::OK();
1384}
1385
1386rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1387PeerConnection::FindTransceiverBySender(
1388 rtc::scoped_refptr<RtpSenderInterface> sender) {
1389 for (auto transceiver : transceivers_) {
1390 if (transceiver->sender() == sender) {
1391 return transceiver;
1392 }
1393 }
1394 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001395}
1396
Steve Anton9158ef62017-11-27 13:01:52 -08001397RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1398PeerConnection::AddTransceiver(
1399 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1400 return AddTransceiver(track, RtpTransceiverInit());
1401}
1402
1403RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1404PeerConnection::AddTransceiver(
1405 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1406 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001407 RTC_CHECK(IsUnifiedPlan())
1408 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001409 if (!track) {
1410 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1411 }
1412 cricket::MediaType media_type;
1413 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1414 media_type = cricket::MEDIA_TYPE_AUDIO;
1415 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1416 media_type = cricket::MEDIA_TYPE_VIDEO;
1417 } else {
1418 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1419 "Track kind is not audio or video");
1420 }
1421 return AddTransceiver(media_type, track, init);
1422}
1423
1424RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1425PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1426 return AddTransceiver(media_type, RtpTransceiverInit());
1427}
1428
1429RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1430PeerConnection::AddTransceiver(cricket::MediaType media_type,
1431 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001432 RTC_CHECK(IsUnifiedPlan())
1433 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001434 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1435 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1436 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1437 "media type is not audio or video");
1438 }
1439 return AddTransceiver(media_type, nullptr, init);
1440}
1441
1442RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1443PeerConnection::AddTransceiver(
1444 cricket::MediaType media_type,
1445 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001446 const RtpTransceiverInit& init,
1447 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001448 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1449 media_type == cricket::MEDIA_TYPE_VIDEO));
1450 if (track) {
1451 RTC_DCHECK_EQ(media_type,
1452 (track->kind() == MediaStreamTrackInterface::kAudioKind
1453 ? cricket::MEDIA_TYPE_AUDIO
1454 : cricket::MEDIA_TYPE_VIDEO));
1455 }
1456
1457 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001458 if (init.send_encodings.size() > 1) {
1459 LOG_AND_RETURN_ERROR(
1460 RTCErrorType::UNSUPPORTED_PARAMETER,
1461 "Attempted to create an encoder with more than 1 encoding parameter.");
1462 }
1463
1464 for (const auto& encoding : init.send_encodings) {
1465 if (encoding.ssrc.has_value()) {
1466 LOG_AND_RETURN_ERROR(
1467 RTCErrorType::UNSUPPORTED_PARAMETER,
1468 "Attempted to set an unimplemented parameter of RtpParameters.");
1469 }
1470 }
1471
1472 RtpParameters parameters;
1473 parameters.encodings = init.send_encodings;
1474 if (UnimplementedRtpParameterHasValue(parameters)) {
1475 LOG_AND_RETURN_ERROR(
1476 RTCErrorType::UNSUPPORTED_PARAMETER,
1477 "Attempted to set an unimplemented parameter of RtpParameters.");
1478 }
Steve Anton9158ef62017-11-27 13:01:52 -08001479
Steve Anton3d954a62018-04-02 11:27:23 -07001480 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1481 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001482 // Set the sender ID equal to the track ID if the track is specified unless
1483 // that sender ID is already in use.
1484 std::string sender_id =
1485 (track && !FindSenderById(track->id()) ? track->id()
1486 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001487 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1488 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001489 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1490 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1491 transceiver->internal()->set_direction(init.direction);
1492
Steve Anton22da89f2018-01-25 13:58:07 -08001493 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001494 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001495 }
Steve Antonf9381f02017-12-14 10:23:57 -08001496
1497 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1498}
1499
Steve Anton02ee47c2018-01-10 16:26:06 -08001500rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1501PeerConnection::CreateSender(
1502 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001503 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001504 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001505 const std::vector<std::string>& stream_ids,
1506 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001507 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001508 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1509 RTC_DCHECK(!track ||
1510 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1511 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1512 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001513 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001514 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001515 } else {
1516 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1517 RTC_DCHECK(!track ||
1518 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1519 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001520 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001521 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001522 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001523 bool set_track_succeeded = sender->SetTrack(track);
1524 RTC_DCHECK(set_track_succeeded);
1525 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001526 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001527 return sender;
1528}
1529
1530rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1531PeerConnection::CreateReceiver(cricket::MediaType media_type,
1532 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001533 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1534 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001535 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001536 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001537 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1538 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001539 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001540 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001541 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001542 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001543 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1544 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001545 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001546 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001547 return receiver;
1548}
1549
1550rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1551PeerConnection::CreateAndAddTransceiver(
1552 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1553 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1554 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001555 // Ensure that the new sender does not have an ID that is already in use by
1556 // another sender.
1557 // Allow receiver IDs to conflict since those come from remote SDP (which
1558 // could be invalid, but should not cause a crash).
1559 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001560 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1561 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001562 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001563 transceiver->internal()->SignalNegotiationNeeded.connect(
1564 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001565 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001566}
1567
Steve Anton52d86772018-02-20 15:48:12 -08001568void PeerConnection::OnNegotiationNeeded() {
1569 RTC_DCHECK_RUN_ON(signaling_thread());
1570 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001571 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001572}
1573
deadbeeffac06552015-11-25 11:26:01 -08001574rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001575 const std::string& kind,
1576 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001577 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1578 "Plan SdpSemantics. Please use AddTransceiver "
1579 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001580 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001581 if (IsClosed()) {
1582 return nullptr;
1583 }
Steve Anton4171afb2017-11-20 10:20:22 -08001584
Seth Hampson5b4f0752018-04-02 16:31:36 -07001585 // Internally we need to have one stream with Plan B semantics, so we
1586 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001587 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001588 if (stream_id.empty()) {
1589 stream_ids.push_back(rtc::CreateRandomUuid());
1590 RTC_LOG(LS_INFO)
1591 << "No stream_id specified for sender. Generated stream ID: "
1592 << stream_ids[0];
1593 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001594 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001595 }
1596
Steve Anton4171afb2017-11-20 10:20:22 -08001597 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001598 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001599 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001600 auto* audio_sender = new AudioRtpSender(
1601 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001602 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001603 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001604 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001605 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001606 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001607 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001608 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001609 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001610 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001611 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001612 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001613 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001614 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001615 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001616 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001617 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001618
deadbeefe1f9d832016-01-14 15:35:42 -08001619 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001620}
1621
deadbeef70ab1a12015-09-28 16:53:55 -07001622std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1623 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001624 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001625 for (auto sender : GetSendersInternal()) {
1626 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001627 }
1628 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001629}
1630
Steve Anton4171afb2017-11-20 10:20:22 -08001631std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1632PeerConnection::GetSendersInternal() const {
1633 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1634 all_senders;
1635 for (auto transceiver : transceivers_) {
1636 auto senders = transceiver->internal()->senders();
1637 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1638 }
1639 return all_senders;
1640}
1641
deadbeef70ab1a12015-09-28 16:53:55 -07001642std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1643PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001644 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001645 for (const auto& receiver : GetReceiversInternal()) {
1646 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001647 }
1648 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001649}
1650
Steve Anton4171afb2017-11-20 10:20:22 -08001651std::vector<
1652 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1653PeerConnection::GetReceiversInternal() const {
1654 std::vector<
1655 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1656 all_receivers;
1657 for (auto transceiver : transceivers_) {
1658 auto receivers = transceiver->internal()->receivers();
1659 all_receivers.insert(all_receivers.end(), receivers.begin(),
1660 receivers.end());
1661 }
1662 return all_receivers;
1663}
1664
Steve Anton9158ef62017-11-27 13:01:52 -08001665std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1666PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001667 RTC_CHECK(IsUnifiedPlan())
1668 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001669 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1670 for (auto transceiver : transceivers_) {
1671 all_transceivers.push_back(transceiver);
1672 }
1673 return all_transceivers;
1674}
1675
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001677 MediaStreamTrackInterface* track,
1678 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001679 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001680 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001681 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001682 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683 return false;
1684 }
1685
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001686 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001687 // The StatsCollector is used to tell if a track is valid because it may
1688 // remember tracks that the PeerConnection previously removed.
1689 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001690 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1691 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001692 return false;
1693 }
Steve Antonad182762018-09-05 20:22:40 +00001694 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1695 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001696 return true;
1697}
1698
hbos74e1a4f2016-09-15 23:33:01 -07001699void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001700 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001701 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001702 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001703 stats_collector_->GetStatsReport(callback);
1704}
1705
Henrik Boström1df1bf82018-03-20 13:24:20 +01001706void PeerConnection::GetStats(
1707 rtc::scoped_refptr<RtpSenderInterface> selector,
1708 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1709 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1710 RTC_DCHECK(callback);
1711 RTC_DCHECK(stats_collector_);
1712 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1713 if (selector) {
1714 for (const auto& proxy_transceiver : transceivers_) {
1715 for (const auto& proxy_sender :
1716 proxy_transceiver->internal()->senders()) {
1717 if (proxy_sender == selector) {
1718 internal_sender = proxy_sender->internal();
1719 break;
1720 }
1721 }
1722 if (internal_sender)
1723 break;
1724 }
1725 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001726 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001727 // belong to the PeerConnection (in Plan B, senders can be removed from the
1728 // PeerConnection). This means that "all the stats objects representing the
1729 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1730 // produces an empty stats report.
1731 stats_collector_->GetStatsReport(internal_sender, callback);
1732}
1733
1734void PeerConnection::GetStats(
1735 rtc::scoped_refptr<RtpReceiverInterface> selector,
1736 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1737 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1738 RTC_DCHECK(callback);
1739 RTC_DCHECK(stats_collector_);
1740 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1741 if (selector) {
1742 for (const auto& proxy_transceiver : transceivers_) {
1743 for (const auto& proxy_receiver :
1744 proxy_transceiver->internal()->receivers()) {
1745 if (proxy_receiver == selector) {
1746 internal_receiver = proxy_receiver->internal();
1747 break;
1748 }
1749 }
1750 if (internal_receiver)
1751 break;
1752 }
1753 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001754 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001755 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1756 // the PeerConnection). This means that "all the stats objects representing
1757 // the selector" is an empty set. Invoking GetStatsReport() with a null
1758 // selector produces an empty stats report.
1759 stats_collector_->GetStatsReport(internal_receiver, callback);
1760}
1761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001762PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1763 return signaling_state_;
1764}
1765
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001766PeerConnectionInterface::IceConnectionState
1767PeerConnection::ice_connection_state() {
1768 return ice_connection_state_;
1769}
1770
Alex Loiko9289eda2018-11-23 16:18:59 +00001771PeerConnectionInterface::IceConnectionState
1772PeerConnection::standardized_ice_connection_state() {
1773 return standardized_ice_connection_state_;
1774}
1775
Jonas Olsson635474e2018-10-18 15:58:17 +02001776PeerConnectionInterface::PeerConnectionState
1777PeerConnection::peer_connection_state() {
1778 return connection_state_;
1779}
1780
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001781PeerConnectionInterface::IceGatheringState
1782PeerConnection::ice_gathering_state() {
1783 return ice_gathering_state_;
1784}
1785
Yves Gerey665174f2018-06-19 15:03:05 +02001786rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001787 const std::string& label,
1788 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001789 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001790
deadbeefab9b2d12015-10-14 11:33:11 -07001791 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001792
kwibergd1fe2812016-04-27 06:47:29 -07001793 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001794 if (config) {
1795 internal_config.reset(new InternalDataChannelInit(*config));
1796 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001797 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001798 InternalCreateDataChannel(label, internal_config.get()));
1799 if (!channel.get()) {
1800 return nullptr;
1801 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001803 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1804 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001805 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001806 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001807 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001808 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809 return DataChannelProxy::Create(signaling_thread(), channel.get());
1810}
1811
1812void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001813 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001814 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001815
nisse7ce109a2017-01-31 00:57:56 -08001816 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001817 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001818 return;
1819 }
deadbeefab9b2d12015-10-14 11:33:11 -07001820
Steve Anton8d3444d2017-10-20 15:30:51 -07001821 if (IsClosed()) {
1822 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001823 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001824 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001825 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001826 return;
1827 }
1828
zhihuang1c378ed2017-08-17 14:10:50 -07001829 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001830 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001831 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001832 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001833 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001834 return;
1835 }
1836
Steve Anton22da89f2018-01-25 13:58:07 -08001837 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1838 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1839 if (IsUnifiedPlan()) {
1840 RTCError error = HandleLegacyOfferOptions(options);
1841 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001842 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001843 return;
1844 }
1845 }
1846
zhihuang1c378ed2017-08-17 14:10:50 -07001847 cricket::MediaSessionOptions session_options;
1848 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001849 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850}
1851
Steve Anton22da89f2018-01-25 13:58:07 -08001852RTCError PeerConnection::HandleLegacyOfferOptions(
1853 const RTCOfferAnswerOptions& options) {
1854 RTC_DCHECK(IsUnifiedPlan());
1855
1856 if (options.offer_to_receive_audio == 0) {
1857 RemoveRecvDirectionFromReceivingTransceiversOfType(
1858 cricket::MEDIA_TYPE_AUDIO);
1859 } else if (options.offer_to_receive_audio == 1) {
1860 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1861 } else if (options.offer_to_receive_audio > 1) {
1862 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1863 "offer_to_receive_audio > 1 is not supported.");
1864 }
1865
1866 if (options.offer_to_receive_video == 0) {
1867 RemoveRecvDirectionFromReceivingTransceiversOfType(
1868 cricket::MEDIA_TYPE_VIDEO);
1869 } else if (options.offer_to_receive_video == 1) {
1870 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1871 } else if (options.offer_to_receive_video > 1) {
1872 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1873 "offer_to_receive_video > 1 is not supported.");
1874 }
1875
1876 return RTCError::OK();
1877}
1878
1879void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1880 cricket::MediaType media_type) {
1881 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001882 RtpTransceiverDirection new_direction =
1883 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1884 if (new_direction != transceiver->direction()) {
1885 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1886 << " transceiver (MID="
1887 << transceiver->mid().value_or("<not set>") << ") from "
1888 << RtpTransceiverDirectionToString(
1889 transceiver->direction())
1890 << " to "
1891 << RtpTransceiverDirectionToString(new_direction)
1892 << " since CreateOffer specified offer_to_receive=0";
1893 transceiver->internal()->set_direction(new_direction);
1894 }
Steve Anton22da89f2018-01-25 13:58:07 -08001895 }
1896}
1897
1898void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1899 cricket::MediaType media_type) {
1900 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001901 RTC_LOG(LS_INFO)
1902 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1903 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001904 RtpTransceiverInit init;
1905 init.direction = RtpTransceiverDirection::kRecvOnly;
1906 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1907 }
1908}
1909
1910std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1911PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1912 std::vector<
1913 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1914 receiving_transceivers;
1915 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001916 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001917 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1918 receiving_transceivers.push_back(transceiver);
1919 }
1920 }
1921 return receiving_transceivers;
1922}
1923
htaa2a49d92016-03-04 02:51:39 -08001924void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1925 const RTCOfferAnswerOptions& options) {
1926 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001927 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001928 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001929 return;
1930 }
1931
Steve Antondffead82018-02-06 10:31:29 -08001932 if (!(signaling_state_ == kHaveRemoteOffer ||
1933 signaling_state_ == kHaveLocalPrAnswer)) {
1934 std::string error =
1935 "PeerConnection cannot create an answer in a state other than "
1936 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001937 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001938 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001939 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001940 return;
1941 }
1942
Steve Antondffead82018-02-06 10:31:29 -08001943 // The remote description should be set if we're in the right state.
1944 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001945
Steve Anton22da89f2018-01-25 13:58:07 -08001946 if (IsUnifiedPlan()) {
1947 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1948 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1949 "supported with Unified Plan semantics. Use the "
1950 "RtpTransceiver API instead.";
1951 }
1952 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1953 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1954 "supported with Unified Plan semantics. Use the "
1955 "RtpTransceiver API instead.";
1956 }
1957 }
1958
htaa2a49d92016-03-04 02:51:39 -08001959 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001960 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001961
Steve Antond25da372017-11-06 14:50:29 -08001962 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001963}
1964
1965void PeerConnection::SetLocalDescription(
1966 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001967 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001968 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001969
Steve Anton80dd7b52018-02-16 17:08:42 -08001970 // The SetLocalDescription contract is that we take ownership of the session
1971 // description regardless of the outcome, so wrap it in a unique_ptr right
1972 // away. Ideally, SetLocalDescription's signature will be changed to take the
1973 // description as a unique_ptr argument to formalize this agreement.
1974 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1975
nisse7ce109a2017-01-31 00:57:56 -08001976 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001977 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001978 return;
1979 }
Steve Anton8a006912017-12-04 15:25:56 -08001980
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001981 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001982 PostSetSessionDescriptionFailure(
1983 observer,
1984 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 return;
1986 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001987
Steve Anton80dd7b52018-02-16 17:08:42 -08001988 // If a session error has occurred the PeerConnection is in a possibly
1989 // inconsistent state so fail right away.
1990 if (session_error() != SessionError::kNone) {
1991 std::string error_message = GetSessionErrorMsg();
1992 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001993 PostSetSessionDescriptionFailure(
1994 observer,
1995 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001996 return;
1997 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001998
Steve Anton80dd7b52018-02-16 17:08:42 -08001999 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2000 if (!error.ok()) {
2001 std::string error_message = GetSetDescriptionErrorMessage(
2002 cricket::CS_LOCAL, desc->GetType(), error);
2003 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002004 PostSetSessionDescriptionFailure(
2005 observer,
2006 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002007 return;
2008 }
2009
2010 // Grab the description type before moving ownership to ApplyLocalDescription,
2011 // which may destroy it before returning.
2012 const SdpType type = desc->GetType();
2013
2014 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002015 // |desc| may be destroyed at this point.
2016
2017 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002018 // If ApplyLocalDescription fails, the PeerConnection could be in an
2019 // inconsistent state, so act conservatively here and set the session error
2020 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2021 SetSessionError(SessionError::kContent, error.message());
2022 std::string error_message =
2023 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2024 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002025 PostSetSessionDescriptionFailure(
2026 observer,
2027 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002028 return;
2029 }
Steve Anton8a006912017-12-04 15:25:56 -08002030 RTC_DCHECK(local_description());
2031
2032 PostSetSessionDescriptionSuccess(observer);
2033
Steve Antonad182762018-09-05 20:22:40 +00002034 // MaybeStartGathering needs to be called after posting
2035 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2036 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002037 transport_controller_->MaybeStartGathering();
2038
Steve Antona3a92c22017-12-07 10:27:41 -08002039 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002040 // TODO(deadbeef): We already had to hop to the network thread for
2041 // MaybeStartGathering...
2042 network_thread()->Invoke<void>(
2043 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2044 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002045 // Make UMA notes about what was agreed to.
2046 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002047 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002048 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002049}
2050
2051RTCError PeerConnection::ApplyLocalDescription(
2052 std::unique_ptr<SessionDescriptionInterface> desc) {
2053 RTC_DCHECK_RUN_ON(signaling_thread());
2054 RTC_DCHECK(desc);
2055
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002056 // Update stats here so that we have the most recent stats for tracks and
2057 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002058 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002059
Steve Antondcc3c022017-12-22 16:02:54 -08002060 // Take a reference to the old local description since it's used below to
2061 // compare against the new local description. When setting the new local
2062 // description, grab ownership of the replaced session description in case it
2063 // is the same as |old_local_description|, to keep it alive for the duration
2064 // of the method.
2065 const SessionDescriptionInterface* old_local_description =
2066 local_description();
2067 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002068 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002069 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002070 replaced_local_description = pending_local_description_
2071 ? std::move(pending_local_description_)
2072 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002073 current_local_description_ = std::move(desc);
2074 pending_local_description_ = nullptr;
2075 current_remote_description_ = std::move(pending_remote_description_);
2076 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002077 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002078 pending_local_description_ = std::move(desc);
2079 }
2080 // The session description to apply now must be accessed by
2081 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002082 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002083
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002084 if (!is_caller_) {
2085 if (remote_description()) {
2086 // Remote description was applied first, so this PC is the callee.
2087 is_caller_ = false;
2088 } else {
2089 // Local description is applied first, so this PC is the caller.
2090 is_caller_ = true;
2091 }
2092 }
2093
Zhi Huange830e682018-03-30 10:48:35 -07002094 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2095 if (!error.ok()) {
2096 return error;
2097 }
2098
Steve Antondcc3c022017-12-22 16:02:54 -08002099 if (IsUnifiedPlan()) {
2100 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002101 cricket::CS_LOCAL, *local_description(), old_local_description,
2102 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002103 if (!error.ok()) {
2104 return error;
2105 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002106 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2107 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002108 for (auto transceiver : transceivers_) {
2109 const ContentInfo* content =
2110 FindMediaSectionForTransceiver(transceiver, local_description());
2111 if (!content) {
2112 continue;
2113 }
2114 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002115 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2116 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002117 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002118 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2119 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2120 // "recvonly", process the removal of a remote track for the media
2121 // description, given transceiver, removeList, and muteTracks.
2122 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2123 (transceiver->internal()->fired_direction() &&
2124 RtpTransceiverDirectionHasRecv(
2125 *transceiver->internal()->fired_direction()))) {
2126 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2127 &removed_streams);
2128 }
2129 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2130 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002131 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002132 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002133 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002134 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002135 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002136 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002137 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002138 }
2139 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002140 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002141 }
2142 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002143 // Media channels will be created only when offer is set. These may use new
2144 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002145 if (type == SdpType::kOffer) {
2146 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2147 // description is applied. Restore back to old description.
2148 RTCError error = CreateChannels(*local_description()->description());
2149 if (!error.ok()) {
2150 return error;
2151 }
2152 }
Steve Antondcc3c022017-12-22 16:02:54 -08002153 // Remove unused channels if MediaContentDescription is rejected.
2154 RemoveUnusedChannels(local_description()->description());
2155 }
Steve Anton8a006912017-12-04 15:25:56 -08002156
Zhi Huange830e682018-03-30 10:48:35 -07002157 error = UpdateSessionState(type, cricket::CS_LOCAL,
2158 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002159 if (!error.ok()) {
2160 return error;
2161 }
Steve Antondcc3c022017-12-22 16:02:54 -08002162
Steve Anton8a006912017-12-04 15:25:56 -08002163 if (remote_description()) {
2164 // Now that we have a local description, we can push down remote candidates.
2165 UseCandidatesInSessionDescription(remote_description());
2166 }
2167
2168 pending_ice_restarts_.clear();
2169 if (session_error() != SessionError::kNone) {
2170 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2171 }
2172
deadbeefab9b2d12015-10-14 11:33:11 -07002173 // If setting the description decided our SSL role, allocate any necessary
2174 // SCTP sids.
2175 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002176 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002177 AllocateSctpSids(role);
2178 }
2179
Steve Antond3679212018-01-17 17:41:02 -08002180 if (IsUnifiedPlan()) {
2181 for (auto transceiver : transceivers_) {
2182 const ContentInfo* content =
2183 FindMediaSectionForTransceiver(transceiver, local_description());
2184 if (!content) {
2185 continue;
2186 }
Steve Anton74255ff2018-01-24 18:32:57 -08002187 const auto& streams = content->media_description()->streams();
2188 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002189 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002190 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002191 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002192 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002193 } else {
2194 // 0 is a special value meaning "this sender has no associated send
2195 // stream". Need to call this so the sender won't attempt to configure
2196 // a no longer existing stream and run into DCHECKs in the lower
2197 // layers.
2198 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002199 }
2200 }
2201 } else {
2202 // Plan B semantics.
2203
Steve Antondcc3c022017-12-22 16:02:54 -08002204 // Update state and SSRC of local MediaStreams and DataChannels based on the
2205 // local session description.
2206 const cricket::ContentInfo* audio_content =
2207 GetFirstAudioContent(local_description()->description());
2208 if (audio_content) {
2209 if (audio_content->rejected) {
2210 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2211 } else {
2212 const cricket::AudioContentDescription* audio_desc =
2213 audio_content->media_description()->as_audio();
2214 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2215 }
deadbeeffaac4972015-11-12 15:33:07 -08002216 }
deadbeefab9b2d12015-10-14 11:33:11 -07002217
Steve Antondcc3c022017-12-22 16:02:54 -08002218 const cricket::ContentInfo* video_content =
2219 GetFirstVideoContent(local_description()->description());
2220 if (video_content) {
2221 if (video_content->rejected) {
2222 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2223 } else {
2224 const cricket::VideoContentDescription* video_desc =
2225 video_content->media_description()->as_video();
2226 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2227 }
deadbeeffaac4972015-11-12 15:33:07 -08002228 }
deadbeefab9b2d12015-10-14 11:33:11 -07002229 }
2230
2231 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002232 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002233 if (data_content) {
2234 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002235 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002236 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002237 cricket::kMediaProtocolRtpPrefix)) {
2238 UpdateLocalRtpDataChannels(data_desc->streams());
2239 }
2240 }
2241
Steve Anton8a006912017-12-04 15:25:56 -08002242 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243}
2244
Steve Anton06817cd2018-12-18 15:55:30 -08002245// The SDP parser used to populate these values by default for the 'content
2246// name' if an a=mid line was absent.
2247static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2248 switch (media_type) {
2249 case cricket::MEDIA_TYPE_AUDIO:
2250 return cricket::CN_AUDIO;
2251 case cricket::MEDIA_TYPE_VIDEO:
2252 return cricket::CN_VIDEO;
2253 case cricket::MEDIA_TYPE_DATA:
2254 return cricket::CN_DATA;
2255 }
2256 RTC_NOTREACHED();
2257 return "";
2258}
2259
2260void PeerConnection::FillInMissingRemoteMids(
2261 cricket::SessionDescription* remote_description) {
2262 RTC_DCHECK(remote_description);
2263 const cricket::ContentInfos& local_contents =
2264 (local_description() ? local_description()->description()->contents()
2265 : cricket::ContentInfos());
Steve Anton06817cd2018-12-18 15:55:30 -08002266 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2267 cricket::ContentInfo& content = remote_description->contents()[i];
2268 if (!content.name.empty()) {
2269 continue;
2270 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002271 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002272 absl::string_view source_explanation;
2273 if (IsUnifiedPlan()) {
2274 if (i < local_contents.size()) {
2275 new_mid = local_contents[i].name;
2276 source_explanation = "from the matching local media section";
2277 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002278 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002279 source_explanation = "generated just now";
2280 }
2281 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002282 new_mid = std::string(
2283 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002284 source_explanation = "to match pre-existing behavior";
2285 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002286 content.name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002287 remote_description->transport_infos()[i].content_name =
2288 std::string(new_mid);
2289 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2290 << " is missing an a=mid line. Filling in the value '"
2291 << new_mid << "' " << source_explanation << ".";
2292 }
2293}
2294
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002296 SetSessionDescriptionObserver* observer,
2297 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002298 SetRemoteDescription(
2299 std::unique_ptr<SessionDescriptionInterface>(desc),
2300 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2301 new SetRemoteDescriptionObserverAdapter(this, observer)));
2302}
2303
2304void PeerConnection::SetRemoteDescription(
2305 std::unique_ptr<SessionDescriptionInterface> desc,
2306 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002307 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002308
nisse7ce109a2017-01-31 00:57:56 -08002309 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002310 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002311 return;
2312 }
Steve Anton8a006912017-12-04 15:25:56 -08002313
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002314 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002315 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002316 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002317 return;
2318 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002319
Steve Anton80dd7b52018-02-16 17:08:42 -08002320 // If a session error has occurred the PeerConnection is in a possibly
2321 // inconsistent state so fail right away.
2322 if (session_error() != SessionError::kNone) {
2323 std::string error_message = GetSessionErrorMsg();
2324 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2325 observer->OnSetRemoteDescriptionComplete(
2326 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2327 return;
2328 }
Steve Anton71439a62018-02-15 11:53:06 -08002329
Steve Antonba42e992018-04-09 14:10:01 -07002330 if (desc->GetType() == SdpType::kOffer) {
2331 // Report to UMA the format of the received offer.
2332 ReportSdpFormatReceived(*desc);
2333 }
2334
Steve Anton06817cd2018-12-18 15:55:30 -08002335 // Handle remote descriptions missing a=mid lines for interop with legacy end
2336 // points.
2337 FillInMissingRemoteMids(desc->description());
2338
Steve Anton80dd7b52018-02-16 17:08:42 -08002339 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002340 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002341 std::string error_message = GetSetDescriptionErrorMessage(
2342 cricket::CS_REMOTE, desc->GetType(), error);
2343 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002344 observer->OnSetRemoteDescriptionComplete(
2345 RTCError(error.type(), std::move(error_message)));
2346 return;
2347 }
Steve Anton71439a62018-02-15 11:53:06 -08002348
Steve Anton80dd7b52018-02-16 17:08:42 -08002349 // Grab the description type before moving ownership to
2350 // ApplyRemoteDescription, which may destroy it before returning.
2351 const SdpType type = desc->GetType();
2352
2353 error = ApplyRemoteDescription(std::move(desc));
2354 // |desc| may be destroyed at this point.
2355
2356 if (!error.ok()) {
2357 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2358 // inconsistent state, so act conservatively here and set the session error
2359 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2360 SetSessionError(SessionError::kContent, error.message());
2361 std::string error_message =
2362 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2363 RTC_LOG(LS_ERROR) << error_message;
2364 observer->OnSetRemoteDescriptionComplete(
2365 RTCError(error.type(), std::move(error_message)));
2366 return;
2367 }
2368 RTC_DCHECK(remote_description());
2369
2370 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002371 // TODO(deadbeef): We already had to hop to the network thread for
2372 // MaybeStartGathering...
2373 network_thread()->Invoke<void>(
2374 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2375 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002376 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002377 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002378 }
2379
2380 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002381 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002382}
2383
2384RTCError PeerConnection::ApplyRemoteDescription(
2385 std::unique_ptr<SessionDescriptionInterface> desc) {
2386 RTC_DCHECK_RUN_ON(signaling_thread());
2387 RTC_DCHECK(desc);
2388
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002389 // Update stats here so that we have the most recent stats for tracks and
2390 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002391 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002392
Steve Antondcc3c022017-12-22 16:02:54 -08002393 // Take a reference to the old remote description since it's used below to
2394 // compare against the new remote description. When setting the new remote
2395 // description, grab ownership of the replaced session description in case it
2396 // is the same as |old_remote_description|, to keep it alive for the duration
2397 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002398 const SessionDescriptionInterface* old_remote_description =
2399 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002400 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002401 SdpType type = desc->GetType();
2402 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002403 replaced_remote_description = pending_remote_description_
2404 ? std::move(pending_remote_description_)
2405 : std::move(current_remote_description_);
2406 current_remote_description_ = std::move(desc);
2407 pending_remote_description_ = nullptr;
2408 current_local_description_ = std::move(pending_local_description_);
2409 } else {
2410 replaced_remote_description = std::move(pending_remote_description_);
2411 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 }
Steve Anton8a006912017-12-04 15:25:56 -08002413 // The session description to apply now must be accessed by
2414 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002415 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416
Zhi Huange830e682018-03-30 10:48:35 -07002417 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2418 if (!error.ok()) {
2419 return error;
2420 }
Steve Anton8a006912017-12-04 15:25:56 -08002421 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002422 if (IsUnifiedPlan()) {
2423 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002424 cricket::CS_REMOTE, *remote_description(), local_description(),
2425 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002426 if (!error.ok()) {
2427 return error;
2428 }
Steve Antondcc3c022017-12-22 16:02:54 -08002429 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002430 // Media channels will be created only when offer is set. These may use new
2431 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002432 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002433 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002434 // description is applied. Restore back to old description.
2435 RTCError error = CreateChannels(*remote_description()->description());
2436 if (!error.ok()) {
2437 return error;
2438 }
2439 }
Steve Antondcc3c022017-12-22 16:02:54 -08002440 // Remove unused channels if MediaContentDescription is rejected.
2441 RemoveUnusedChannels(remote_description()->description());
2442 }
Steve Anton8a006912017-12-04 15:25:56 -08002443
Zhi Huange830e682018-03-30 10:48:35 -07002444 // NOTE: Candidates allocation will be initiated only when
2445 // SetLocalDescription is called.
2446 error = UpdateSessionState(type, cricket::CS_REMOTE,
2447 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002448 if (!error.ok()) {
2449 return error;
2450 }
2451
2452 if (local_description() &&
2453 !UseCandidatesInSessionDescription(remote_description())) {
2454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2455 }
2456
2457 if (old_remote_description) {
2458 for (const cricket::ContentInfo& content :
2459 old_remote_description->description()->contents()) {
2460 // Check if this new SessionDescription contains new ICE ufrag and
2461 // password that indicates the remote peer requests an ICE restart.
2462 // TODO(deadbeef): When we start storing both the current and pending
2463 // remote description, this should reset pending_ice_restarts and compare
2464 // against the current description.
2465 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2466 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002467 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002468 pending_ice_restarts_.insert(content.name);
2469 }
2470 } else {
2471 // We retain all received candidates only if ICE is not restarted.
2472 // When ICE is restarted, all previous candidates belong to an old
2473 // generation and should not be kept.
2474 // TODO(deadbeef): This goes against the W3C spec which says the remote
2475 // description should only contain candidates from the last set remote
2476 // description plus any candidates added since then. We should remove
2477 // this once we're sure it won't break anything.
2478 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2479 old_remote_description, content.name, mutable_remote_description());
2480 }
2481 }
2482 }
2483
2484 if (session_error() != SessionError::kNone) {
2485 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2486 }
2487
2488 // Set the the ICE connection state to connecting since the connection may
2489 // become writable with peer reflexive candidates before any remote candidate
2490 // is signaled.
2491 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2492 // is to have a new signal the indicates a change in checking state from the
2493 // transport and expose a new checking() member from transport that can be
2494 // read to determine the current checking state. The existing SignalConnecting
2495 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002496 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002497 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002498 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2499 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2500 }
2501
deadbeefab9b2d12015-10-14 11:33:11 -07002502 // If setting the description decided our SSL role, allocate any necessary
2503 // SCTP sids.
2504 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002505 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002506 AllocateSctpSids(role);
2507 }
2508
Steve Antondcc3c022017-12-22 16:02:54 -08002509 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002510 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002511 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002512 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002513 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002514 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002515 for (auto transceiver : transceivers_) {
2516 const ContentInfo* content =
2517 FindMediaSectionForTransceiver(transceiver, remote_description());
2518 if (!content) {
2519 continue;
2520 }
2521 const MediaContentDescription* media_desc = content->media_description();
2522 RtpTransceiverDirection local_direction =
2523 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002524 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2525 // RTCSessionDescription: Set the associated remote streams given
2526 // transceiver.[[Receiver]], msids, addList, and removeList".
2527 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2528 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2529 std::vector<std::string> stream_ids;
2530 if (!media_desc->streams().empty()) {
2531 // The remote description has signaled the stream IDs.
2532 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002533 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002534 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2535 << " (" << GetStreamIdsString(stream_ids) << ").";
2536 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2537 stream_ids, &added_streams,
2538 &removed_streams);
2539 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2540 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2541 // and transceiver's current direction is neither sendrecv nor recvonly,
2542 // process the addition of a remote track for the media description.
2543 if (!transceiver->fired_direction() ||
2544 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2545 RTC_LOG(LS_INFO)
2546 << "Processing the addition of a remote track for MID="
2547 << content->name << ".";
2548 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002549 }
Steve Antondcc3c022017-12-22 16:02:54 -08002550 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002551 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2552 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2553 // removal of a remote track for the media description, given transceiver,
2554 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002555 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002556 (transceiver->fired_direction() &&
2557 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2558 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2559 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002560 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002561 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2562 transceiver->internal()->set_fired_direction(local_direction);
2563 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2564 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002565 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002566 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2567 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002568 transceiver->internal()->set_current_direction(local_direction);
2569 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002570 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2571 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002572 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002573 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2574 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002575 transceiver->Stop();
2576 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002577 if (!content->rejected &&
2578 RtpTransceiverDirectionHasRecv(local_direction)) {
2579 // Set ssrc to 0 in the case of an unsignalled ssrc.
2580 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002581 if (!media_desc->streams().empty() &&
2582 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002583 ssrc = media_desc->streams()[0].first_ssrc();
2584 }
2585 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002586 }
Steve Antondcc3c022017-12-22 16:02:54 -08002587 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002588 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002589 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002590 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002591 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002592 observer->OnTrack(transceiver);
2593 observer->OnAddTrack(transceiver->receiver(),
2594 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002595 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002596 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002597 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002598 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002599 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002600 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002601 }
2602 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002603 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002604 }
Steve Antondcc3c022017-12-22 16:02:54 -08002605 }
2606
Henrik Boströmfdb92012017-11-09 19:55:44 +01002607 const cricket::ContentInfo* audio_content =
2608 GetFirstAudioContent(remote_description()->description());
2609 const cricket::ContentInfo* video_content =
2610 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002611 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002612 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002613 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002614 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002615 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002616 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002617
2618 // Check if the descriptions include streams, just in case the peer supports
2619 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002620 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002621 (audio_desc && !audio_desc->streams().empty()) ||
2622 (video_desc && !video_desc->streams().empty())) {
2623 remote_peer_supports_msid_ = true;
2624 }
deadbeefab9b2d12015-10-14 11:33:11 -07002625
2626 // We wait to signal new streams until we finish processing the description,
2627 // since only at that point will new streams have all their tracks.
2628 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2629
Steve Antondcc3c022017-12-22 16:02:54 -08002630 if (!IsUnifiedPlan()) {
2631 // TODO(steveanton): When removing RTP senders/receivers in response to a
2632 // rejected media section, there is some cleanup logic that expects the
2633 // voice/ video channel to still be set. But in this method the voice/video
2634 // channel would have been destroyed by the SetRemoteDescription caller
2635 // above so the cleanup that relies on them fails to run. The RemoveSenders
2636 // calls should be moved to right before the DestroyChannel calls to fix
2637 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002638
Steve Antondcc3c022017-12-22 16:02:54 -08002639 // Find all audio rtp streams and create corresponding remote AudioTracks
2640 // and MediaStreams.
2641 if (audio_content) {
2642 if (audio_content->rejected) {
2643 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2644 } else {
2645 bool default_audio_track_needed =
2646 !remote_peer_supports_msid_ &&
2647 RtpTransceiverDirectionHasSend(audio_desc->direction());
2648 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2649 default_audio_track_needed, audio_desc->type(),
2650 new_streams);
2651 }
deadbeeffaac4972015-11-12 15:33:07 -08002652 }
deadbeefab9b2d12015-10-14 11:33:11 -07002653
Steve Antondcc3c022017-12-22 16:02:54 -08002654 // Find all video rtp streams and create corresponding remote VideoTracks
2655 // and MediaStreams.
2656 if (video_content) {
2657 if (video_content->rejected) {
2658 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2659 } else {
2660 bool default_video_track_needed =
2661 !remote_peer_supports_msid_ &&
2662 RtpTransceiverDirectionHasSend(video_desc->direction());
2663 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2664 default_video_track_needed, video_desc->type(),
2665 new_streams);
2666 }
deadbeeffaac4972015-11-12 15:33:07 -08002667 }
deadbeefab9b2d12015-10-14 11:33:11 -07002668
Steve Antondcc3c022017-12-22 16:02:54 -08002669 // Update the DataChannels with the information from the remote peer.
2670 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002671 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002672 cricket::kMediaProtocolRtpPrefix)) {
2673 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2674 }
deadbeefab9b2d12015-10-14 11:33:11 -07002675 }
deadbeefab9b2d12015-10-14 11:33:11 -07002676
Steve Antondcc3c022017-12-22 16:02:54 -08002677 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002678 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002679 for (size_t i = 0; i < new_streams->count(); ++i) {
2680 MediaStreamInterface* new_stream = new_streams->at(i);
2681 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002682 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002683 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2684 }
deadbeefab9b2d12015-10-14 11:33:11 -07002685
Steve Antondcc3c022017-12-22 16:02:54 -08002686 UpdateEndedRemoteMediaStreams();
2687 }
deadbeefab9b2d12015-10-14 11:33:11 -07002688
Steve Anton8a006912017-12-04 15:25:56 -08002689 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002690}
2691
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002692void PeerConnection::SetAssociatedRemoteStreams(
2693 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2694 const std::vector<std::string>& stream_ids,
2695 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2696 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2697 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2698 for (const std::string& stream_id : stream_ids) {
2699 rtc::scoped_refptr<MediaStreamInterface> stream =
2700 remote_streams_->find(stream_id);
2701 if (!stream) {
2702 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2703 MediaStream::Create(stream_id));
2704 remote_streams_->AddStream(stream);
2705 added_streams->push_back(stream);
2706 }
2707 media_streams.push_back(stream);
2708 }
2709 // Special case: "a=msid" missing, use random stream ID.
2710 if (media_streams.empty() &&
2711 !(remote_description()->description()->msid_signaling() &
2712 cricket::kMsidSignalingMediaSection)) {
2713 if (!missing_msid_default_stream_) {
2714 missing_msid_default_stream_ = MediaStreamProxy::Create(
2715 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2716 added_streams->push_back(missing_msid_default_stream_);
2717 }
2718 media_streams.push_back(missing_msid_default_stream_);
2719 }
2720 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2721 receiver->streams();
2722 // SetStreams() will add/remove the receiver's track to/from the streams. This
2723 // differs from the spec - the spec uses an "addList" and "removeList" to
2724 // update the stream-track relationships in a later step. We do this earlier,
2725 // changing the order of things, but the end-result is the same.
2726 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2727 // instead. https://crbug.com/webrtc/9480
2728 receiver->SetStreams(media_streams);
2729 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2730}
2731
Steve Anton0f5400a2018-07-17 14:25:36 -07002732void PeerConnection::ProcessRemovalOfRemoteTrack(
2733 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2734 transceiver,
2735 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2736 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2737 RTC_DCHECK(transceiver->mid());
2738 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2739 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002740 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002741 transceiver->internal()->receiver_internal()->streams();
2742 // This will remove the remote track from the streams.
2743 transceiver->internal()->receiver_internal()->set_stream_ids({});
2744 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002745 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2746}
2747
2748void PeerConnection::RemoveRemoteStreamsIfEmpty(
2749 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2750 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2751 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2752 // streams, see if the stream was removed by checking if this was the last
2753 // receiver with that stream ID.
2754 for (auto remote_stream : remote_streams) {
2755 if (remote_stream->GetAudioTracks().empty() &&
2756 remote_stream->GetVideoTracks().empty()) {
2757 remote_streams_->RemoveStream(remote_stream);
2758 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002759 }
2760 }
2761}
2762
Steve Antondcc3c022017-12-22 16:02:54 -08002763RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2764 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002765 const SessionDescriptionInterface& new_session,
2766 const SessionDescriptionInterface* old_local_description,
2767 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002768 RTC_DCHECK(IsUnifiedPlan());
2769
Steve Anton7464fca2018-01-19 11:10:37 -08002770 const cricket::ContentGroup* bundle_group = nullptr;
2771 if (new_session.GetType() == SdpType::kOffer) {
2772 auto bundle_group_or_error =
2773 GetEarlyBundleGroup(*new_session.description());
2774 if (!bundle_group_or_error.ok()) {
2775 return bundle_group_or_error.MoveError();
2776 }
2777 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002778 }
Steve Antondcc3c022017-12-22 16:02:54 -08002779
Steve Antondcc3c022017-12-22 16:02:54 -08002780 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002781 for (size_t i = 0; i < new_contents.size(); ++i) {
2782 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002783 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002784 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002785 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2786 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002787 const cricket::ContentInfo* old_local_content = nullptr;
2788 if (old_local_description &&
2789 i < old_local_description->description()->contents().size()) {
2790 old_local_content =
2791 &old_local_description->description()->contents()[i];
2792 }
2793 const cricket::ContentInfo* old_remote_content = nullptr;
2794 if (old_remote_description &&
2795 i < old_remote_description->description()->contents().size()) {
2796 old_remote_content =
2797 &old_remote_description->description()->contents()[i];
2798 }
Steve Antondcc3c022017-12-22 16:02:54 -08002799 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002800 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2801 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002802 if (!transceiver_or_error.ok()) {
2803 return transceiver_or_error.MoveError();
2804 }
2805 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002806 RTCError error =
2807 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2808 if (!error.ok()) {
2809 return error;
2810 }
2811 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002812 if (GetDataMid() && new_content.name != *GetDataMid()) {
2813 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002814 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2815 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002816 continue;
2817 }
2818 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2819 if (!error.ok()) {
2820 return error;
2821 }
Steve Antondcc3c022017-12-22 16:02:54 -08002822 } else {
2823 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2824 "Unknown section type.");
2825 }
2826 }
2827
2828 return RTCError::OK();
2829}
2830
2831RTCError PeerConnection::UpdateTransceiverChannel(
2832 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2833 transceiver,
2834 const cricket::ContentInfo& content,
2835 const cricket::ContentGroup* bundle_group) {
2836 RTC_DCHECK(IsUnifiedPlan());
2837 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002838 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002839 if (content.rejected) {
2840 if (channel) {
2841 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002842 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002843 }
2844 } else {
2845 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002846 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002847 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002848 } else {
Steve Anton69470252018-02-09 11:43:08 -08002849 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002850 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002851 }
2852 if (!channel) {
2853 LOG_AND_RETURN_ERROR(
2854 RTCErrorType::INTERNAL_ERROR,
2855 "Failed to create channel for mid=" + content.name);
2856 }
2857 transceiver->internal()->SetChannel(channel);
2858 }
2859 }
2860 return RTCError::OK();
2861}
2862
Steve Antonfa2260d2017-12-28 16:38:23 -08002863RTCError PeerConnection::UpdateDataChannel(
2864 cricket::ContentSource source,
2865 const cricket::ContentInfo& content,
2866 const cricket::ContentGroup* bundle_group) {
2867 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002868 // If data channels are disabled, ignore this media section. CreateAnswer
2869 // will take care of rejecting it.
2870 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002871 }
2872 if (content.rejected) {
2873 DestroyDataChannel();
2874 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002875 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002876 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002877 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2878 "Failed to create data channel.");
2879 }
2880 }
2881 if (source == cricket::CS_REMOTE) {
2882 const MediaContentDescription* data_desc = content.media_description();
2883 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2884 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2885 }
2886 }
2887 }
2888 return RTCError::OK();
2889}
2890
Steve Antondcc3c022017-12-22 16:02:54 -08002891RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2892PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002893 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002894 size_t mline_index,
2895 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002896 const ContentInfo* old_local_content,
2897 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002898 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002899 // If this is an offer then the m= section might be recycled. If the m=
2900 // section is being recycled (defined as: rejected in the current local or
2901 // remote description and not rejected in new description), dissociate the
2902 // currently associated RtpTransceiver by setting its mid property to null,
2903 // and discard the mapping between the transceiver and its m= section index.
2904 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2905 old_remote_content)) {
2906 // We want to dissociate the transceiver that has the rejected mid.
2907 const std::string& old_mid =
2908 (old_local_content && old_local_content->rejected)
2909 ? old_local_content->name
2910 : old_remote_content->name;
2911 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002912 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002913 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2914 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002915 old_transceiver->internal()->set_mid(absl::nullopt);
2916 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002917 }
2918 }
2919 const MediaContentDescription* media_desc = content.media_description();
2920 auto transceiver = GetAssociatedTransceiver(content.name);
2921 if (source == cricket::CS_LOCAL) {
2922 // Find the RtpTransceiver that corresponds to this m= section, using the
2923 // mapping between transceivers and m= section indices established when
2924 // creating the offer.
2925 if (!transceiver) {
2926 transceiver = GetTransceiverByMLineIndex(mline_index);
2927 }
2928 if (!transceiver) {
2929 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2930 "Unknown transceiver");
2931 }
2932 } else {
2933 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2934 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2935 // of the same type...
2936 if (!transceiver &&
2937 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2938 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2939 }
2940 // If no RtpTransceiver was found in the previous step, create one with a
2941 // recvonly direction.
2942 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002943 RTC_LOG(LS_INFO) << "Adding "
2944 << cricket::MediaTypeToString(media_desc->type())
2945 << " transceiver for MID=" << content.name
2946 << " at i=" << mline_index
2947 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002948 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002949 auto sender =
2950 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002951 std::string receiver_id;
2952 if (!media_desc->streams().empty()) {
2953 receiver_id = media_desc->streams()[0].id;
2954 } else {
2955 receiver_id = rtc::CreateRandomUuid();
2956 }
2957 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002958 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002959 transceiver->internal()->set_direction(
2960 RtpTransceiverDirection::kRecvOnly);
2961 }
2962 }
2963 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002964 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002965 LOG_AND_RETURN_ERROR(
2966 RTCErrorType::INVALID_PARAMETER,
2967 "Transceiver type does not match media description type.");
2968 }
2969 // Associate the found or created RtpTransceiver with the m= section by
2970 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2971 // section, and establish a mapping between the transceiver and the index of
2972 // the m= section.
2973 transceiver->internal()->set_mid(content.name);
2974 transceiver->internal()->set_mline_index(mline_index);
2975 return std::move(transceiver);
2976}
2977
2978rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2979PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2980 RTC_DCHECK(IsUnifiedPlan());
2981 for (auto transceiver : transceivers_) {
2982 if (transceiver->mid() == mid) {
2983 return transceiver;
2984 }
2985 }
2986 return nullptr;
2987}
2988
2989rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2990PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2991 RTC_DCHECK(IsUnifiedPlan());
2992 for (auto transceiver : transceivers_) {
2993 if (transceiver->internal()->mline_index() == mline_index) {
2994 return transceiver;
2995 }
2996 }
2997 return nullptr;
2998}
2999
3000rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3001PeerConnection::FindAvailableTransceiverToReceive(
3002 cricket::MediaType media_type) const {
3003 RTC_DCHECK(IsUnifiedPlan());
3004 // From JSEP section 5.10 (Applying a Remote Description):
3005 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3006 // the same type that were added to the PeerConnection by addTrack and are not
3007 // associated with any m= section and are not stopped, find the first such
3008 // RtpTransceiver.
3009 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003010 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003011 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3012 !transceiver->stopped()) {
3013 return transceiver;
3014 }
3015 }
3016 return nullptr;
3017}
3018
Steve Antoned10bd92017-12-05 10:52:59 -08003019const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3020 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3021 transceiver,
3022 const SessionDescriptionInterface* sdesc) const {
3023 RTC_DCHECK(transceiver);
3024 RTC_DCHECK(sdesc);
3025 if (IsUnifiedPlan()) {
3026 if (!transceiver->internal()->mid()) {
3027 // This transceiver is not associated with a media section yet.
3028 return nullptr;
3029 }
3030 return sdesc->description()->GetContentByName(
3031 *transceiver->internal()->mid());
3032 } else {
3033 // Plan B only allows at most one audio and one video section, so use the
3034 // first media section of that type.
3035 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003036 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003037 }
3038}
3039
deadbeef46c73892016-11-16 19:42:04 -08003040PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3041 return configuration_;
3042}
3043
deadbeef293e9262017-01-11 12:28:30 -08003044bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3045 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003046 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003047 if (IsClosed()) {
3048 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3049 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3050 }
3051
Qingsi Wanga2d60672018-04-11 16:57:45 -07003052 // According to JSEP, after setLocalDescription, changing the candidate pool
3053 // size is not allowed, and changing the set of ICE servers will not result
3054 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003055 if (local_description() && configuration.ice_candidate_pool_size !=
3056 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003057 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3058 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003059 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003060 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003061
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003062 if (local_description() &&
3063 configuration.use_media_transport != configuration_.use_media_transport) {
3064 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3065 "SetLocalDescription.";
3066 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3067 }
3068
3069 if (remote_description() &&
3070 configuration.use_media_transport != configuration_.use_media_transport) {
3071 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3072 "SetRemoteDescription.";
3073 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3074 }
3075
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003076 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003077 configuration.use_media_transport_for_data_channels !=
3078 configuration_.use_media_transport_for_data_channels) {
3079 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3080 "after calling SetLocalDescription.";
3081 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3082 }
3083
3084 if (remote_description() &&
3085 configuration.use_media_transport_for_data_channels !=
3086 configuration_.use_media_transport_for_data_channels) {
3087 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3088 "after calling SetRemoteDescription.";
3089 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3090 }
3091
3092 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003093 configuration.crypto_options != configuration_.crypto_options) {
3094 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3095 "SetLocalDescription.";
3096 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3097 }
3098
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003099 if (configuration.use_media_transport_for_data_channels ||
3100 configuration.use_media_transport) {
3101 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3102 << "Media transport requires MaxBundle policy.";
3103 }
3104
deadbeef293e9262017-01-11 12:28:30 -08003105 // The simplest (and most future-compatible) way to tell if the config was
3106 // modified in an invalid way is to copy each property we do support
3107 // modifying, then use operator==. There are far more properties we don't
3108 // support modifying than those we do, and more could be added.
3109 RTCConfiguration modified_config = configuration_;
3110 modified_config.servers = configuration.servers;
3111 modified_config.type = configuration.type;
3112 modified_config.ice_candidate_pool_size =
3113 configuration.ice_candidate_pool_size;
3114 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003115 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003116 modified_config.ice_check_interval_strong_connectivity =
3117 configuration.ice_check_interval_strong_connectivity;
3118 modified_config.ice_check_interval_weak_connectivity =
3119 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003120 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3121 modified_config.ice_unwritable_min_checks =
3122 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003123 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003124 modified_config.stun_candidate_keepalive_interval =
3125 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003126 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003127 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003128 modified_config.active_reset_srtp_params =
3129 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003130 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003131 modified_config.use_media_transport_for_data_channels =
3132 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003133 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003134 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003135 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3136 }
3137
Steve Anton038834f2017-07-14 15:59:59 -07003138 // Validate the modified configuration.
3139 RTCError validate_error = ValidateConfiguration(modified_config);
3140 if (!validate_error.ok()) {
3141 return SafeSetError(std::move(validate_error), error);
3142 }
3143
deadbeef293e9262017-01-11 12:28:30 -08003144 // Note that this isn't possible through chromium, since it's an unsigned
3145 // short in WebIDL.
3146 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003147 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003148 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3149 }
3150
3151 // Parse ICE servers before hopping to network thread.
3152 cricket::ServerAddresses stun_servers;
3153 std::vector<cricket::RelayServerConfig> turn_servers;
3154 RTCErrorType parse_error =
3155 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3156 if (parse_error != RTCErrorType::NONE) {
3157 return SafeSetError(parse_error, error);
3158 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003159 // Note if STUN or TURN servers were supplied.
3160 if (!stun_servers.empty()) {
3161 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3162 }
3163 if (!turn_servers.empty()) {
3164 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3165 }
deadbeef293e9262017-01-11 12:28:30 -08003166
3167 // In theory this shouldn't fail.
3168 if (!network_thread()->Invoke<bool>(
3169 RTC_FROM_HERE,
3170 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3171 stun_servers, turn_servers, modified_config.type,
3172 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003173 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003174 modified_config.turn_customizer,
3175 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003176 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003177 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3178 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003179
deadbeefd1a38b52016-12-10 13:15:33 -08003180 // As described in JSEP, calling setConfiguration with new ICE servers or
3181 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3182 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003183 if (modified_config.servers != configuration_.servers ||
3184 modified_config.type != configuration_.type ||
3185 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003186 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003187 }
skvladd1f5fda2017-02-03 16:54:05 -08003188
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003189 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003190 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003191 modified_config.use_media_transport ||
3192 modified_config.use_media_transport_for_data_channels
3193 ? factory_->media_transport_factory()
3194 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003195
Zhi Huangb57e1692018-06-12 11:41:11 -07003196 if (configuration_.active_reset_srtp_params !=
3197 modified_config.active_reset_srtp_params) {
3198 transport_controller_->SetActiveResetSrtpParams(
3199 modified_config.active_reset_srtp_params);
3200 }
3201
deadbeef293e9262017-01-11 12:28:30 -08003202 configuration_ = modified_config;
3203 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003204}
3205
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206bool PeerConnection::AddIceCandidate(
3207 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003208 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003209 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003210 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003211 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003212 return false;
3213 }
Steve Antond25da372017-11-06 14:50:29 -08003214
3215 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003216 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003217 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003218 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003219 return false;
3220 }
3221
3222 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003223 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003224 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003225 return false;
3226 }
3227
3228 bool valid = false;
3229 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3230 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003231 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003232 return false;
3233 }
3234
3235 // Add this candidate to the remote session description.
3236 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003237 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003238 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003239 return false;
3240 }
3241
3242 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003243 bool result = UseCandidate(ice_candidate);
3244 if (result) {
3245 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3246 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3247 } else {
3248 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3249 }
3250 return result;
Steve Antond25da372017-11-06 14:50:29 -08003251 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003252 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003253 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003254 return true;
3255 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003256}
3257
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003258bool PeerConnection::RemoveIceCandidates(
3259 const std::vector<cricket::Candidate>& candidates) {
3260 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003261 if (IsClosed()) {
3262 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3263 return false;
3264 }
3265
Steve Antond25da372017-11-06 14:50:29 -08003266 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003267 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3268 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003269 return false;
3270 }
3271
3272 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003273 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003274 return false;
3275 }
3276
3277 size_t number_removed =
3278 mutable_remote_description()->RemoveCandidates(candidates);
3279 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003280 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003281 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003282 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003283 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003284 }
3285
3286 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003287 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3288 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003289 RTC_LOG(LS_ERROR)
3290 << "RemoveIceCandidates: Error when removing remote candidates: "
3291 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003292 }
3293 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003294}
3295
Niels Möller0c4f7be2018-05-07 14:01:37 +02003296RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003297 if (!worker_thread()->IsCurrent()) {
3298 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003299 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003300 }
3301
Niels Möller0c4f7be2018-05-07 14:01:37 +02003302 const bool has_min = bitrate.min_bitrate_bps.has_value();
3303 const bool has_start = bitrate.start_bitrate_bps.has_value();
3304 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003305 if (has_min && *bitrate.min_bitrate_bps < 0) {
3306 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3307 "min_bitrate_bps <= 0");
3308 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003309 if (has_start) {
3310 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003311 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003312 "start_bitrate_bps < min_bitrate_bps");
3313 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003314 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3315 "curent_bitrate_bps < 0");
3316 }
3317 }
3318 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003319 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003320 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003321 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003322 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3324 "max_bitrate_bps < min_bitrate_bps");
3325 } else if (*bitrate.max_bitrate_bps < 0) {
3326 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3327 "max_bitrate_bps < 0");
3328 }
3329 }
3330
zstein4b979802017-06-02 14:37:37 -07003331 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003332 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003333
3334 return RTCError::OK();
3335}
3336
Alex Narest78609d52017-10-20 10:37:47 +02003337void PeerConnection::SetBitrateAllocationStrategy(
3338 std::unique_ptr<rtc::BitrateAllocationStrategy>
3339 bitrate_allocation_strategy) {
3340 rtc::Thread* worker_thread = factory_->worker_thread();
3341 if (!worker_thread->IsCurrent()) {
3342 rtc::BitrateAllocationStrategy* strategy_raw =
3343 bitrate_allocation_strategy.release();
3344 auto functor = [this, strategy_raw]() {
3345 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003346 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003347 };
3348 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3349 return;
3350 }
3351 RTC_DCHECK(call_.get());
3352 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3353}
3354
henrika5f6bf242017-11-01 11:06:56 +01003355void PeerConnection::SetAudioPlayout(bool playout) {
3356 if (!worker_thread()->IsCurrent()) {
3357 worker_thread()->Invoke<void>(
3358 RTC_FROM_HERE,
3359 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3360 return;
3361 }
3362 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003363 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003364 audio_state->SetPlayout(playout);
3365}
3366
3367void PeerConnection::SetAudioRecording(bool recording) {
3368 if (!worker_thread()->IsCurrent()) {
3369 worker_thread()->Invoke<void>(
3370 RTC_FROM_HERE,
3371 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3372 return;
3373 }
3374 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003375 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003376 audio_state->SetRecording(recording);
3377}
3378
Steve Anton8c0f7a72017-10-03 10:03:10 -07003379std::unique_ptr<rtc::SSLCertificate>
3380PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003381 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3382 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003383 return nullptr;
3384 }
Steve Antonf25303e2018-10-16 15:23:31 -07003385 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003386}
3387
Zhi Huang70b820f2018-01-27 14:16:15 -08003388std::unique_ptr<rtc::SSLCertChain>
3389PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003390 auto audio_transceiver = GetFirstAudioTransceiver();
3391 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003392 return nullptr;
3393 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003394 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003395 audio_transceiver->internal()->channel()->transport_name());
3396}
3397
3398rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3399PeerConnection::GetFirstAudioTransceiver() const {
3400 for (auto transceiver : transceivers_) {
3401 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3402 return transceiver;
3403 }
3404 }
3405 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003406}
3407
ivoc14d5dbe2016-07-04 07:06:55 -07003408bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3409 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003410 // TODO(eladalon): It would be better to not allow negative values into PC.
3411 const size_t max_size = (max_size_bytes < 0)
3412 ? RtcEventLog::kUnlimitedOutput
3413 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003414 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3415 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3416 output_period_ms = 5000;
3417 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003418 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003419 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003420 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003421}
3422
Bjorn Tereliusde939432017-11-20 17:38:14 +01003423bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3424 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003425 // TODO(eladalon): In C++14, this can be done with a lambda.
3426 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003427 bool operator()() {
3428 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3429 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003430 PeerConnection* const pc;
3431 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003432 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003433 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003434 return worker_thread()->Invoke<bool>(
3435 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003436}
3437
3438void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003439 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003440 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3441}
3442
Harald Alvestrandad88c882018-11-28 16:47:46 +01003443rtc::scoped_refptr<DtlsTransportInterface>
3444PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3445 return transport_controller_->LookupDtlsTransportByMid(mid);
3446}
3447
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003448const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003449 return pending_local_description_ ? pending_local_description_.get()
3450 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003451}
3452
3453const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003454 return pending_remote_description_ ? pending_remote_description_.get()
3455 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003456}
3457
deadbeeffe4a8a42016-12-20 17:56:17 -08003458const SessionDescriptionInterface* PeerConnection::current_local_description()
3459 const {
Steve Anton75737c02017-11-06 10:37:17 -08003460 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003461}
3462
3463const SessionDescriptionInterface* PeerConnection::current_remote_description()
3464 const {
Steve Anton75737c02017-11-06 10:37:17 -08003465 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003466}
3467
3468const SessionDescriptionInterface* PeerConnection::pending_local_description()
3469 const {
Steve Anton75737c02017-11-06 10:37:17 -08003470 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003471}
3472
3473const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3474 const {
Steve Anton75737c02017-11-06 10:37:17 -08003475 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003476}
3477
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003478void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003479 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003480 // Update stats here so that we have the most recent stats for tracks and
3481 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003482 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003483
Steve Anton75737c02017-11-06 10:37:17 -08003484 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003485 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003486
Steve Anton8af21862017-12-15 11:20:13 -08003487 for (auto transceiver : transceivers_) {
3488 transceiver->Stop();
3489 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003490
3491 // Ensure that all asynchronous stats requests are completed before destroying
3492 // the transport controller below.
3493 if (stats_collector_) {
3494 stats_collector_->WaitForPendingRequest();
3495 }
3496
3497 // Don't destroy BaseChannels until after stats has been cleaned up so that
3498 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003499 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003500
Qingsi Wang93a84392018-01-30 17:13:09 -08003501 // The event log is used in the transport controller, which must be outlived
3502 // by the former. CreateOffer by the peer connection is implemented
3503 // asynchronously and if the peer connection is closed without resetting the
3504 // WebRTC session description factory, the session description factory would
3505 // call the transport controller.
3506 webrtc_session_desc_factory_.reset();
3507 transport_controller_.reset();
3508
deadbeef42a42632017-03-10 15:18:00 -08003509 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003510 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3511 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003512
Steve Anton978b8762017-09-29 12:15:02 -07003513 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003514 call_.reset();
3515 // The event log must outlive call (and any other object that uses it).
3516 event_log_.reset();
3517 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003518 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003519 // The .h file says that observer can be discarded after close() returns.
3520 // Make sure this is true.
3521 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003522}
3523
Steve Antonad182762018-09-05 20:22:40 +00003524void PeerConnection::OnMessage(rtc::Message* msg) {
3525 switch (msg->message_id) {
3526 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3527 SetSessionDescriptionMsg* param =
3528 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3529 param->observer->OnSuccess();
3530 delete param;
3531 break;
3532 }
3533 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3534 SetSessionDescriptionMsg* param =
3535 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3536 param->observer->OnFailure(std::move(param->error));
3537 delete param;
3538 break;
3539 }
3540 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3541 CreateSessionDescriptionMsg* param =
3542 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3543 param->observer->OnFailure(std::move(param->error));
3544 delete param;
3545 break;
3546 }
3547 case MSG_GETSTATS: {
3548 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3549 StatsReports reports;
3550 stats_->GetStats(param->track, &reports);
3551 param->observer->OnComplete(reports);
3552 delete param;
3553 break;
3554 }
3555 case MSG_FREE_DATACHANNELS: {
3556 sctp_data_channels_to_free_.clear();
3557 break;
3558 }
3559 case MSG_REPORT_USAGE_PATTERN: {
3560 ReportUsagePattern();
3561 break;
3562 }
3563 default:
3564 RTC_NOTREACHED() << "Not implemented";
3565 break;
3566 }
3567}
3568
Steve Antonafb0bb72018-02-20 11:35:37 -08003569cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3570 RTC_DCHECK(!IsUnifiedPlan());
3571 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3572 GetAudioTransceiver()->internal()->channel());
3573 if (voice_channel) {
3574 return voice_channel->media_channel();
3575 } else {
3576 return nullptr;
3577 }
3578}
3579
3580cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3581 RTC_DCHECK(!IsUnifiedPlan());
3582 auto* video_channel = static_cast<cricket::VideoChannel*>(
3583 GetVideoTransceiver()->internal()->channel());
3584 if (video_channel) {
3585 return video_channel->media_channel();
3586 } else {
3587 return nullptr;
3588 }
3589}
3590
Steve Anton4171afb2017-11-20 10:20:22 -08003591void PeerConnection::CreateAudioReceiver(
3592 MediaStreamInterface* stream,
3593 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003594 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3595 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003596 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3597 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003598 auto* audio_receiver = new AudioRtpReceiver(
3599 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003600 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003601 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3602 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3603 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003604 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003605 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003606 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003607}
3608
Steve Anton4171afb2017-11-20 10:20:22 -08003609void PeerConnection::CreateVideoReceiver(
3610 MediaStreamInterface* stream,
3611 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003612 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3613 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003614 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3615 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003616 auto* video_receiver = new VideoRtpReceiver(
3617 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003618 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003619 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3620 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3621 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003622 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003623 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003624 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003625}
3626
deadbeef70ab1a12015-09-28 16:53:55 -07003627// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3628// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003629rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003630 const RtpSenderInfo& remote_sender_info) {
3631 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3632 if (!receiver) {
3633 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3634 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003635 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003636 }
Steve Anton4171afb2017-11-20 10:20:22 -08003637 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3638 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3639 } else {
3640 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3641 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003642 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003643}
3644
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003645void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3646 MediaStreamInterface* stream) {
3647 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003648 RTC_DCHECK(track);
3649 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003650 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003651 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003652 // We already have a sender for this track, so just change the stream_id
3653 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003654 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003655 return;
3656 }
3657
3658 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003659 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003660 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003661 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003662 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003663 // If the sender has already been configured in SDP, we call SetSsrc,
3664 // which will connect the sender to the underlying transport. This can
3665 // occur if a local session description that contains the ID of the sender
3666 // is set before AddStream is called. It can also occur if the local
3667 // session description is not changed and RemoveStream is called, and
3668 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003669 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003670 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003671 if (sender_info) {
3672 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003673 }
3674}
3675
3676// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3677// indefinitely, when we have unified plan SDP.
3678void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3679 MediaStreamInterface* stream) {
3680 RTC_DCHECK(!IsClosed());
3681 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003682 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003683 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3684 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003685 return;
3686 }
Steve Anton4171afb2017-11-20 10:20:22 -08003687 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003688}
3689
3690void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3691 MediaStreamInterface* stream) {
3692 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003693 RTC_DCHECK(track);
3694 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003695 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003696 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003697 // We already have a sender for this track, so just change the stream_id
3698 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003699 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003700 return;
3701 }
3702
3703 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003704 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003705 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003706 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003707 GetVideoTransceiver()->internal()->AddSender(new_sender);
3708 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003709 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003710 if (sender_info) {
3711 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003712 }
3713}
3714
3715void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3716 MediaStreamInterface* stream) {
3717 RTC_DCHECK(!IsClosed());
3718 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003719 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003720 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3721 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003722 return;
3723 }
Steve Anton4171afb2017-11-20 10:20:22 -08003724 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003725}
3726
Steve Antonba818672017-11-06 10:21:57 -08003727void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003728 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003729 if (ice_connection_state_ == new_state) {
3730 return;
3731 }
3732
deadbeefcbecd352015-09-23 11:50:27 -07003733 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003734 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003735 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003736 return;
3737 }
Steve Antonba818672017-11-06 10:21:57 -08003738
Mirko Bonadei675513b2017-11-09 11:09:25 +01003739 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3740 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003741 RTC_DCHECK(ice_connection_state_ !=
3742 PeerConnectionInterface::kIceConnectionClosed);
3743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003744 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003745 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003746}
3747
Alex Loiko9289eda2018-11-23 16:18:59 +00003748void PeerConnection::SetStandardizedIceConnectionState(
3749 PeerConnectionInterface::IceConnectionState new_state) {
3750 RTC_DCHECK(signaling_thread()->IsCurrent());
3751 if (standardized_ice_connection_state_ == new_state)
3752 return;
3753 if (IsClosed())
3754 return;
3755 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003756 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003757}
3758
Jonas Olsson635474e2018-10-18 15:58:17 +02003759void PeerConnection::SetConnectionState(
3760 PeerConnectionInterface::PeerConnectionState new_state) {
3761 RTC_DCHECK(signaling_thread()->IsCurrent());
3762 if (connection_state_ == new_state)
3763 return;
3764 if (IsClosed())
3765 return;
3766 connection_state_ = new_state;
3767 Observer()->OnConnectionChange(new_state);
3768}
3769
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003770void PeerConnection::OnIceGatheringChange(
3771 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003772 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003773 if (IsClosed()) {
3774 return;
3775 }
3776 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003777 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003778}
3779
jbauch81bf7b02017-03-25 08:31:12 -07003780void PeerConnection::OnIceCandidate(
3781 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003782 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003783 if (IsClosed()) {
3784 return;
3785 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003786 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003787 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3788 candidate->candidate().address().IsPrivateIP()) {
3789 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3790 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003791 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003792}
3793
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003794void PeerConnection::OnIceCandidatesRemoved(
3795 const std::vector<cricket::Candidate>& candidates) {
3796 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003797 if (IsClosed()) {
3798 return;
3799 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003800 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003801}
3802
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003803void PeerConnection::ChangeSignalingState(
3804 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003805 RTC_DCHECK(signaling_thread()->IsCurrent());
3806 if (signaling_state_ == signaling_state) {
3807 return;
3808 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003809 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3810 << GetSignalingStateString(signaling_state_)
3811 << " New state: "
3812 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003813 signaling_state_ = signaling_state;
3814 if (signaling_state == kClosed) {
3815 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003816 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003817 standardized_ice_connection_state_ =
3818 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003819 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3820 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003821 if (ice_gathering_state_ != kIceGatheringComplete) {
3822 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003823 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003824 }
3825 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003826 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003827}
3828
deadbeefeb459812015-12-15 19:24:43 -08003829void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3830 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003831 if (IsClosed()) {
3832 return;
3833 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003834 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003835 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003836}
3837
deadbeefeb459812015-12-15 19:24:43 -08003838void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3839 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003840 if (IsClosed()) {
3841 return;
3842 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003843 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003844 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003845}
3846
3847void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3848 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003849 if (IsClosed()) {
3850 return;
3851 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003852 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003853 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003854}
3855
3856void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3857 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003858 if (IsClosed()) {
3859 return;
3860 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003861 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003862 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003863}
3864
Henrik Boström31638672017-11-23 17:48:32 +01003865void PeerConnection::PostSetSessionDescriptionSuccess(
3866 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003867 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3868 signaling_thread()->Post(RTC_FROM_HERE, this,
3869 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003870}
3871
deadbeefab9b2d12015-10-14 11:33:11 -07003872void PeerConnection::PostSetSessionDescriptionFailure(
3873 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003874 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003875 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003876 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3877 msg->error = std::move(error);
3878 signaling_thread()->Post(RTC_FROM_HERE, this,
3879 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003880}
3881
3882void PeerConnection::PostCreateSessionDescriptionFailure(
3883 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003884 RTCError error) {
3885 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003886 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3887 msg->error = std::move(error);
3888 signaling_thread()->Post(RTC_FROM_HERE, this,
3889 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003890}
3891
zhihuang1c378ed2017-08-17 14:10:50 -07003892void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003893 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003894 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003895 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003896
Steve Antondcc3c022017-12-22 16:02:54 -08003897 if (IsUnifiedPlan()) {
3898 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3899 } else {
3900 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3901 }
3902
Steve Antonfa2260d2017-12-28 16:38:23 -08003903 // Intentionally unset the data channel type for RTP data channel with the
3904 // second condition. Otherwise the RTP data channels would be successfully
3905 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3906 // when building with chromium. We want to leave RTP data channels broken, so
3907 // people won't try to use them.
3908 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3909 session_options->data_channel_type = data_channel_type();
3910 }
3911
Steve Antondcc3c022017-12-22 16:02:54 -08003912 // Apply ICE restart flag and renomination flag.
3913 for (auto& options : session_options->media_description_options) {
3914 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3915 options.transport_options.enable_ice_renomination =
3916 configuration_.enable_ice_renomination;
3917 }
3918
3919 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003920 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003921 session_options->pooled_ice_credentials =
3922 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3923 RTC_FROM_HERE,
3924 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3925 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003926 session_options->offer_extmap_allow_mixed =
3927 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003928}
3929
3930void PeerConnection::GetOptionsForPlanBOffer(
3931 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3932 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003933 // Figure out transceiver directional preferences.
3934 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3935 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3936
3937 // By default, generate sendrecv/recvonly m= sections.
3938 bool recv_audio = true;
3939 bool recv_video = true;
3940
3941 // By default, only offer a new m= section if we have media to send with it.
3942 bool offer_new_audio_description = send_audio;
3943 bool offer_new_video_description = send_video;
3944 bool offer_new_data_description = HasDataChannels();
3945
3946 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003947 if (offer_answer_options.offer_to_receive_audio !=
3948 RTCOfferAnswerOptions::kUndefined) {
3949 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003950 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003951 offer_new_audio_description ||
3952 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003953 }
Steve Antondcc3c022017-12-22 16:02:54 -08003954 if (offer_answer_options.offer_to_receive_video !=
3955 RTCOfferAnswerOptions::kUndefined) {
3956 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003957 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003958 offer_new_video_description ||
3959 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003960 }
3961
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003962 absl::optional<size_t> audio_index;
3963 absl::optional<size_t> video_index;
3964 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003965 // If a current description exists, generate m= sections in the same order,
3966 // using the first audio/video/data section that appears and rejecting
3967 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003968 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003969 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003970 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003971 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3972 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3973 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003974 }
3975
zhihuang1c378ed2017-08-17 14:10:50 -07003976 // Add audio/video/data m= sections to the end if needed.
3977 if (!audio_index && offer_new_audio_description) {
3978 session_options->media_description_options.push_back(
3979 cricket::MediaDescriptionOptions(
3980 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003981 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3982 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003983 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003984 }
zhihuang1c378ed2017-08-17 14:10:50 -07003985 if (!video_index && offer_new_video_description) {
3986 session_options->media_description_options.push_back(
3987 cricket::MediaDescriptionOptions(
3988 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003989 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3990 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003991 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003992 }
zhihuang1c378ed2017-08-17 14:10:50 -07003993 if (!data_index && offer_new_data_description) {
3994 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003995 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003996 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003997 }
3998
3999 cricket::MediaDescriptionOptions* audio_media_description_options =
4000 !audio_index ? nullptr
4001 : &session_options->media_description_options[*audio_index];
4002 cricket::MediaDescriptionOptions* video_media_description_options =
4003 !video_index ? nullptr
4004 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004005
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004006 AddPlanBRtpSenderOptions(GetSendersInternal(),
4007 audio_media_description_options,
4008 video_media_description_options,
4009 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004010}
4011
Steve Antondcc3c022017-12-22 16:02:54 -08004012static cricket::MediaDescriptionOptions
4013GetMediaDescriptionOptionsForTransceiver(
4014 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4015 transceiver,
4016 const std::string& mid) {
4017 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004018 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004019 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004020 // This behavior is specified in JSEP. The gist is that:
4021 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4022 // sendrecv.
4023 // 2. If the MSID is included, then it must be included in any subsequent
4024 // offer/answer exactly the same until the RtpTransceiver is stopped.
4025 if (!transceiver->stopped() &&
4026 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
4027 transceiver->internal()->has_ever_been_used_to_send())) {
4028 cricket::SenderOptions sender_options;
4029 sender_options.track_id = transceiver->sender()->id();
4030 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02004031 int num_send_encoding_layers =
4032 transceiver->sender()->init_send_encodings().size();
4033 sender_options.num_sim_layers =
4034 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08004035 media_description_options.sender_options.push_back(sender_options);
4036 }
Steve Antondcc3c022017-12-22 16:02:54 -08004037 return media_description_options;
4038}
4039
Steve Anton5c72e712018-12-10 14:25:30 -08004040// Returns the ContentInfo at mline index |i|, or null if none exists.
4041static const ContentInfo* GetContentByIndex(
4042 const SessionDescriptionInterface* sdesc,
4043 size_t i) {
4044 if (!sdesc) {
4045 return nullptr;
4046 }
4047 const ContentInfos& contents = sdesc->description()->contents();
4048 return (i < contents.size() ? &contents[i] : nullptr);
4049}
4050
Steve Antondcc3c022017-12-22 16:02:54 -08004051void PeerConnection::GetOptionsForUnifiedPlanOffer(
4052 const RTCOfferAnswerOptions& offer_answer_options,
4053 cricket::MediaSessionOptions* session_options) {
4054 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4055 // Offers) and 5.2.2 (Subsequent Offers).
4056 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4057 const ContentInfos& local_contents =
4058 (local_description() ? local_description()->description()->contents()
4059 : ContentInfos());
4060 const ContentInfos& remote_contents =
4061 (remote_description() ? remote_description()->description()->contents()
4062 : ContentInfos());
4063 // The mline indices that can be recycled. New transceivers should reuse these
4064 // slots first.
4065 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004066 // First, go through each media section that exists in either the local or
4067 // remote description and generate a media section in this offer for the
4068 // associated transceiver. If a media section can be recycled, generate a
4069 // default, rejected media section here that can be later overwritten.
4070 for (size_t i = 0;
4071 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4072 // Either |local_content| or |remote_content| is non-null.
4073 const ContentInfo* local_content =
4074 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004075 const ContentInfo* current_local_content =
4076 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004077 const ContentInfo* remote_content =
4078 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004079 const ContentInfo* current_remote_content =
4080 GetContentByIndex(current_remote_description(), i);
4081 bool had_been_rejected =
4082 (current_local_content && current_local_content->rejected) ||
4083 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004084 const std::string& mid =
4085 (local_content ? local_content->name : remote_content->name);
4086 cricket::MediaType media_type =
4087 (local_content ? local_content->media_description()->type()
4088 : remote_content->media_description()->type());
4089 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4090 media_type == cricket::MEDIA_TYPE_VIDEO) {
4091 auto transceiver = GetAssociatedTransceiver(mid);
4092 RTC_CHECK(transceiver);
4093 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004094 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004095 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004096 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004097 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4098 RtpTransceiverDirection::kInactive,
4099 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004100 recycleable_mline_indices.push(i);
4101 } else {
4102 session_options->media_description_options.push_back(
4103 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4104 // CreateOffer shouldn't really cause any state changes in
4105 // PeerConnection, but we need a way to match new transceivers to new
4106 // media sections in SetLocalDescription and JSEP specifies this is done
4107 // by recording the index of the media section generated for the
4108 // transceiver in the offer.
4109 transceiver->internal()->set_mline_index(i);
4110 }
4111 } else {
4112 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004113 RTC_CHECK(GetDataMid());
4114 if (had_been_rejected || mid != *GetDataMid()) {
4115 session_options->media_description_options.push_back(
4116 GetMediaDescriptionOptionsForRejectedData(mid));
4117 } else {
4118 session_options->media_description_options.push_back(
4119 GetMediaDescriptionOptionsForActiveData(mid));
4120 }
Steve Antondcc3c022017-12-22 16:02:54 -08004121 }
4122 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004123
Steve Antondcc3c022017-12-22 16:02:54 -08004124 // Next, look for transceivers that are newly added (that is, are not stopped
4125 // and not associated). Reuse media sections marked as recyclable first,
4126 // otherwise append to the end of the offer. New media sections should be
4127 // added in the order they were added to the PeerConnection.
4128 for (auto transceiver : transceivers_) {
4129 if (transceiver->mid() || transceiver->stopped()) {
4130 continue;
4131 }
4132 size_t mline_index;
4133 if (!recycleable_mline_indices.empty()) {
4134 mline_index = recycleable_mline_indices.front();
4135 recycleable_mline_indices.pop();
4136 session_options->media_description_options[mline_index] =
4137 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004138 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004139 } else {
4140 mline_index = session_options->media_description_options.size();
4141 session_options->media_description_options.push_back(
4142 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004143 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004144 }
4145 // See comment above for why CreateOffer changes the transceiver's state.
4146 transceiver->internal()->set_mline_index(mline_index);
4147 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004148 // Lastly, add a m-section if we have local data channels and an m section
4149 // does not already exist.
4150 if (!GetDataMid() && HasDataChannels()) {
4151 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004152 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004153 }
Steve Antondcc3c022017-12-22 16:02:54 -08004154}
4155
4156void PeerConnection::GetOptionsForAnswer(
4157 const RTCOfferAnswerOptions& offer_answer_options,
4158 cricket::MediaSessionOptions* session_options) {
4159 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4160
4161 if (IsUnifiedPlan()) {
4162 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4163 } else {
4164 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4165 }
4166
Steve Antonfa2260d2017-12-28 16:38:23 -08004167 // Intentionally unset the data channel type for RTP data channel. Otherwise
4168 // the RTP data channels would be successfully negotiated by default and the
4169 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4170 // We want to leave RTP data channels broken, so people won't try to use them.
4171 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4172 session_options->data_channel_type = data_channel_type();
4173 }
4174
Steve Antondcc3c022017-12-22 16:02:54 -08004175 // Apply ICE renomination flag.
4176 for (auto& options : session_options->media_description_options) {
4177 options.transport_options.enable_ice_renomination =
4178 configuration_.enable_ice_renomination;
4179 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004180
4181 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004182 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004183 session_options->pooled_ice_credentials =
4184 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4185 RTC_FROM_HERE,
4186 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4187 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004188}
4189
Steve Antondcc3c022017-12-22 16:02:54 -08004190void PeerConnection::GetOptionsForPlanBAnswer(
4191 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004192 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004193 // Figure out transceiver directional preferences.
4194 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4195 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4196
4197 // By default, generate sendrecv/recvonly m= sections. The direction is also
4198 // restricted by the direction in the offer.
4199 bool recv_audio = true;
4200 bool recv_video = true;
4201
4202 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004203 if (offer_answer_options.offer_to_receive_audio !=
4204 RTCOfferAnswerOptions::kUndefined) {
4205 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004206 }
Steve Antondcc3c022017-12-22 16:02:54 -08004207 if (offer_answer_options.offer_to_receive_video !=
4208 RTCOfferAnswerOptions::kUndefined) {
4209 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004210 }
4211
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004212 absl::optional<size_t> audio_index;
4213 absl::optional<size_t> video_index;
4214 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004215
4216 // Generate m= sections that match those in the offer.
4217 // Note that mediasession.cc will handle intersection our preferred
4218 // direction with the offered direction.
4219 GenerateMediaDescriptionOptions(
4220 remote_description(),
4221 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4222 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4223 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004224
4225 cricket::MediaDescriptionOptions* audio_media_description_options =
4226 !audio_index ? nullptr
4227 : &session_options->media_description_options[*audio_index];
4228 cricket::MediaDescriptionOptions* video_media_description_options =
4229 !video_index ? nullptr
4230 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004231
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004232 AddPlanBRtpSenderOptions(GetSendersInternal(),
4233 audio_media_description_options,
4234 video_media_description_options,
4235 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004236}
zhihuangaf388472016-11-02 16:49:48 -07004237
Steve Antondcc3c022017-12-22 16:02:54 -08004238void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4239 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4240 cricket::MediaSessionOptions* session_options) {
4241 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4242 // Answers) and 5.3.2 (Subsequent Answers).
4243 RTC_DCHECK(remote_description());
4244 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4245 for (const ContentInfo& content :
4246 remote_description()->description()->contents()) {
4247 cricket::MediaType media_type = content.media_description()->type();
4248 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4249 media_type == cricket::MEDIA_TYPE_VIDEO) {
4250 auto transceiver = GetAssociatedTransceiver(content.name);
4251 RTC_CHECK(transceiver);
4252 session_options->media_description_options.push_back(
4253 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4254 } else {
4255 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004256 // Reject all data sections if data channels are disabled.
4257 // Reject a data section if it has already been rejected.
4258 // Reject all data sections except for the first one.
4259 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4260 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004261 session_options->media_description_options.push_back(
4262 GetMediaDescriptionOptionsForRejectedData(content.name));
4263 } else {
4264 session_options->media_description_options.push_back(
4265 GetMediaDescriptionOptionsForActiveData(content.name));
4266 }
Steve Antondcc3c022017-12-22 16:02:54 -08004267 }
4268 }
htaa2a49d92016-03-04 02:51:39 -08004269}
4270
zhihuang1c378ed2017-08-17 14:10:50 -07004271void PeerConnection::GenerateMediaDescriptionOptions(
4272 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004273 RtpTransceiverDirection audio_direction,
4274 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004275 absl::optional<size_t>* audio_index,
4276 absl::optional<size_t>* video_index,
4277 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004278 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004279 for (const cricket::ContentInfo& content :
4280 session_desc->description()->contents()) {
4281 if (IsAudioContent(&content)) {
4282 // If we already have an audio m= section, reject this extra one.
4283 if (*audio_index) {
4284 session_options->media_description_options.push_back(
4285 cricket::MediaDescriptionOptions(
4286 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004287 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004288 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004289 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004290 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004291 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4292 content.name, audio_direction,
4293 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004294 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004295 }
4296 } else if (IsVideoContent(&content)) {
4297 // If we already have an video m= section, reject this extra one.
4298 if (*video_index) {
4299 session_options->media_description_options.push_back(
4300 cricket::MediaDescriptionOptions(
4301 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004302 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004303 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004304 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004305 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004306 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4307 content.name, video_direction,
4308 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004309 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004310 }
4311 } else {
4312 RTC_DCHECK(IsDataContent(&content));
4313 // If we already have an data m= section, reject this extra one.
4314 if (*data_index) {
4315 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004316 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004317 } else {
4318 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004319 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004320 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004321 }
4322 }
htaa2a49d92016-03-04 02:51:39 -08004323 }
deadbeefab9b2d12015-10-14 11:33:11 -07004324}
4325
Steve Antonfa2260d2017-12-28 16:38:23 -08004326cricket::MediaDescriptionOptions
4327PeerConnection::GetMediaDescriptionOptionsForActiveData(
4328 const std::string& mid) const {
4329 // Direction for data sections is meaningless, but legacy endpoints might
4330 // expect sendrecv.
4331 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4332 RtpTransceiverDirection::kSendRecv,
4333 /*stopped=*/false);
4334 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4335 return options;
4336}
4337
4338cricket::MediaDescriptionOptions
4339PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4340 const std::string& mid) const {
4341 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4342 RtpTransceiverDirection::kInactive,
4343 /*stopped=*/true);
4344 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4345 return options;
4346}
4347
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004348absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004349 switch (data_channel_type_) {
4350 case cricket::DCT_RTP:
4351 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004352 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004353 }
4354 return rtp_data_channel_->content_name();
4355 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004356 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004357 case cricket::DCT_MEDIA_TRANSPORT:
4358 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004359 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004360 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004361 }
4362}
4363
Steve Anton4171afb2017-11-20 10:20:22 -08004364void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4365 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4366 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004367 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004368}
4369
Steve Anton4171afb2017-11-20 10:20:22 -08004370void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004371 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004372 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004373 cricket::MediaType media_type,
4374 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004375 RTC_DCHECK(!IsUnifiedPlan());
4376
Steve Anton4171afb2017-11-20 10:20:22 -08004377 std::vector<RtpSenderInfo>* current_senders =
4378 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004379
Steve Anton4171afb2017-11-20 10:20:22 -08004380 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004381 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004382 for (auto sender_it = current_senders->begin();
4383 sender_it != current_senders->end();
4384 /* incremented manually */) {
4385 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004386 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004387 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004388 std::string params_stream_id;
4389 if (params) {
4390 params_stream_id =
4391 (!params->first_stream_id().empty() ? params->first_stream_id()
4392 : kDefaultStreamId);
4393 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004394 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004395 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004396 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004397 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004398 sender_exists) {
4399 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004400 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004401 OnRemoteSenderRemoved(info, media_type);
4402 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004403 }
4404 }
4405
Steve Anton4171afb2017-11-20 10:20:22 -08004406 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004407 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004408 if (!params.has_ssrcs()) {
4409 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4410 // sender, this means it is coming from a Unified Plan endpoint,so we just
4411 // create a default.
4412 default_sender_needed = true;
4413 break;
4414 }
4415
Seth Hampson845e8782018-03-02 11:34:10 -08004416 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004417 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004418 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4419 // not supported in Plan B, we just take the first here and create the
4420 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004421 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004422 (!params.first_stream_id().empty() ? params.first_stream_id()
4423 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004424 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004425 uint32_t ssrc = params.first_ssrc();
4426
4427 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004428 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004429 if (!stream) {
4430 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004431 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004432 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004433 remote_streams_->AddStream(stream);
4434 new_streams->AddStream(stream);
4435 }
4436
Steve Anton4171afb2017-11-20 10:20:22 -08004437 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004438 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004439 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004440 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004441 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004442 }
4443 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004444
Steve Anton4171afb2017-11-20 10:20:22 -08004445 // Add default sender if necessary.
4446 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004447 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004448 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004449 if (!default_stream) {
4450 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004451 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004452 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004453 remote_streams_->AddStream(default_stream);
4454 new_streams->AddStream(default_stream);
4455 }
Steve Anton4171afb2017-11-20 10:20:22 -08004456 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4457 ? kDefaultAudioSenderId
4458 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004459 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004460 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004461 if (!default_sender_info) {
4462 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004463 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004464 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004465 }
4466 }
deadbeefab9b2d12015-10-14 11:33:11 -07004467}
4468
Steve Anton4171afb2017-11-20 10:20:22 -08004469void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4470 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004471 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4472 << " receiver for track_id=" << sender_info.sender_id
4473 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004474
Steve Anton3d954a62018-04-02 11:27:23 -07004475 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004476 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004477 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004478 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004479 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004480 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004481 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004482 }
4483}
4484
Steve Anton4171afb2017-11-20 10:20:22 -08004485void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4486 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004487 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4488 << " receiver for track_id=" << sender_info.sender_id
4489 << " and stream_id=" << sender_info.stream_id;
4490
Seth Hampson845e8782018-03-02 11:34:10 -08004491 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004492
Henrik Boström933d8b02017-10-10 10:05:16 -07004493 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004494 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004495 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4496 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004497 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004498 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004499 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004500 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004501 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004502 }
4503 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004504 // Stopping or destroying a VideoRtpReceiver will end the
4505 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004506 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004507 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004508 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004509 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004510 // There's no guarantee the track is still available, e.g. the track may
4511 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004512 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004513 }
4514 } else {
nisseede5da42017-01-12 05:15:36 -08004515 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004516 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004517 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004518 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004519 }
deadbeefab9b2d12015-10-14 11:33:11 -07004520}
4521
4522void PeerConnection::UpdateEndedRemoteMediaStreams() {
4523 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4524 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4525 MediaStreamInterface* stream = remote_streams_->at(i);
4526 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4527 streams_to_remove.push_back(stream);
4528 }
4529 }
4530
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004531 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004532 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004533 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004534 }
4535}
4536
Steve Anton4171afb2017-11-20 10:20:22 -08004537void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004538 const std::vector<cricket::StreamParams>& streams,
4539 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004540 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004541
Seth Hampson845e8782018-03-02 11:34:10 -08004542 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004543 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004544 for (auto sender_it = current_senders->begin();
4545 sender_it != current_senders->end();
4546 /* incremented manually */) {
4547 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004548 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004549 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4550 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004551 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004552 OnLocalSenderRemoved(info, media_type);
4553 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004554 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004555 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004556 }
4557 }
4558
Steve Anton4171afb2017-11-20 10:20:22 -08004559 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004560 for (const cricket::StreamParams& params : streams) {
4561 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004562 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004563 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004564 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004565 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004566 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004567 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004568 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004569 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004570 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004571 }
4572 }
4573}
4574
Steve Anton4171afb2017-11-20 10:20:22 -08004575void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4576 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004577 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004578 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004579 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004580 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4581 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004582 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004583 return;
4584 }
4585
deadbeeffac06552015-11-25 11:26:01 -08004586 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004587 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004588 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004589 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004590 }
deadbeeffac06552015-11-25 11:26:01 -08004591
Seth Hampson5b4f0752018-04-02 16:31:36 -07004592 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004593 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004594}
4595
Steve Anton4171afb2017-11-20 10:20:22 -08004596void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4597 cricket::MediaType media_type) {
4598 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004599 if (!sender) {
4600 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004601 // SessionDescriptions has been renegotiated.
4602 return;
4603 }
deadbeeffac06552015-11-25 11:26:01 -08004604
4605 // A sender has been removed from the SessionDescription but it's still
4606 // associated with the PeerConnection. This only occurs if the SDP doesn't
4607 // match with the calls to CreateSender, AddStream and RemoveStream.
4608 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004609 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004610 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004611 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004612 }
deadbeeffac06552015-11-25 11:26:01 -08004613
Steve Anton4171afb2017-11-20 10:20:22 -08004614 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004615}
4616
4617void PeerConnection::UpdateLocalRtpDataChannels(
4618 const cricket::StreamParamsVec& streams) {
4619 std::vector<std::string> existing_channels;
4620
4621 // Find new and active data channels.
4622 for (const cricket::StreamParams& params : streams) {
4623 // |it->sync_label| is actually the data channel label. The reason is that
4624 // we use the same naming of data channels as we do for
4625 // MediaStreams and Tracks.
4626 // For MediaStreams, the sync_label is the MediaStream label and the
4627 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004628 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004629 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004630 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004631 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004632 continue;
4633 }
4634 // Set the SSRC the data channel should use for sending.
4635 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4636 existing_channels.push_back(data_channel_it->first);
4637 }
4638
4639 UpdateClosingRtpDataChannels(existing_channels, true);
4640}
4641
4642void PeerConnection::UpdateRemoteRtpDataChannels(
4643 const cricket::StreamParamsVec& streams) {
4644 std::vector<std::string> existing_channels;
4645
4646 // Find new and active data channels.
4647 for (const cricket::StreamParams& params : streams) {
4648 // The data channel label is either the mslabel or the SSRC if the mslabel
4649 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004650 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004651 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004652 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004653 auto data_channel_it = rtp_data_channels_.find(label);
4654 if (data_channel_it == rtp_data_channels_.end()) {
4655 // This is a new data channel.
4656 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4657 } else {
4658 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4659 }
4660 existing_channels.push_back(label);
4661 }
4662
4663 UpdateClosingRtpDataChannels(existing_channels, false);
4664}
4665
4666void PeerConnection::UpdateClosingRtpDataChannels(
4667 const std::vector<std::string>& active_channels,
4668 bool is_local_update) {
4669 auto it = rtp_data_channels_.begin();
4670 while (it != rtp_data_channels_.end()) {
4671 DataChannel* data_channel = it->second;
4672 if (std::find(active_channels.begin(), active_channels.end(),
4673 data_channel->label()) != active_channels.end()) {
4674 ++it;
4675 continue;
4676 }
4677
4678 if (is_local_update) {
4679 data_channel->SetSendSsrc(0);
4680 } else {
4681 data_channel->RemotePeerRequestClose();
4682 }
4683
4684 if (data_channel->state() == DataChannel::kClosed) {
4685 rtp_data_channels_.erase(it);
4686 it = rtp_data_channels_.begin();
4687 } else {
4688 ++it;
4689 }
4690 }
4691}
4692
4693void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4694 uint32_t remote_ssrc) {
4695 rtc::scoped_refptr<DataChannel> channel(
4696 InternalCreateDataChannel(label, nullptr));
4697 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004698 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004699 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004700 return;
4701 }
4702 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004703 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4704 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004705 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004706}
4707
4708rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4709 const std::string& label,
4710 const InternalDataChannelInit* config) {
4711 if (IsClosed()) {
4712 return nullptr;
4713 }
Steve Anton75737c02017-11-06 10:37:17 -08004714 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004715 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004716 << "InternalCreateDataChannel: Data is not supported in this call.";
4717 return nullptr;
4718 }
4719 InternalDataChannelInit new_config =
4720 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004721 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004722 if (new_config.id < 0) {
4723 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004724 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004725 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004726 RTC_LOG(LS_ERROR)
4727 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004728 return nullptr;
4729 }
4730 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004731 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004732 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004733 return nullptr;
4734 }
4735 }
4736
Steve Anton75737c02017-11-06 10:37:17 -08004737 rtc::scoped_refptr<DataChannel> channel(
4738 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004739 if (!channel) {
4740 sid_allocator_.ReleaseSid(new_config.id);
4741 return nullptr;
4742 }
4743
4744 if (channel->data_channel_type() == cricket::DCT_RTP) {
4745 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004746 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4747 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004748 return nullptr;
4749 }
4750 rtp_data_channels_[channel->label()] = channel;
4751 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004752 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004753 sctp_data_channels_.push_back(channel);
4754 channel->SignalClosed.connect(this,
4755 &PeerConnection::OnSctpDataChannelClosed);
4756 }
4757
Steve Anton2d8609c2018-01-23 16:38:46 -08004758 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004759 return channel;
4760}
4761
4762bool PeerConnection::HasDataChannels() const {
4763 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4764}
4765
4766void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4767 for (const auto& channel : sctp_data_channels_) {
4768 if (channel->id() < 0) {
4769 int sid;
4770 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004771 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004772 continue;
4773 }
4774 channel->SetSctpSid(sid);
4775 }
4776 }
4777}
4778
4779void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004780 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004781 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4782 ++it) {
4783 if (it->get() == channel) {
4784 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004785 // After the closing procedure is done, it's safe to use this ID for
4786 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004787 sid_allocator_.ReleaseSid(channel->id());
4788 }
deadbeefbd292462015-12-14 18:15:29 -08004789 // Since this method is triggered by a signal from the DataChannel,
4790 // we can't free it directly here; we need to free it asynchronously.
4791 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004792 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004793 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4794 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004795 return;
4796 }
4797 }
4798}
4799
deadbeefab9b2d12015-10-14 11:33:11 -07004800void PeerConnection::OnDataChannelDestroyed() {
4801 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4802 // DataChannel may callback to us and try to modify the list.
4803 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4804 temp_rtp_dcs.swap(rtp_data_channels_);
4805 for (const auto& kv : temp_rtp_dcs) {
4806 kv.second->OnTransportChannelDestroyed();
4807 }
4808
4809 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4810 temp_sctp_dcs.swap(sctp_data_channels_);
4811 for (const auto& channel : temp_sctp_dcs) {
4812 channel->OnTransportChannelDestroyed();
4813 }
4814}
4815
4816void PeerConnection::OnDataChannelOpenMessage(
4817 const std::string& label,
4818 const InternalDataChannelInit& config) {
4819 rtc::scoped_refptr<DataChannel> channel(
4820 InternalCreateDataChannel(label, &config));
4821 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004822 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004823 return;
4824 }
4825
deadbeefa601f5c2016-06-06 14:27:39 -07004826 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4827 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004828 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004829 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004830}
4831
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004832bool PeerConnection::HandleOpenMessage_s(
4833 const cricket::ReceiveDataParams& params,
4834 const rtc::CopyOnWriteBuffer& buffer) {
4835 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4836 // Received OPEN message; parse and signal that a new data channel should
4837 // be created.
4838 std::string label;
4839 InternalDataChannelInit config;
4840 config.id = params.ssrc;
4841 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4842 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4843 << params.ssrc;
4844 return true;
4845 }
4846 config.open_handshake_role = InternalDataChannelInit::kAcker;
4847 OnDataChannelOpenMessage(label, config);
4848 return true;
4849 }
4850 return false;
4851}
4852
Steve Anton4171afb2017-11-20 10:20:22 -08004853rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4854PeerConnection::GetAudioTransceiver() const {
4855 // This method only works with Plan B SDP, where there is a single
4856 // audio/video transceiver.
4857 RTC_DCHECK(!IsUnifiedPlan());
4858 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004859 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004860 return transceiver;
4861 }
4862 }
4863 RTC_NOTREACHED();
4864 return nullptr;
4865}
4866
4867rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4868PeerConnection::GetVideoTransceiver() const {
4869 // This method only works with Plan B SDP, where there is a single
4870 // audio/video transceiver.
4871 RTC_DCHECK(!IsUnifiedPlan());
4872 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004873 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004874 return transceiver;
4875 }
4876 }
4877 RTC_NOTREACHED();
4878 return nullptr;
4879}
4880
4881// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4882// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004883bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004884 switch (type) {
4885 case cricket::MEDIA_TYPE_AUDIO:
4886 return !GetAudioTransceiver()->internal()->senders().empty();
4887 case cricket::MEDIA_TYPE_VIDEO:
4888 return !GetVideoTransceiver()->internal()->senders().empty();
4889 case cricket::MEDIA_TYPE_DATA:
4890 return false;
4891 }
4892 RTC_NOTREACHED();
4893 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004894}
4895
Steve Anton4171afb2017-11-20 10:20:22 -08004896rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4897PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4898 for (auto transceiver : transceivers_) {
4899 for (auto sender : transceiver->internal()->senders()) {
4900 if (sender->track() == track) {
4901 return sender;
4902 }
4903 }
4904 }
4905 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004906}
4907
Steve Anton4171afb2017-11-20 10:20:22 -08004908rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4909PeerConnection::FindSenderById(const std::string& sender_id) const {
4910 for (auto transceiver : transceivers_) {
4911 for (auto sender : transceiver->internal()->senders()) {
4912 if (sender->id() == sender_id) {
4913 return sender;
4914 }
4915 }
4916 }
4917 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004918}
4919
Steve Anton4171afb2017-11-20 10:20:22 -08004920rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4921PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4922 for (auto transceiver : transceivers_) {
4923 for (auto receiver : transceiver->internal()->receivers()) {
4924 if (receiver->id() == receiver_id) {
4925 return receiver;
4926 }
4927 }
4928 }
4929 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004930}
4931
Steve Anton4171afb2017-11-20 10:20:22 -08004932std::vector<PeerConnection::RtpSenderInfo>*
4933PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4934 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4935 media_type == cricket::MEDIA_TYPE_VIDEO);
4936 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4937 ? &remote_audio_sender_infos_
4938 : &remote_video_sender_infos_;
4939}
4940
4941std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004942 cricket::MediaType media_type) {
4943 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4944 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004945 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4946 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004947}
4948
Steve Anton4171afb2017-11-20 10:20:22 -08004949const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4950 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004951 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004952 const std::string sender_id) const {
4953 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004954 if (sender_info.stream_id == stream_id &&
4955 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004956 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004957 }
4958 }
4959 return nullptr;
4960}
4961
4962DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4963 for (const auto& channel : sctp_data_channels_) {
4964 if (channel->id() == sid) {
4965 return channel;
4966 }
4967 }
4968 return nullptr;
4969}
4970
deadbeef91dd5672016-05-18 16:55:30 -07004971bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004972 const cricket::ServerAddresses& stun_servers,
4973 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004974 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004975 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004976 // To handle both internal and externally created port allocator, we will
4977 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004978 port_allocator_flags_ = port_allocator_->flags();
4979 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4980 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4981 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004982 // If the disable-IPv6 flag was specified, we'll not override it
4983 // by experiment.
4984 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004985 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004986 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4987 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004988 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004989 }
4990
zhihuangb09b3f92017-03-07 14:40:51 -08004991 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004992 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004993 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004994 }
4995
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004996 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004997 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004998 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004999 }
5000
honghaiz60347052016-05-31 18:29:12 -07005001 if (configuration.candidate_network_policy ==
5002 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005003 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005004 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005005 }
5006
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005007 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005008 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005009 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5010 }
5011
Qingsi Wanga2d60672018-04-11 16:57:45 -07005012 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005013 // No step delay is used while allocating ports.
5014 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5015 port_allocator_->set_candidate_filter(
5016 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005017 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005018
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005019 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005020 for (auto& turn_server : turn_servers_copy) {
5021 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005022 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005023 // Call this last since it may create pooled allocator sessions using the
5024 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005025 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005026 stun_servers, std::move(turn_servers_copy),
5027 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5028 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005029 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005030 return true;
5031}
5032
deadbeef91dd5672016-05-18 16:55:30 -07005033bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005034 const cricket::ServerAddresses& stun_servers,
5035 const std::vector<cricket::RelayServerConfig>& turn_servers,
5036 IceTransportsType type,
5037 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005038 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005039 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005040 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005041 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005042 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005043 // According to JSEP, after setLocalDescription, changing the candidate pool
5044 // size is not allowed, and changing the set of ICE servers will not result
5045 // in new candidates being gathered.
5046 if (local_description()) {
5047 port_allocator_->FreezeCandidatePool();
5048 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005049 // Add the custom tls turn servers if they exist.
5050 auto turn_servers_copy = turn_servers;
5051 for (auto& turn_server : turn_servers_copy) {
5052 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5053 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005054 // Call this last since it may create pooled allocator sessions using the
5055 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005056 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005057 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5058 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005059}
5060
Steve Antonba818672017-11-06 10:21:57 -08005061cricket::ChannelManager* PeerConnection::channel_manager() const {
5062 return factory_->channel_manager();
5063}
5064
Elad Alon99c3fe52017-10-13 16:29:40 +02005065bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005066 std::unique_ptr<RtcEventLogOutput> output,
5067 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005068 if (!event_log_) {
5069 return false;
5070 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005071 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005072}
5073
5074void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005075 if (event_log_) {
5076 event_log_->StopLogging();
5077 }
ivoc14d5dbe2016-07-04 07:06:55 -07005078}
nisseeaabdf62017-05-05 02:23:02 -07005079
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005080cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005081 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005082 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005083 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005084 if (channel && channel->content_name() == content_name) {
5085 return channel;
5086 }
Steve Anton75737c02017-11-06 10:37:17 -08005087 }
5088 if (rtp_data_channel() &&
5089 rtp_data_channel()->content_name() == content_name) {
5090 return rtp_data_channel();
5091 }
5092 return nullptr;
5093}
5094
5095bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005096 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005097 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005098 RTC_LOG(LS_INFO)
5099 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005100 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005101 return false;
5102 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005103 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005104 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005105 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005106 return false;
5107 }
5108
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005109 absl::optional<rtc::SSLRole> dtls_role;
5110 if (sctp_mid_) {
5111 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5112 } else if (is_caller_) {
5113 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5114 }
Zhi Huange830e682018-03-30 10:48:35 -07005115 if (dtls_role) {
5116 *role = *dtls_role;
5117 return true;
5118 }
5119 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005120}
5121
5122bool PeerConnection::GetSslRole(const std::string& content_name,
5123 rtc::SSLRole* role) {
5124 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005125 RTC_LOG(LS_INFO)
5126 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005127 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005128 return false;
5129 }
5130
Zhi Huange830e682018-03-30 10:48:35 -07005131 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5132 if (dtls_role) {
5133 *role = *dtls_role;
5134 return true;
5135 }
5136 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005137}
5138
Steve Antonf8470812017-12-04 10:46:21 -08005139void PeerConnection::SetSessionError(SessionError error,
5140 const std::string& error_desc) {
5141 RTC_DCHECK_RUN_ON(signaling_thread());
5142 if (error != session_error_) {
5143 session_error_ = error;
5144 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005145 }
5146}
5147
Zhi Huange830e682018-03-30 10:48:35 -07005148RTCError PeerConnection::UpdateSessionState(
5149 SdpType type,
5150 cricket::ContentSource source,
5151 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005152 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005153
5154 // If there's already a pending error then no state transition should happen.
5155 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005156 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005157
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005158 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005159 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005160 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005161 }
5162
5163 // Update the signaling state according to the specified state machine (see
5164 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005165 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005166 ChangeSignalingState(source == cricket::CS_LOCAL
5167 ? PeerConnectionInterface::kHaveLocalOffer
5168 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005169 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005170 ChangeSignalingState(source == cricket::CS_LOCAL
5171 ? PeerConnectionInterface::kHaveLocalPrAnswer
5172 : PeerConnectionInterface::kHaveRemotePrAnswer);
5173 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005174 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005175 ChangeSignalingState(PeerConnectionInterface::kStable);
5176 }
5177
5178 // Update internal objects according to the session description's media
5179 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005180 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005181 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005182 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005183 }
5184
Steve Anton8a006912017-12-04 15:25:56 -08005185 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005186}
5187
Steve Anton8a006912017-12-04 15:25:56 -08005188RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005189 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005190 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005191 const SessionDescriptionInterface* sdesc =
5192 (source == cricket::CS_LOCAL ? local_description()
5193 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005194 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005195
5196 // Push down the new SDP media section for each audio/video transceiver.
5197 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005198 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005199 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005200 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005201 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005202 continue;
5203 }
5204 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005205 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005206 if (!content_desc) {
5207 continue;
5208 }
5209 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005210 bool success = (source == cricket::CS_LOCAL)
5211 ? channel->SetLocalContent(content_desc, type, &error)
5212 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005213 if (!success) {
5214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5215 }
5216 }
5217
5218 // If using the RtpDataChannel, push down the new SDP section for it too.
5219 if (rtp_data_channel_) {
5220 const ContentInfo* data_content =
5221 cricket::GetFirstDataContent(sdesc->description());
5222 if (data_content && !data_content->rejected) {
5223 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005224 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005225 if (data_desc) {
5226 std::string error;
5227 bool success =
5228 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005229 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005230 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005231 if (!success) {
5232 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5233 std::move(error));
5234 }
Steve Anton75737c02017-11-06 10:37:17 -08005235 }
5236 }
5237 }
Steve Antoned10bd92017-12-05 10:52:59 -08005238
Steve Anton75737c02017-11-06 10:37:17 -08005239 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5240 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5241 if (sctp_transport_ && local_description() && remote_description() &&
5242 cricket::GetFirstDataContent(local_description()->description()) &&
5243 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005244 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005245 RTC_FROM_HERE,
5246 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005247 if (!success) {
5248 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5249 "Failed to push down SCTP parameters.");
5250 }
Steve Anton75737c02017-11-06 10:37:17 -08005251 }
Steve Antoned10bd92017-12-05 10:52:59 -08005252
Steve Anton8a006912017-12-04 15:25:56 -08005253 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005254}
5255
5256bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5257 RTC_DCHECK(network_thread()->IsCurrent());
5258 RTC_DCHECK(local_description());
5259 RTC_DCHECK(remote_description());
5260 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5261 // When we support "max-message-size", that would also be pushed down here.
5262 return sctp_transport_->Start(
5263 GetSctpPort(local_description()->description()),
5264 GetSctpPort(remote_description()->description()));
5265}
5266
Steve Anton8a006912017-12-04 15:25:56 -08005267RTCError PeerConnection::PushdownTransportDescription(
5268 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005269 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005270 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005271
Zhi Huange830e682018-03-30 10:48:35 -07005272 if (source == cricket::CS_LOCAL) {
5273 const SessionDescriptionInterface* sdesc = local_description();
5274 RTC_DCHECK(sdesc);
5275 return transport_controller_->SetLocalDescription(type,
5276 sdesc->description());
5277 } else {
5278 const SessionDescriptionInterface* sdesc = remote_description();
5279 RTC_DCHECK(sdesc);
5280 return transport_controller_->SetRemoteDescription(type,
5281 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005282 }
Steve Anton75737c02017-11-06 10:37:17 -08005283}
5284
5285bool PeerConnection::GetTransportDescription(
5286 const SessionDescription* description,
5287 const std::string& content_name,
5288 cricket::TransportDescription* tdesc) {
5289 if (!description || !tdesc) {
5290 return false;
5291 }
5292 const TransportInfo* transport_info =
5293 description->GetTransportInfoByName(content_name);
5294 if (!transport_info) {
5295 return false;
5296 }
5297 *tdesc = transport_info->description;
5298 return true;
5299}
5300
Steve Anton75737c02017-11-06 10:37:17 -08005301cricket::IceConfig PeerConnection::ParseIceConfig(
5302 const PeerConnectionInterface::RTCConfiguration& config) const {
5303 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005304 switch (config.continual_gathering_policy) {
5305 case PeerConnectionInterface::GATHER_ONCE:
5306 gathering_policy = cricket::GATHER_ONCE;
5307 break;
5308 case PeerConnectionInterface::GATHER_CONTINUALLY:
5309 gathering_policy = cricket::GATHER_CONTINUALLY;
5310 break;
5311 default:
5312 RTC_NOTREACHED();
5313 gathering_policy = cricket::GATHER_ONCE;
5314 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005315
Steve Anton75737c02017-11-06 10:37:17 -08005316 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005317 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5318 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005319 ice_config.prioritize_most_likely_candidate_pairs =
5320 config.prioritize_most_likely_ice_candidate_pairs;
5321 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005322 RTCConfigurationToIceConfigOptionalInt(
5323 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005324 ice_config.continual_gathering_policy = gathering_policy;
5325 ice_config.presume_writable_when_fully_relayed =
5326 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005327 ice_config.ice_check_interval_strong_connectivity =
5328 config.ice_check_interval_strong_connectivity;
5329 ice_config.ice_check_interval_weak_connectivity =
5330 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005331 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005332 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5333 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005334 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005335 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005336 ice_config.regather_all_networks_interval_range =
5337 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005338 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005339 return ice_config;
5340}
5341
Steve Antona41959e2018-11-28 11:15:33 -08005342static absl::string_view GetTrackIdBySsrc(
5343 const SessionDescriptionInterface* session_description,
5344 uint32_t ssrc) {
5345 if (!session_description) {
5346 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005347 }
Steve Antona41959e2018-11-28 11:15:33 -08005348 for (const cricket::ContentInfo& content :
5349 session_description->description()->contents()) {
5350 const cricket::MediaContentDescription& media =
5351 *content.media_description();
5352 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5353 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5354 const cricket::StreamParams* stream_params =
5355 cricket::GetStreamBySsrc(media.streams(), ssrc);
5356 if (stream_params) {
5357 return stream_params->id;
5358 }
5359 }
5360 }
5361 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005362}
5363
Steve Antona41959e2018-11-28 11:15:33 -08005364absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5365 return GetTrackIdBySsrc(local_description(), ssrc);
5366}
5367
5368absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5369 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005370}
5371
5372bool PeerConnection::SendData(const cricket::SendDataParams& params,
5373 const rtc::CopyOnWriteBuffer& payload,
5374 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005375 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5376 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5377 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005378 return false;
5379 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005380 if (media_transport_) {
5381 SendDataParams send_params;
5382 send_params.type = ToWebrtcDataMessageType(params.type);
5383 send_params.ordered = params.ordered;
5384 if (params.max_rtx_count >= 0) {
5385 send_params.max_rtx_count = params.max_rtx_count;
5386 } else if (params.max_rtx_ms >= 0) {
5387 send_params.max_rtx_ms = params.max_rtx_ms;
5388 }
5389 return media_transport_->SendData(params.sid, send_params, payload).ok();
5390 }
Steve Anton75737c02017-11-06 10:37:17 -08005391 return rtp_data_channel_
5392 ? rtp_data_channel_->SendData(params, payload, result)
5393 : network_thread()->Invoke<bool>(
5394 RTC_FROM_HERE,
5395 Bind(&cricket::SctpTransportInternal::SendData,
5396 sctp_transport_.get(), params, payload, result));
5397}
5398
5399bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005400 RTC_DCHECK_RUN_ON(signaling_thread());
5401 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005402 // Don't log an error here, because DataChannels are expected to call
5403 // ConnectDataChannel in this state. It's the only way to initially tell
5404 // whether or not the underlying transport is ready.
5405 return false;
5406 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005407 if (media_transport_) {
5408 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5409 &DataChannel::OnChannelReady);
5410 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5411 &DataChannel::OnDataReceived);
5412 SignalMediaTransportChannelClosing_s.connect(
5413 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5414 SignalMediaTransportChannelClosed_s.connect(
5415 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5416 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005417 rtp_data_channel_->SignalReadyToSendData.connect(
5418 webrtc_data_channel, &DataChannel::OnChannelReady);
5419 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5420 &DataChannel::OnDataReceived);
5421 } else {
5422 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5423 &DataChannel::OnChannelReady);
5424 SignalSctpDataReceived.connect(webrtc_data_channel,
5425 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005426 SignalSctpClosingProcedureStartedRemotely.connect(
5427 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5428 SignalSctpClosingProcedureComplete.connect(
5429 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005430 }
5431 return true;
5432}
5433
5434void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005435 RTC_DCHECK_RUN_ON(signaling_thread());
5436 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005437 RTC_LOG(LS_ERROR)
5438 << "DisconnectDataChannel called when rtp_data_channel_ and "
5439 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005440 return;
5441 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005442 if (media_transport_) {
5443 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5444 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5445 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5446 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5447 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005448 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5449 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5450 } else {
5451 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5452 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005453 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5454 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005455 }
5456}
5457
5458void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005459 if (media_transport_) {
5460 // No-op. Media transport does not need to add streams.
5461 return;
5462 }
Steve Anton75737c02017-11-06 10:37:17 -08005463 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005464 RTC_LOG(LS_ERROR)
5465 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005466 return;
5467 }
5468 network_thread()->Invoke<void>(
5469 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5470 sctp_transport_.get(), sid));
5471}
5472
5473void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005474 if (media_transport_) {
5475 media_transport_->CloseChannel(sid);
5476 return;
5477 }
Steve Anton75737c02017-11-06 10:37:17 -08005478 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005479 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005480 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005481 return;
5482 }
5483 network_thread()->Invoke<void>(
5484 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5485 sctp_transport_.get(), sid));
5486}
5487
5488bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005489 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005490 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005491 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005492 sctp_ready_to_send_data_;
5493}
5494
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005495void PeerConnection::OnDataReceived(int channel_id,
5496 DataMessageType type,
5497 const rtc::CopyOnWriteBuffer& buffer) {
5498 cricket::ReceiveDataParams params;
5499 params.sid = channel_id;
5500 params.type = ToCricketDataMessageType(type);
5501 media_transport_invoker_->AsyncInvoke<void>(
5502 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5503 RTC_DCHECK_RUN_ON(signaling_thread());
5504 if (!HandleOpenMessage_s(params, buffer)) {
5505 SignalMediaTransportReceivedData_s(params, buffer);
5506 }
5507 });
5508}
5509
5510void PeerConnection::OnChannelClosing(int channel_id) {
5511 media_transport_invoker_->AsyncInvoke<void>(
5512 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5513 RTC_DCHECK_RUN_ON(signaling_thread());
5514 SignalMediaTransportChannelClosing_s(channel_id);
5515 });
5516}
5517
5518void PeerConnection::OnChannelClosed(int channel_id) {
5519 media_transport_invoker_->AsyncInvoke<void>(
5520 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5521 RTC_DCHECK_RUN_ON(signaling_thread());
5522 SignalMediaTransportChannelClosed_s(channel_id);
5523 });
5524}
5525
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005526absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005527 if (sctp_mid_ && transport_controller_) {
5528 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5529 if (dtls_transport) {
5530 return dtls_transport->transport_name();
5531 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005532 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005533 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005534 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005535}
5536
Qingsi Wang72a43a12018-02-20 16:03:18 -08005537cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5538 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005539 network_thread()->Invoke<void>(
5540 RTC_FROM_HERE,
5541 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5542 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005543 return candidate_states_list;
5544}
5545
Steve Anton5dfde182018-02-06 10:34:40 -08005546std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5547 const {
5548 std::map<std::string, std::string> transport_names_by_mid;
5549 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005550 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005551 if (channel) {
5552 transport_names_by_mid[channel->content_name()] =
5553 channel->transport_name();
5554 }
Steve Anton75737c02017-11-06 10:37:17 -08005555 }
Steve Anton5dfde182018-02-06 10:34:40 -08005556 if (rtp_data_channel_) {
5557 transport_names_by_mid[rtp_data_channel_->content_name()] =
5558 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005559 }
5560 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005561 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005562 RTC_DCHECK(transport_name);
5563 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005564 }
Steve Anton5dfde182018-02-06 10:34:40 -08005565 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005566}
5567
Steve Anton5dfde182018-02-06 10:34:40 -08005568std::map<std::string, cricket::TransportStats>
5569PeerConnection::GetTransportStatsByNames(
5570 const std::set<std::string>& transport_names) {
5571 if (!network_thread()->IsCurrent()) {
5572 return network_thread()
5573 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5574 RTC_FROM_HERE,
5575 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005576 }
Steve Anton5dfde182018-02-06 10:34:40 -08005577 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5578 for (const std::string& transport_name : transport_names) {
5579 cricket::TransportStats transport_stats;
5580 bool success =
5581 transport_controller_->GetStats(transport_name, &transport_stats);
5582 if (success) {
5583 transport_stats_by_name[transport_name] = std::move(transport_stats);
5584 } else {
5585 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5586 << transport_name;
5587 }
5588 }
5589 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005590}
5591
5592bool PeerConnection::GetLocalCertificate(
5593 const std::string& transport_name,
5594 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005595 if (!certificate) {
5596 return false;
5597 }
5598 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5599 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005600}
5601
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005602std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005603 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005604 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005605}
5606
5607cricket::DataChannelType PeerConnection::data_channel_type() const {
5608 return data_channel_type_;
5609}
5610
5611bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5612 return pending_ice_restarts_.find(content_name) !=
5613 pending_ice_restarts_.end();
5614}
5615
Steve Anton75737c02017-11-06 10:37:17 -08005616bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5617 return transport_controller_->NeedsIceRestart(content_name);
5618}
5619
5620void PeerConnection::OnCertificateReady(
5621 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5622 transport_controller_->SetLocalCertificate(certificate);
5623}
5624
5625void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005626 SetSessionError(SessionError::kTransport,
5627 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005628}
5629
Alex Loiko9289eda2018-11-23 16:18:59 +00005630void PeerConnection::OnTransportControllerConnectionState(
5631 cricket::IceConnectionState state) {
5632 switch (state) {
5633 case cricket::kIceConnectionConnecting:
5634 // If the current state is Connected or Completed, then there were
5635 // writable channels but now there are not, so the next state must
5636 // be Disconnected.
5637 // kIceConnectionConnecting is currently used as the default,
5638 // un-connected state by the TransportController, so its only use is
5639 // detecting disconnections.
5640 if (ice_connection_state_ ==
5641 PeerConnectionInterface::kIceConnectionConnected ||
5642 ice_connection_state_ ==
5643 PeerConnectionInterface::kIceConnectionCompleted) {
5644 SetIceConnectionState(
5645 PeerConnectionInterface::kIceConnectionDisconnected);
5646 }
5647 break;
5648 case cricket::kIceConnectionFailed:
5649 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5650 break;
5651 case cricket::kIceConnectionConnected:
5652 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5653 "all transports are writable.";
5654 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5655 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5656 break;
5657 case cricket::kIceConnectionCompleted:
5658 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5659 "all transports are complete.";
5660 if (ice_connection_state_ !=
5661 PeerConnectionInterface::kIceConnectionConnected) {
5662 // If jumping directly from "checking" to "connected",
5663 // signal "connected" first.
5664 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5665 }
5666 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5667 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5668 ReportTransportStats();
5669 break;
5670 default:
5671 RTC_NOTREACHED();
5672 }
5673}
5674
Steve Anton75737c02017-11-06 10:37:17 -08005675void PeerConnection::OnTransportControllerCandidatesGathered(
5676 const std::string& transport_name,
5677 const cricket::Candidates& candidates) {
5678 RTC_DCHECK(signaling_thread()->IsCurrent());
5679 int sdp_mline_index;
5680 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005681 RTC_LOG(LS_ERROR)
5682 << "OnTransportControllerCandidatesGathered: content name "
5683 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005684 return;
5685 }
5686
5687 for (cricket::Candidates::const_iterator citer = candidates.begin();
5688 citer != candidates.end(); ++citer) {
5689 // Use transport_name as the candidate media id.
5690 std::unique_ptr<JsepIceCandidate> candidate(
5691 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5692 if (local_description()) {
5693 mutable_local_description()->AddCandidate(candidate.get());
5694 }
5695 OnIceCandidate(std::move(candidate));
5696 }
5697}
5698
5699void PeerConnection::OnTransportControllerCandidatesRemoved(
5700 const std::vector<cricket::Candidate>& candidates) {
5701 RTC_DCHECK(signaling_thread()->IsCurrent());
5702 // Sanity check.
5703 for (const cricket::Candidate& candidate : candidates) {
5704 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005705 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005706 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005707 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005708 return;
5709 }
5710 }
5711
5712 if (local_description()) {
5713 mutable_local_description()->RemoveCandidates(candidates);
5714 }
5715 OnIceCandidatesRemoved(candidates);
5716}
5717
5718void PeerConnection::OnTransportControllerDtlsHandshakeError(
5719 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005720 RTC_HISTOGRAM_ENUMERATION(
5721 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5722 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005723}
5724
Steve Antoned10bd92017-12-05 10:52:59 -08005725void PeerConnection::EnableSending() {
5726 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005727 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005728 if (channel && !channel->enabled()) {
5729 channel->Enable(true);
5730 }
Steve Anton75737c02017-11-06 10:37:17 -08005731 }
5732
Steve Anton4171afb2017-11-20 10:20:22 -08005733 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005734 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005735 }
Steve Anton75737c02017-11-06 10:37:17 -08005736}
5737
5738// Returns the media index for a local ice candidate given the content name.
5739bool PeerConnection::GetLocalCandidateMediaIndex(
5740 const std::string& content_name,
5741 int* sdp_mline_index) {
5742 if (!local_description() || !sdp_mline_index) {
5743 return false;
5744 }
5745
5746 bool content_found = false;
5747 const ContentInfos& contents = local_description()->description()->contents();
5748 for (size_t index = 0; index < contents.size(); ++index) {
5749 if (contents[index].name == content_name) {
5750 *sdp_mline_index = static_cast<int>(index);
5751 content_found = true;
5752 break;
5753 }
5754 }
5755 return content_found;
5756}
5757
5758bool PeerConnection::UseCandidatesInSessionDescription(
5759 const SessionDescriptionInterface* remote_desc) {
5760 if (!remote_desc) {
5761 return true;
5762 }
5763 bool ret = true;
5764
5765 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5766 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5767 for (size_t n = 0; n < candidates->count(); ++n) {
5768 const IceCandidateInterface* candidate = candidates->at(n);
5769 bool valid = false;
5770 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5771 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005772 RTC_LOG(LS_INFO)
5773 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005774 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
5776 continue;
5777 }
5778 ret = UseCandidate(candidate);
5779 if (!ret) {
5780 break;
5781 }
5782 }
5783 }
5784 return ret;
5785}
5786
5787bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5788 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5789 size_t remote_content_size =
5790 remote_description()->description()->contents().size();
5791 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005792 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005793 return false;
5794 }
5795
5796 cricket::ContentInfo content =
5797 remote_description()->description()->contents()[mediacontent_index];
5798 std::vector<cricket::Candidate> candidates;
5799 candidates.push_back(candidate->candidate());
5800 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005801 RTCError error =
5802 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005803 if (error.ok()) {
5804 // Candidates successfully submitted for checking.
5805 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5806 ice_connection_state_ ==
5807 PeerConnectionInterface::kIceConnectionDisconnected) {
5808 // If state is New, then the session has just gotten its first remote ICE
5809 // candidates, so go to Checking.
5810 // If state is Disconnected, the session is re-using old candidates or
5811 // receiving additional ones, so go to Checking.
5812 // If state is Connected, stay Connected.
5813 // TODO(bemasc): If state is Connected, and the new candidates are for a
5814 // newly added transport, then the state actually _should_ move to
5815 // checking. Add a way to distinguish that case.
5816 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5817 }
5818 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005819 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005820 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005821 }
5822 return true;
5823}
5824
5825void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005826 // Destroy video channel first since it may have a pointer to the
5827 // voice channel.
5828 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005829 if (!video_info || video_info->rejected) {
5830 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005831 }
5832
Steve Anton6fec8802017-12-04 10:37:29 -08005833 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5834 if (!audio_info || audio_info->rejected) {
5835 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005836 }
5837
5838 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5839 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005840 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005841 }
5842}
5843
Steve Antondcc3c022017-12-22 16:02:54 -08005844RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5845 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005846 const cricket::ContentGroup* bundle_group = nullptr;
5847 if (configuration_.bundle_policy ==
5848 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005849 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005850 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005851 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5852 "max-bundle configured but session description "
5853 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005854 }
5855 }
Steve Antondcc3c022017-12-22 16:02:54 -08005856 return std::move(bundle_group);
5857}
5858
5859RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005860 // Creating the media channels. Transports should already have been created
5861 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005862 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005863 if (voice && !voice->rejected &&
5864 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005865 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005866 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005867 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5868 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005869 }
5870 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5871 }
5872
Steve Antondcc3c022017-12-22 16:02:54 -08005873 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005874 if (video && !video->rejected &&
5875 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005876 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005877 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005878 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5879 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005880 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005881 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005882 }
5883
Steve Antondcc3c022017-12-22 16:02:54 -08005884 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005885 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005886 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005887 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005888 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5889 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005890 }
5891 }
5892
Steve Anton8a006912017-12-04 15:25:56 -08005893 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005894}
5895
Steve Anton4171afb2017-11-20 10:20:22 -08005896// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005897cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005898 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005899 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005900 MediaTransportInterface* media_transport = nullptr;
5901 if (configuration_.use_media_transport) {
5902 media_transport = GetMediaTransport(mid);
5903 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005904
Steve Anton75737c02017-11-06 10:37:17 -08005905 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005906 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005907 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5908 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005909 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005910 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005911 }
Steve Anton75737c02017-11-06 10:37:17 -08005912 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5913 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005914 voice_channel->SignalSentPacket.connect(this,
5915 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005916 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005917
Steve Antoneda6ccd2017-12-04 10:21:55 -08005918 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005919}
5920
Steve Anton4171afb2017-11-20 10:20:22 -08005921// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005922cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005923 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005924 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01005925 MediaTransportInterface* media_transport = nullptr;
5926 if (configuration_.use_media_transport) {
5927 media_transport = GetMediaTransport(mid);
5928 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005929
Steve Anton75737c02017-11-06 10:37:17 -08005930 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01005931 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005932 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5933 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005934 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005935 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005936 }
Steve Anton75737c02017-11-06 10:37:17 -08005937 video_channel->SignalDtlsSrtpSetupFailure.connect(
5938 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005939 video_channel->SignalSentPacket.connect(this,
5940 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005941 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005942
Steve Antoneda6ccd2017-12-04 10:21:55 -08005943 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005944}
5945
Zhi Huange830e682018-03-30 10:48:35 -07005946bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005947 switch (data_channel_type_) {
5948 case cricket::DCT_MEDIA_TRANSPORT:
5949 if (network_thread()->Invoke<bool>(
5950 RTC_FROM_HERE,
5951 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5952 this, mid))) {
5953 for (const auto& channel : sctp_data_channels_) {
5954 channel->OnTransportChannelCreated();
5955 }
5956 return true;
5957 }
Steve Anton75737c02017-11-06 10:37:17 -08005958 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005959 case cricket::DCT_SCTP:
5960 if (!sctp_factory_) {
5961 RTC_LOG(LS_ERROR)
5962 << "Trying to create SCTP transport, but didn't compile with "
5963 "SCTP support (HAVE_SCTP)";
5964 return false;
5965 }
5966 if (!network_thread()->Invoke<bool>(
5967 RTC_FROM_HERE,
5968 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5969 return false;
5970 }
5971 for (const auto& channel : sctp_data_channels_) {
5972 channel->OnTransportChannelCreated();
5973 }
5974 return true;
5975 case cricket::DCT_RTP:
5976 default:
5977 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5978 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5979 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5980 SrtpRequired(), GetCryptoOptions());
5981 if (!rtp_data_channel_) {
5982 return false;
5983 }
5984 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5985 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5986 rtp_data_channel_->SignalSentPacket.connect(
5987 this, &PeerConnection::OnSentPacket_w);
5988 rtp_data_channel_->SetRtpTransport(rtp_transport);
5989 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005990 }
5991
Steve Anton75737c02017-11-06 10:37:17 -08005992 return true;
5993}
5994
5995Call::Stats PeerConnection::GetCallStats() {
5996 if (!worker_thread()->IsCurrent()) {
5997 return worker_thread()->Invoke<Call::Stats>(
5998 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5999 }
6000 if (call_) {
6001 return call_->GetStats();
6002 } else {
6003 return Call::Stats();
6004 }
6005}
6006
Zhi Huange830e682018-03-30 10:48:35 -07006007bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006008 RTC_DCHECK(network_thread()->IsCurrent());
6009 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006010 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006011 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006012 RTC_DCHECK(dtls_transport);
6013 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006014 RTC_DCHECK(sctp_transport_);
6015 sctp_invoker_.reset(new rtc::AsyncInvoker());
6016 sctp_transport_->SignalReadyToSendData.connect(
6017 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6018 sctp_transport_->SignalDataReceived.connect(
6019 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006020 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6021 // another thread. Would be nice if there was a helper class similar to
6022 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6023 // code.
6024 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6025 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6026 sctp_transport_->SignalClosingProcedureComplete.connect(
6027 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006028 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006029 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006030 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006031}
6032
6033void PeerConnection::DestroySctpTransport_n() {
6034 RTC_DCHECK(network_thread()->IsCurrent());
6035 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006036 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006037 sctp_invoker_.reset(nullptr);
6038 sctp_ready_to_send_data_ = false;
6039}
6040
6041void PeerConnection::OnSctpTransportReadyToSendData_n() {
6042 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6043 RTC_DCHECK(network_thread()->IsCurrent());
6044 // Note: Cannot use rtc::Bind here because it will grab a reference to
6045 // PeerConnection and potentially cause PeerConnection to live longer than
6046 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6047 // be destroyed before PeerConnection is destroyed, and at that point all
6048 // pending tasks will be cleared.
6049 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6050 OnSctpTransportReadyToSendData_s(true);
6051 });
6052}
6053
6054void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6055 RTC_DCHECK(signaling_thread()->IsCurrent());
6056 sctp_ready_to_send_data_ = ready;
6057 SignalSctpReadyToSendData(ready);
6058}
6059
6060void PeerConnection::OnSctpTransportDataReceived_n(
6061 const cricket::ReceiveDataParams& params,
6062 const rtc::CopyOnWriteBuffer& payload) {
6063 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6064 RTC_DCHECK(network_thread()->IsCurrent());
6065 // Note: Cannot use rtc::Bind here because it will grab a reference to
6066 // PeerConnection and potentially cause PeerConnection to live longer than
6067 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6068 // be destroyed before PeerConnection is destroyed, and at that point all
6069 // pending tasks will be cleared.
6070 sctp_invoker_->AsyncInvoke<void>(
6071 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6072 OnSctpTransportDataReceived_s(params, payload);
6073 });
6074}
6075
6076void PeerConnection::OnSctpTransportDataReceived_s(
6077 const cricket::ReceiveDataParams& params,
6078 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006079 RTC_DCHECK_RUN_ON(signaling_thread());
6080 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006081 SignalSctpDataReceived(params, payload);
6082 }
6083}
6084
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006085void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006086 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(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006091 &SignalSctpClosingProcedureStartedRemotely, sid));
6092}
6093
6094void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6095 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6096 RTC_DCHECK(network_thread()->IsCurrent());
6097 sctp_invoker_->AsyncInvoke<void>(
6098 RTC_FROM_HERE, signaling_thread(),
6099 rtc::Bind(&sigslot::signal1<int>::operator(),
6100 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006101}
6102
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006103bool PeerConnection::SetupMediaTransportForDataChannels_n(
6104 const std::string& mid) {
6105 media_transport_ = transport_controller_->GetMediaTransport(mid);
6106 if (!media_transport_) {
6107 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6108 return false;
6109 }
6110
6111 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6112 media_transport_->SetDataSink(this);
6113 media_transport_data_mid_ = mid;
6114 transport_controller_->SignalMediaTransportStateChanged.connect(
6115 this, &PeerConnection::OnMediaTransportStateChanged_n);
6116 // Check the initial state right away, in case transport is already writable.
6117 OnMediaTransportStateChanged_n();
6118 return true;
6119}
6120
6121void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6122 if (!media_transport_) {
6123 return;
6124 }
6125 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6126 media_transport_data_mid_.reset();
6127 media_transport_->SetDataSink(nullptr);
6128 media_transport_invoker_ = nullptr;
6129 media_transport_ = nullptr;
6130}
6131
6132void PeerConnection::OnMediaTransportStateChanged_n() {
6133 if (!media_transport_data_mid_ ||
6134 transport_controller_->GetMediaTransportState(
6135 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6136 return;
6137 }
6138 media_transport_invoker_->AsyncInvoke<void>(
6139 RTC_FROM_HERE, signaling_thread(), [this] {
6140 RTC_DCHECK_RUN_ON(signaling_thread());
6141 media_transport_ready_to_send_data_ = true;
6142 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6143 });
6144}
6145
Steve Anton75737c02017-11-06 10:37:17 -08006146// Returns false if bundle is enabled and rtcp_mux is disabled.
6147bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6148 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6149 if (!bundle_enabled)
6150 return true;
6151
6152 const cricket::ContentGroup* bundle_group =
6153 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6154 RTC_DCHECK(bundle_group != NULL);
6155
6156 const cricket::ContentInfos& contents = desc->contents();
6157 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6158 citer != contents.end(); ++citer) {
6159 const cricket::ContentInfo* content = (&*citer);
6160 RTC_DCHECK(content != NULL);
6161 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006162 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006163 if (!HasRtcpMuxEnabled(content))
6164 return false;
6165 }
6166 }
6167 // RTCP-MUX is enabled in all the contents.
6168 return true;
6169}
6170
6171bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006172 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006173}
6174
Steve Anton06817cd2018-12-18 15:55:30 -08006175static RTCError ValidateMids(const cricket::SessionDescription& description) {
6176 std::set<std::string> mids;
6177 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006178 if (content.name.empty()) {
6179 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6180 "A media section is missing a MID attribute.");
6181 }
Steve Anton06817cd2018-12-18 15:55:30 -08006182 if (!mids.insert(content.name).second) {
6183 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6184 "Duplicate a=mid value '" + content.name + "'.");
6185 }
6186 }
6187 return RTCError::OK();
6188}
6189
Steve Anton8a006912017-12-04 15:25:56 -08006190RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006191 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006192 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006193 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006194 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006195 }
6196
6197 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006198 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006199 }
6200
Steve Anton3828c062017-12-06 10:34:51 -08006201 SdpType type = sdesc->GetType();
6202 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6203 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006204 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006205 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006206 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006207 }
6208
Steve Anton06817cd2018-12-18 15:55:30 -08006209 RTCError error = ValidateMids(*sdesc->description());
6210 if (!error.ok()) {
6211 return error;
6212 }
6213
Steve Anton75737c02017-11-06 10:37:17 -08006214 // Verify crypto settings.
6215 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006216 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6217 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006218 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006219 if (!crypto_error.ok()) {
6220 return crypto_error;
6221 }
Steve Anton75737c02017-11-06 10:37:17 -08006222 }
6223
6224 // Verify ice-ufrag and ice-pwd.
6225 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6227 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006228 }
6229
6230 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6232 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006233 }
6234
6235 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6236 // m-lines that do not rtcp-mux enabled.
6237
6238 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006239 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006240 // With an answer we want to compare the new answer session description with
6241 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006242 const cricket::SessionDescription* offer_desc =
6243 (source == cricket::CS_LOCAL) ? remote_description()->description()
6244 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006245 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6246 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6247 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006248 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6249 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006250 }
6251 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006252 // The re-offers should respect the order of m= sections in current
6253 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006254 // With a re-offer, either the current local or current remote descriptions
6255 // could be the most up to date, so we would like to check against both of
6256 // them if they exist. It could be the case that one of them has a 0 port
6257 // for a media section, but the other does not. This is important to check
6258 // against in the case that we are recycling an m= section.
6259 const cricket::SessionDescription* current_desc = nullptr;
6260 const cricket::SessionDescription* secondary_current_desc = nullptr;
6261 if (local_description()) {
6262 current_desc = local_description()->description();
6263 if (remote_description()) {
6264 secondary_current_desc = remote_description()->description();
6265 }
6266 } else if (remote_description()) {
6267 current_desc = remote_description()->description();
6268 }
Steve Anton75737c02017-11-06 10:37:17 -08006269 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006270 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6271 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006272 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6273 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006274 }
6275 }
6276
Steve Antonba42e992018-04-09 14:10:01 -07006277 if (IsUnifiedPlan()) {
6278 // Ensure that each audio and video media section has at most one
6279 // "StreamParams". This will return an error if receiving a session
6280 // description from a "Plan B" endpoint which adds multiple tracks of the
6281 // same type. With Unified Plan, there can only be at most one track per
6282 // media section.
6283 for (const ContentInfo& content : sdesc->description()->contents()) {
6284 const MediaContentDescription& desc = *content.description;
6285 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6286 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6287 desc.streams().size() > 1u) {
6288 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6289 "Media section has more than one track specified "
6290 "with a=ssrc lines which is not supported with "
6291 "Unified Plan.");
6292 }
6293 }
6294 }
6295
Steve Anton8a006912017-12-04 15:25:56 -08006296 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006297}
6298
Steve Anton3828c062017-12-06 10:34:51 -08006299bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006300 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006301 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006302 return (state == PeerConnectionInterface::kStable) ||
6303 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006304 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006305 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006306 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6307 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6308 }
6309}
6310
Steve Anton3828c062017-12-06 10:34:51 -08006311bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006312 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006313 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006314 return (state == PeerConnectionInterface::kStable) ||
6315 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006316 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006317 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006318 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6319 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6320 }
6321}
6322
Steve Antonf8470812017-12-04 10:46:21 -08006323const char* PeerConnection::SessionErrorToString(SessionError error) const {
6324 switch (error) {
6325 case SessionError::kNone:
6326 return "ERROR_NONE";
6327 case SessionError::kContent:
6328 return "ERROR_CONTENT";
6329 case SessionError::kTransport:
6330 return "ERROR_TRANSPORT";
6331 }
6332 RTC_NOTREACHED();
6333 return "";
6334}
6335
Steve Anton75737c02017-11-06 10:37:17 -08006336std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006337 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006338 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6339 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006340 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006341}
6342
Steve Anton8e20f172018-03-06 10:55:04 -08006343void PeerConnection::ReportSdpFormatReceived(
6344 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006345 int num_audio_mlines = 0;
6346 int num_video_mlines = 0;
6347 int num_audio_tracks = 0;
6348 int num_video_tracks = 0;
6349 for (const ContentInfo& content : remote_offer.description()->contents()) {
6350 cricket::MediaType media_type = content.media_description()->type();
6351 int num_tracks = std::max(
6352 1, static_cast<int>(content.media_description()->streams().size()));
6353 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6354 num_audio_mlines += 1;
6355 num_audio_tracks += num_tracks;
6356 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6357 num_video_mlines += 1;
6358 num_video_tracks += num_tracks;
6359 }
6360 }
6361 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6362 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6363 format = kSdpFormatReceivedComplexUnifiedPlan;
6364 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6365 format = kSdpFormatReceivedComplexPlanB;
6366 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6367 format = kSdpFormatReceivedSimple;
6368 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006369 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6370 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006371}
6372
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006373void PeerConnection::NoteUsageEvent(UsageEvent event) {
6374 RTC_DCHECK_RUN_ON(signaling_thread());
6375 usage_event_accumulator_ |= static_cast<int>(event);
6376}
6377
6378void PeerConnection::ReportUsagePattern() const {
6379 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006380 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6381 usage_event_accumulator_,
6382 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006383 const int bad_bits =
6384 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6385 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6386 const int good_bits =
6387 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6388 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6389 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6390 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6391 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006392 // If called after close(), we can't report, because observer may have
6393 // been deallocated, and therefore pointer is null. Write to log instead.
6394 if (observer_) {
6395 Observer()->OnInterestingUsage(usage_event_accumulator_);
6396 } else {
6397 RTC_LOG(LS_INFO) << "Interesting usage signature "
6398 << usage_event_accumulator_
6399 << " observed after observer shutdown";
6400 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006401 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006402}
6403
Steve Anton0ffaaa22018-02-23 10:31:30 -08006404void PeerConnection::ReportNegotiatedSdpSemantics(
6405 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006406 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006407 switch (answer.description()->msid_signaling()) {
6408 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006409 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006410 break;
6411 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006412 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006413 break;
6414 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006415 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006416 break;
6417 case cricket::kMsidSignalingMediaSection |
6418 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006419 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006420 break;
6421 default:
6422 RTC_NOTREACHED();
6423 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006424 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6425 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006426}
6427
Steve Anton75737c02017-11-06 10:37:17 -08006428// We need to check the local/remote description for the Transport instead of
6429// the session, because a new Transport added during renegotiation may have
6430// them unset while the session has them set from the previous negotiation.
6431// Not doing so may trigger the auto generation of transport description and
6432// mess up DTLS identity information, ICE credential, etc.
6433bool PeerConnection::ReadyToUseRemoteCandidate(
6434 const IceCandidateInterface* candidate,
6435 const SessionDescriptionInterface* remote_desc,
6436 bool* valid) {
6437 *valid = true;
6438
6439 const SessionDescriptionInterface* current_remote_desc =
6440 remote_desc ? remote_desc : remote_description();
6441
6442 if (!current_remote_desc) {
6443 return false;
6444 }
6445
6446 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6447 size_t remote_content_size =
6448 current_remote_desc->description()->contents().size();
6449 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006450 RTC_LOG(LS_ERROR)
6451 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6452 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006453
6454 *valid = false;
6455 return false;
6456 }
6457
6458 cricket::ContentInfo content =
6459 current_remote_desc->description()->contents()[mediacontent_index];
6460
6461 const std::string transport_name = GetTransportName(content.name);
6462 if (transport_name.empty()) {
6463 return false;
6464 }
Zhi Huange830e682018-03-30 10:48:35 -07006465 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006466}
6467
6468bool PeerConnection::SrtpRequired() const {
6469 return dtls_enabled_ ||
6470 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6471}
6472
6473void PeerConnection::OnTransportControllerGatheringState(
6474 cricket::IceGatheringState state) {
6475 RTC_DCHECK(signaling_thread()->IsCurrent());
6476 if (state == cricket::kIceGatheringGathering) {
6477 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6478 } else if (state == cricket::kIceGatheringComplete) {
6479 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6480 }
6481}
6482
6483void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006484 std::map<std::string, std::set<cricket::MediaType>>
6485 media_types_by_transport_name;
6486 for (auto transceiver : transceivers_) {
6487 if (transceiver->internal()->channel()) {
6488 const std::string& transport_name =
6489 transceiver->internal()->channel()->transport_name();
6490 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006491 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006492 }
Steve Anton75737c02017-11-06 10:37:17 -08006493 }
6494 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006495 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6496 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006497 }
Zhi Huange830e682018-03-30 10:48:35 -07006498
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006499 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006500 if (transport_name) {
6501 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006502 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006503 }
Zhi Huange830e682018-03-30 10:48:35 -07006504
Steve Antonc7b964c2018-02-01 14:39:45 -08006505 for (const auto& entry : media_types_by_transport_name) {
6506 const std::string& transport_name = entry.first;
6507 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006508 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006509 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006510 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006511 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006512 }
6513 }
6514}
6515// Walk through the ConnectionInfos to gather best connection usage
6516// for IPv4 and IPv6.
6517void PeerConnection::ReportBestConnectionState(
6518 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006519 for (const cricket::TransportChannelStats& channel_stats :
6520 stats.channel_stats) {
6521 for (const cricket::ConnectionInfo& connection_info :
6522 channel_stats.connection_infos) {
6523 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006524 continue;
6525 }
6526
Steve Antonc7b964c2018-02-01 14:39:45 -08006527 const cricket::Candidate& local = connection_info.local_candidate;
6528 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006529
6530 // Increment the counter for IceCandidatePairType.
6531 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6532 (local.type() == RELAY_PORT_TYPE &&
6533 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006534 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6535 GetIceCandidatePairCounter(local, remote),
6536 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006537 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006538 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6539 GetIceCandidatePairCounter(local, remote),
6540 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006541 } else {
6542 RTC_CHECK(0);
6543 }
Steve Anton75737c02017-11-06 10:37:17 -08006544
6545 // Increment the counter for IP type.
6546 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006547 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6548 kBestConnections_IPv4,
6549 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006550 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006551 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6552 kBestConnections_IPv6,
6553 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006554 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006555 RTC_CHECK(!local.address().hostname().empty() &&
6556 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006557 }
6558
6559 return;
6560 }
6561 }
6562}
6563
6564void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006565 const cricket::TransportStats& stats,
6566 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006567 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6568 return;
6569 }
6570
6571 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6572 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6573 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6574 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6575 return;
6576 }
6577
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006578 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6579 for (cricket::MediaType media_type : media_types) {
6580 switch (media_type) {
6581 case cricket::MEDIA_TYPE_AUDIO:
6582 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6583 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6584 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6585 break;
6586 case cricket::MEDIA_TYPE_VIDEO:
6587 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6588 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6589 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6590 break;
6591 case cricket::MEDIA_TYPE_DATA:
6592 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6593 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6594 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6595 break;
6596 default:
6597 RTC_NOTREACHED();
6598 continue;
6599 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006600 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006601 }
6602
6603 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6604 for (cricket::MediaType media_type : media_types) {
6605 switch (media_type) {
6606 case cricket::MEDIA_TYPE_AUDIO:
6607 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6608 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6609 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6610 break;
6611 case cricket::MEDIA_TYPE_VIDEO:
6612 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6613 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6614 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6615 break;
6616 case cricket::MEDIA_TYPE_DATA:
6617 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6618 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6619 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6620 break;
6621 default:
6622 RTC_NOTREACHED();
6623 continue;
6624 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006625 }
Steve Anton75737c02017-11-06 10:37:17 -08006626 }
6627}
6628
6629void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6630 RTC_DCHECK(worker_thread()->IsCurrent());
6631 RTC_DCHECK(call_);
6632 call_->OnSentPacket(sent_packet);
6633}
6634
6635const std::string PeerConnection::GetTransportName(
6636 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006637 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006638 if (channel) {
6639 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006640 }
Steve Anton6fec8802017-12-04 10:37:29 -08006641 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006642 RTC_DCHECK(sctp_mid_);
6643 if (content_name == *sctp_mid_) {
6644 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006645 }
6646 }
6647 // Return an empty string if failed to retrieve the transport name.
6648 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006649}
6650
Steve Anton6fec8802017-12-04 10:37:29 -08006651void PeerConnection::DestroyTransceiverChannel(
6652 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6653 transceiver) {
6654 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006655
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006656 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006657 if (channel) {
6658 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006659 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006660 }
6661}
6662
6663void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006664 if (rtp_data_channel_) {
6665 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006666 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006667 rtp_data_channel_ = nullptr;
6668 }
6669
6670 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6671 // grab a reference to this PeerConnection. If this is called from the
6672 // PeerConnection destructor, the RefCountedObject vtable will have already
6673 // been destroyed (since it is a subclass of PeerConnection) and using
6674 // rtc::Bind will cause "Pure virtual function called" error to appear.
6675
6676 if (sctp_transport_) {
6677 OnDataChannelDestroyed();
6678 network_thread()->Invoke<void>(RTC_FROM_HERE,
6679 [this] { DestroySctpTransport_n(); });
6680 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006681
6682 if (media_transport_) {
6683 OnDataChannelDestroyed();
6684 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6685 RTC_DCHECK_RUN_ON(network_thread());
6686 TeardownMediaTransportForDataChannels_n();
6687 });
6688 }
Steve Anton6fec8802017-12-04 10:37:29 -08006689}
6690
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006691void PeerConnection::DestroyChannelInterface(
6692 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006693 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006694 switch (channel->media_type()) {
6695 case cricket::MEDIA_TYPE_AUDIO:
6696 channel_manager()->DestroyVoiceChannel(
6697 static_cast<cricket::VoiceChannel*>(channel));
6698 break;
6699 case cricket::MEDIA_TYPE_VIDEO:
6700 channel_manager()->DestroyVideoChannel(
6701 static_cast<cricket::VideoChannel*>(channel));
6702 break;
6703 case cricket::MEDIA_TYPE_DATA:
6704 channel_manager()->DestroyRtpDataChannel(
6705 static_cast<cricket::RtpDataChannel*>(channel));
6706 break;
6707 default:
6708 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6709 break;
6710 }
Zhi Huange830e682018-03-30 10:48:35 -07006711}
Steve Anton6fec8802017-12-04 10:37:29 -08006712
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006713bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006714 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006715 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006716 cricket::DtlsTransportInternal* dtls_transport,
6717 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006718 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006719 auto base_channel = GetChannel(mid);
6720 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006721 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006722 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006723 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006724 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006725 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006726
6727 call_->MediaTransportChange(media_transport);
6728
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006729 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006730}
6731
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006732PeerConnectionObserver* PeerConnection::Observer() const {
6733 // In earlier production code, the pointer was not cleared on close,
6734 // which might have led to undefined behavior if the observer was not
6735 // deallocated, or strange crashes if it was.
6736 // We use CHECK in order to catch such behavior if it exists.
6737 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6738 RTC_CHECK(observer_);
6739 return observer_;
6740}
6741
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006742CryptoOptions PeerConnection::GetCryptoOptions() {
6743 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6744 // after it has been removed.
6745 return configuration_.crypto_options.has_value()
6746 ? *configuration_.crypto_options
6747 : factory_->options().crypto_options;
6748}
6749
Harald Alvestrand89061872018-01-02 14:08:34 +01006750void PeerConnection::ClearStatsCache() {
6751 if (stats_collector_) {
6752 stats_collector_->ClearCachedStatsReport();
6753 }
6754}
6755
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006756void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006757 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6758 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006759}
6760
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006761} // namespace webrtc