blob: 0cbd3153f7ce87f26127ce9cdf34a9af01b1f8e9 [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_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002109 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2110 // Note that code paths that don't set MID won't be able to use
2111 // information about DTLS transports.
2112 if (transceiver->mid()) {
2113 auto dtls_transport =
2114 LookupDtlsTransportByMidInternal(*transceiver->mid());
2115 transceiver->internal()->sender_internal()->set_transport(
2116 dtls_transport);
2117 transceiver->internal()->receiver_internal()->set_transport(
2118 dtls_transport);
2119 }
2120
Steve Antondcc3c022017-12-22 16:02:54 -08002121 const ContentInfo* content =
2122 FindMediaSectionForTransceiver(transceiver, local_description());
2123 if (!content) {
2124 continue;
2125 }
2126 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002127 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2128 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002129 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002130 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2131 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2132 // "recvonly", process the removal of a remote track for the media
2133 // description, given transceiver, removeList, and muteTracks.
2134 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2135 (transceiver->internal()->fired_direction() &&
2136 RtpTransceiverDirectionHasRecv(
2137 *transceiver->internal()->fired_direction()))) {
2138 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2139 &removed_streams);
2140 }
2141 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2142 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002143 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002144 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002145 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002146 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002147 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002148 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002149 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002150 }
2151 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002152 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002153 }
2154 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002155 // Media channels will be created only when offer is set. These may use new
2156 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002157 if (type == SdpType::kOffer) {
2158 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2159 // description is applied. Restore back to old description.
2160 RTCError error = CreateChannels(*local_description()->description());
2161 if (!error.ok()) {
2162 return error;
2163 }
2164 }
Steve Antondcc3c022017-12-22 16:02:54 -08002165 // Remove unused channels if MediaContentDescription is rejected.
2166 RemoveUnusedChannels(local_description()->description());
2167 }
Steve Anton8a006912017-12-04 15:25:56 -08002168
Zhi Huange830e682018-03-30 10:48:35 -07002169 error = UpdateSessionState(type, cricket::CS_LOCAL,
2170 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002171 if (!error.ok()) {
2172 return error;
2173 }
Steve Antondcc3c022017-12-22 16:02:54 -08002174
Steve Anton8a006912017-12-04 15:25:56 -08002175 if (remote_description()) {
2176 // Now that we have a local description, we can push down remote candidates.
2177 UseCandidatesInSessionDescription(remote_description());
2178 }
2179
2180 pending_ice_restarts_.clear();
2181 if (session_error() != SessionError::kNone) {
2182 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2183 }
2184
deadbeefab9b2d12015-10-14 11:33:11 -07002185 // If setting the description decided our SSL role, allocate any necessary
2186 // SCTP sids.
2187 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002188 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002189 AllocateSctpSids(role);
2190 }
2191
Steve Antond3679212018-01-17 17:41:02 -08002192 if (IsUnifiedPlan()) {
2193 for (auto transceiver : transceivers_) {
2194 const ContentInfo* content =
2195 FindMediaSectionForTransceiver(transceiver, local_description());
2196 if (!content) {
2197 continue;
2198 }
Steve Anton74255ff2018-01-24 18:32:57 -08002199 const auto& streams = content->media_description()->streams();
2200 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002201 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002202 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002203 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002204 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002205 } else {
2206 // 0 is a special value meaning "this sender has no associated send
2207 // stream". Need to call this so the sender won't attempt to configure
2208 // a no longer existing stream and run into DCHECKs in the lower
2209 // layers.
2210 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002211 }
2212 }
2213 } else {
2214 // Plan B semantics.
2215
Steve Antondcc3c022017-12-22 16:02:54 -08002216 // Update state and SSRC of local MediaStreams and DataChannels based on the
2217 // local session description.
2218 const cricket::ContentInfo* audio_content =
2219 GetFirstAudioContent(local_description()->description());
2220 if (audio_content) {
2221 if (audio_content->rejected) {
2222 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2223 } else {
2224 const cricket::AudioContentDescription* audio_desc =
2225 audio_content->media_description()->as_audio();
2226 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2227 }
deadbeeffaac4972015-11-12 15:33:07 -08002228 }
deadbeefab9b2d12015-10-14 11:33:11 -07002229
Steve Antondcc3c022017-12-22 16:02:54 -08002230 const cricket::ContentInfo* video_content =
2231 GetFirstVideoContent(local_description()->description());
2232 if (video_content) {
2233 if (video_content->rejected) {
2234 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2235 } else {
2236 const cricket::VideoContentDescription* video_desc =
2237 video_content->media_description()->as_video();
2238 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2239 }
deadbeeffaac4972015-11-12 15:33:07 -08002240 }
deadbeefab9b2d12015-10-14 11:33:11 -07002241 }
2242
2243 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002244 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002245 if (data_content) {
2246 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002247 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002248 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002249 cricket::kMediaProtocolRtpPrefix)) {
2250 UpdateLocalRtpDataChannels(data_desc->streams());
2251 }
2252 }
2253
Steve Anton8a006912017-12-04 15:25:56 -08002254 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002255}
2256
Steve Anton06817cd2018-12-18 15:55:30 -08002257// The SDP parser used to populate these values by default for the 'content
2258// name' if an a=mid line was absent.
2259static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2260 switch (media_type) {
2261 case cricket::MEDIA_TYPE_AUDIO:
2262 return cricket::CN_AUDIO;
2263 case cricket::MEDIA_TYPE_VIDEO:
2264 return cricket::CN_VIDEO;
2265 case cricket::MEDIA_TYPE_DATA:
2266 return cricket::CN_DATA;
2267 }
2268 RTC_NOTREACHED();
2269 return "";
2270}
2271
2272void PeerConnection::FillInMissingRemoteMids(
2273 cricket::SessionDescription* remote_description) {
2274 RTC_DCHECK(remote_description);
2275 const cricket::ContentInfos& local_contents =
2276 (local_description() ? local_description()->description()->contents()
2277 : cricket::ContentInfos());
Steve Anton06817cd2018-12-18 15:55:30 -08002278 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2279 cricket::ContentInfo& content = remote_description->contents()[i];
2280 if (!content.name.empty()) {
2281 continue;
2282 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002283 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002284 absl::string_view source_explanation;
2285 if (IsUnifiedPlan()) {
2286 if (i < local_contents.size()) {
2287 new_mid = local_contents[i].name;
2288 source_explanation = "from the matching local media section";
2289 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002290 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002291 source_explanation = "generated just now";
2292 }
2293 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002294 new_mid = std::string(
2295 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002296 source_explanation = "to match pre-existing behavior";
2297 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002298 content.name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002299 remote_description->transport_infos()[i].content_name =
2300 std::string(new_mid);
2301 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2302 << " is missing an a=mid line. Filling in the value '"
2303 << new_mid << "' " << source_explanation << ".";
2304 }
2305}
2306
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002308 SetSessionDescriptionObserver* observer,
2309 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002310 SetRemoteDescription(
2311 std::unique_ptr<SessionDescriptionInterface>(desc),
2312 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2313 new SetRemoteDescriptionObserverAdapter(this, observer)));
2314}
2315
2316void PeerConnection::SetRemoteDescription(
2317 std::unique_ptr<SessionDescriptionInterface> desc,
2318 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002319 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002320
nisse7ce109a2017-01-31 00:57:56 -08002321 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002322 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002323 return;
2324 }
Steve Anton8a006912017-12-04 15:25:56 -08002325
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002327 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002328 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329 return;
2330 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002331
Steve Anton80dd7b52018-02-16 17:08:42 -08002332 // If a session error has occurred the PeerConnection is in a possibly
2333 // inconsistent state so fail right away.
2334 if (session_error() != SessionError::kNone) {
2335 std::string error_message = GetSessionErrorMsg();
2336 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2337 observer->OnSetRemoteDescriptionComplete(
2338 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2339 return;
2340 }
Steve Anton71439a62018-02-15 11:53:06 -08002341
Steve Antonba42e992018-04-09 14:10:01 -07002342 if (desc->GetType() == SdpType::kOffer) {
2343 // Report to UMA the format of the received offer.
2344 ReportSdpFormatReceived(*desc);
2345 }
2346
Steve Anton06817cd2018-12-18 15:55:30 -08002347 // Handle remote descriptions missing a=mid lines for interop with legacy end
2348 // points.
2349 FillInMissingRemoteMids(desc->description());
2350
Steve Anton80dd7b52018-02-16 17:08:42 -08002351 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002352 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002353 std::string error_message = GetSetDescriptionErrorMessage(
2354 cricket::CS_REMOTE, desc->GetType(), error);
2355 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002356 observer->OnSetRemoteDescriptionComplete(
2357 RTCError(error.type(), std::move(error_message)));
2358 return;
2359 }
Steve Anton71439a62018-02-15 11:53:06 -08002360
Steve Anton80dd7b52018-02-16 17:08:42 -08002361 // Grab the description type before moving ownership to
2362 // ApplyRemoteDescription, which may destroy it before returning.
2363 const SdpType type = desc->GetType();
2364
2365 error = ApplyRemoteDescription(std::move(desc));
2366 // |desc| may be destroyed at this point.
2367
2368 if (!error.ok()) {
2369 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2370 // inconsistent state, so act conservatively here and set the session error
2371 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2372 SetSessionError(SessionError::kContent, error.message());
2373 std::string error_message =
2374 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2375 RTC_LOG(LS_ERROR) << error_message;
2376 observer->OnSetRemoteDescriptionComplete(
2377 RTCError(error.type(), std::move(error_message)));
2378 return;
2379 }
2380 RTC_DCHECK(remote_description());
2381
2382 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002383 // TODO(deadbeef): We already had to hop to the network thread for
2384 // MaybeStartGathering...
2385 network_thread()->Invoke<void>(
2386 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2387 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002388 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002389 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002390 }
2391
2392 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002393 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002394}
2395
2396RTCError PeerConnection::ApplyRemoteDescription(
2397 std::unique_ptr<SessionDescriptionInterface> desc) {
2398 RTC_DCHECK_RUN_ON(signaling_thread());
2399 RTC_DCHECK(desc);
2400
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002401 // Update stats here so that we have the most recent stats for tracks and
2402 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002403 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002404
Steve Antondcc3c022017-12-22 16:02:54 -08002405 // Take a reference to the old remote description since it's used below to
2406 // compare against the new remote description. When setting the new remote
2407 // description, grab ownership of the replaced session description in case it
2408 // is the same as |old_remote_description|, to keep it alive for the duration
2409 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002410 const SessionDescriptionInterface* old_remote_description =
2411 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002412 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002413 SdpType type = desc->GetType();
2414 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002415 replaced_remote_description = pending_remote_description_
2416 ? std::move(pending_remote_description_)
2417 : std::move(current_remote_description_);
2418 current_remote_description_ = std::move(desc);
2419 pending_remote_description_ = nullptr;
2420 current_local_description_ = std::move(pending_local_description_);
2421 } else {
2422 replaced_remote_description = std::move(pending_remote_description_);
2423 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424 }
Steve Anton8a006912017-12-04 15:25:56 -08002425 // The session description to apply now must be accessed by
2426 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002427 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002428
Zhi Huange830e682018-03-30 10:48:35 -07002429 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2430 if (!error.ok()) {
2431 return error;
2432 }
Steve Anton8a006912017-12-04 15:25:56 -08002433 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002434 if (IsUnifiedPlan()) {
2435 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002436 cricket::CS_REMOTE, *remote_description(), local_description(),
2437 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002438 if (!error.ok()) {
2439 return error;
2440 }
Steve Antondcc3c022017-12-22 16:02:54 -08002441 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002442 // Media channels will be created only when offer is set. These may use new
2443 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002444 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002445 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002446 // description is applied. Restore back to old description.
2447 RTCError error = CreateChannels(*remote_description()->description());
2448 if (!error.ok()) {
2449 return error;
2450 }
2451 }
Steve Antondcc3c022017-12-22 16:02:54 -08002452 // Remove unused channels if MediaContentDescription is rejected.
2453 RemoveUnusedChannels(remote_description()->description());
2454 }
Steve Anton8a006912017-12-04 15:25:56 -08002455
Zhi Huange830e682018-03-30 10:48:35 -07002456 // NOTE: Candidates allocation will be initiated only when
2457 // SetLocalDescription is called.
2458 error = UpdateSessionState(type, cricket::CS_REMOTE,
2459 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002460 if (!error.ok()) {
2461 return error;
2462 }
2463
2464 if (local_description() &&
2465 !UseCandidatesInSessionDescription(remote_description())) {
2466 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2467 }
2468
2469 if (old_remote_description) {
2470 for (const cricket::ContentInfo& content :
2471 old_remote_description->description()->contents()) {
2472 // Check if this new SessionDescription contains new ICE ufrag and
2473 // password that indicates the remote peer requests an ICE restart.
2474 // TODO(deadbeef): When we start storing both the current and pending
2475 // remote description, this should reset pending_ice_restarts and compare
2476 // against the current description.
2477 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2478 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002479 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002480 pending_ice_restarts_.insert(content.name);
2481 }
2482 } else {
2483 // We retain all received candidates only if ICE is not restarted.
2484 // When ICE is restarted, all previous candidates belong to an old
2485 // generation and should not be kept.
2486 // TODO(deadbeef): This goes against the W3C spec which says the remote
2487 // description should only contain candidates from the last set remote
2488 // description plus any candidates added since then. We should remove
2489 // this once we're sure it won't break anything.
2490 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2491 old_remote_description, content.name, mutable_remote_description());
2492 }
2493 }
2494 }
2495
2496 if (session_error() != SessionError::kNone) {
2497 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2498 }
2499
2500 // Set the the ICE connection state to connecting since the connection may
2501 // become writable with peer reflexive candidates before any remote candidate
2502 // is signaled.
2503 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2504 // is to have a new signal the indicates a change in checking state from the
2505 // transport and expose a new checking() member from transport that can be
2506 // read to determine the current checking state. The existing SignalConnecting
2507 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002508 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002509 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002510 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2511 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2512 }
2513
deadbeefab9b2d12015-10-14 11:33:11 -07002514 // If setting the description decided our SSL role, allocate any necessary
2515 // SCTP sids.
2516 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002517 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002518 AllocateSctpSids(role);
2519 }
2520
Steve Antondcc3c022017-12-22 16:02:54 -08002521 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002522 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002523 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002524 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002525 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002526 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002527 for (auto transceiver : transceivers_) {
2528 const ContentInfo* content =
2529 FindMediaSectionForTransceiver(transceiver, remote_description());
2530 if (!content) {
2531 continue;
2532 }
2533 const MediaContentDescription* media_desc = content->media_description();
2534 RtpTransceiverDirection local_direction =
2535 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002536 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2537 // RTCSessionDescription: Set the associated remote streams given
2538 // transceiver.[[Receiver]], msids, addList, and removeList".
2539 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2540 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2541 std::vector<std::string> stream_ids;
2542 if (!media_desc->streams().empty()) {
2543 // The remote description has signaled the stream IDs.
2544 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002545 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002546 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2547 << " (" << GetStreamIdsString(stream_ids) << ").";
2548 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2549 stream_ids, &added_streams,
2550 &removed_streams);
2551 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2552 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2553 // and transceiver's current direction is neither sendrecv nor recvonly,
2554 // process the addition of a remote track for the media description.
2555 if (!transceiver->fired_direction() ||
2556 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2557 RTC_LOG(LS_INFO)
2558 << "Processing the addition of a remote track for MID="
2559 << content->name << ".";
2560 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002561 }
Steve Antondcc3c022017-12-22 16:02:54 -08002562 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002563 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002564 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2565 // removal of a remote track for the media description, given transceiver,
2566 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002567 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002568 (transceiver->fired_direction() &&
2569 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2570 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2571 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002572 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002573 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002574 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002575 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002576 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002577 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002578 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002579 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002580 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002581 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2582 if (transceiver->mid()) {
2583 auto dtls_transport =
2584 LookupDtlsTransportByMidInternal(*transceiver->mid());
2585 transceiver->internal()->sender_internal()->set_transport(
2586 dtls_transport);
2587 transceiver->internal()->receiver_internal()->set_transport(
2588 dtls_transport);
2589 }
Steve Antondcc3c022017-12-22 16:02:54 -08002590 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002591 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002592 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002593 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002594 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2595 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002596 transceiver->Stop();
2597 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002598 if (!content->rejected &&
2599 RtpTransceiverDirectionHasRecv(local_direction)) {
2600 // Set ssrc to 0 in the case of an unsignalled ssrc.
2601 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002602 if (!media_desc->streams().empty() &&
2603 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002604 ssrc = media_desc->streams()[0].first_ssrc();
2605 }
2606 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002607 }
Steve Antondcc3c022017-12-22 16:02:54 -08002608 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002609 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002610 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002611 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002612 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002613 observer->OnTrack(transceiver);
2614 observer->OnAddTrack(transceiver->receiver(),
2615 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002616 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002617 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002618 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002619 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002620 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002621 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002622 }
2623 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002624 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002625 }
Steve Antondcc3c022017-12-22 16:02:54 -08002626 }
2627
Henrik Boströmfdb92012017-11-09 19:55:44 +01002628 const cricket::ContentInfo* audio_content =
2629 GetFirstAudioContent(remote_description()->description());
2630 const cricket::ContentInfo* video_content =
2631 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002632 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002633 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002634 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002635 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002636 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002637 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002638
2639 // Check if the descriptions include streams, just in case the peer supports
2640 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002641 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002642 (audio_desc && !audio_desc->streams().empty()) ||
2643 (video_desc && !video_desc->streams().empty())) {
2644 remote_peer_supports_msid_ = true;
2645 }
deadbeefab9b2d12015-10-14 11:33:11 -07002646
2647 // We wait to signal new streams until we finish processing the description,
2648 // since only at that point will new streams have all their tracks.
2649 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2650
Steve Antondcc3c022017-12-22 16:02:54 -08002651 if (!IsUnifiedPlan()) {
2652 // TODO(steveanton): When removing RTP senders/receivers in response to a
2653 // rejected media section, there is some cleanup logic that expects the
2654 // voice/ video channel to still be set. But in this method the voice/video
2655 // channel would have been destroyed by the SetRemoteDescription caller
2656 // above so the cleanup that relies on them fails to run. The RemoveSenders
2657 // calls should be moved to right before the DestroyChannel calls to fix
2658 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002659
Steve Antondcc3c022017-12-22 16:02:54 -08002660 // Find all audio rtp streams and create corresponding remote AudioTracks
2661 // and MediaStreams.
2662 if (audio_content) {
2663 if (audio_content->rejected) {
2664 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2665 } else {
2666 bool default_audio_track_needed =
2667 !remote_peer_supports_msid_ &&
2668 RtpTransceiverDirectionHasSend(audio_desc->direction());
2669 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2670 default_audio_track_needed, audio_desc->type(),
2671 new_streams);
2672 }
deadbeeffaac4972015-11-12 15:33:07 -08002673 }
deadbeefab9b2d12015-10-14 11:33:11 -07002674
Steve Antondcc3c022017-12-22 16:02:54 -08002675 // Find all video rtp streams and create corresponding remote VideoTracks
2676 // and MediaStreams.
2677 if (video_content) {
2678 if (video_content->rejected) {
2679 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2680 } else {
2681 bool default_video_track_needed =
2682 !remote_peer_supports_msid_ &&
2683 RtpTransceiverDirectionHasSend(video_desc->direction());
2684 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2685 default_video_track_needed, video_desc->type(),
2686 new_streams);
2687 }
deadbeeffaac4972015-11-12 15:33:07 -08002688 }
deadbeefab9b2d12015-10-14 11:33:11 -07002689
Steve Antondcc3c022017-12-22 16:02:54 -08002690 // Update the DataChannels with the information from the remote peer.
2691 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002692 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002693 cricket::kMediaProtocolRtpPrefix)) {
2694 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2695 }
deadbeefab9b2d12015-10-14 11:33:11 -07002696 }
deadbeefab9b2d12015-10-14 11:33:11 -07002697
Steve Antondcc3c022017-12-22 16:02:54 -08002698 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002699 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002700 for (size_t i = 0; i < new_streams->count(); ++i) {
2701 MediaStreamInterface* new_stream = new_streams->at(i);
2702 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002703 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002704 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2705 }
deadbeefab9b2d12015-10-14 11:33:11 -07002706
Steve Antondcc3c022017-12-22 16:02:54 -08002707 UpdateEndedRemoteMediaStreams();
2708 }
deadbeefab9b2d12015-10-14 11:33:11 -07002709
Steve Anton8a006912017-12-04 15:25:56 -08002710 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002711}
2712
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002713void PeerConnection::SetAssociatedRemoteStreams(
2714 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2715 const std::vector<std::string>& stream_ids,
2716 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2717 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2718 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2719 for (const std::string& stream_id : stream_ids) {
2720 rtc::scoped_refptr<MediaStreamInterface> stream =
2721 remote_streams_->find(stream_id);
2722 if (!stream) {
2723 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2724 MediaStream::Create(stream_id));
2725 remote_streams_->AddStream(stream);
2726 added_streams->push_back(stream);
2727 }
2728 media_streams.push_back(stream);
2729 }
2730 // Special case: "a=msid" missing, use random stream ID.
2731 if (media_streams.empty() &&
2732 !(remote_description()->description()->msid_signaling() &
2733 cricket::kMsidSignalingMediaSection)) {
2734 if (!missing_msid_default_stream_) {
2735 missing_msid_default_stream_ = MediaStreamProxy::Create(
2736 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2737 added_streams->push_back(missing_msid_default_stream_);
2738 }
2739 media_streams.push_back(missing_msid_default_stream_);
2740 }
2741 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2742 receiver->streams();
2743 // SetStreams() will add/remove the receiver's track to/from the streams. This
2744 // differs from the spec - the spec uses an "addList" and "removeList" to
2745 // update the stream-track relationships in a later step. We do this earlier,
2746 // changing the order of things, but the end-result is the same.
2747 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2748 // instead. https://crbug.com/webrtc/9480
2749 receiver->SetStreams(media_streams);
2750 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2751}
2752
Steve Anton0f5400a2018-07-17 14:25:36 -07002753void PeerConnection::ProcessRemovalOfRemoteTrack(
2754 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2755 transceiver,
2756 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2757 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2758 RTC_DCHECK(transceiver->mid());
2759 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2760 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002761 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002762 transceiver->internal()->receiver_internal()->streams();
2763 // This will remove the remote track from the streams.
2764 transceiver->internal()->receiver_internal()->set_stream_ids({});
2765 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002766 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2767}
2768
2769void PeerConnection::RemoveRemoteStreamsIfEmpty(
2770 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2771 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2772 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2773 // streams, see if the stream was removed by checking if this was the last
2774 // receiver with that stream ID.
2775 for (auto remote_stream : remote_streams) {
2776 if (remote_stream->GetAudioTracks().empty() &&
2777 remote_stream->GetVideoTracks().empty()) {
2778 remote_streams_->RemoveStream(remote_stream);
2779 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002780 }
2781 }
2782}
2783
Steve Antondcc3c022017-12-22 16:02:54 -08002784RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2785 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002786 const SessionDescriptionInterface& new_session,
2787 const SessionDescriptionInterface* old_local_description,
2788 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002789 RTC_DCHECK(IsUnifiedPlan());
2790
Steve Anton7464fca2018-01-19 11:10:37 -08002791 const cricket::ContentGroup* bundle_group = nullptr;
2792 if (new_session.GetType() == SdpType::kOffer) {
2793 auto bundle_group_or_error =
2794 GetEarlyBundleGroup(*new_session.description());
2795 if (!bundle_group_or_error.ok()) {
2796 return bundle_group_or_error.MoveError();
2797 }
2798 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002799 }
Steve Antondcc3c022017-12-22 16:02:54 -08002800
Steve Antondcc3c022017-12-22 16:02:54 -08002801 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002802 for (size_t i = 0; i < new_contents.size(); ++i) {
2803 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002804 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002805 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002806 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2807 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002808 const cricket::ContentInfo* old_local_content = nullptr;
2809 if (old_local_description &&
2810 i < old_local_description->description()->contents().size()) {
2811 old_local_content =
2812 &old_local_description->description()->contents()[i];
2813 }
2814 const cricket::ContentInfo* old_remote_content = nullptr;
2815 if (old_remote_description &&
2816 i < old_remote_description->description()->contents().size()) {
2817 old_remote_content =
2818 &old_remote_description->description()->contents()[i];
2819 }
Steve Antondcc3c022017-12-22 16:02:54 -08002820 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002821 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2822 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002823 if (!transceiver_or_error.ok()) {
2824 return transceiver_or_error.MoveError();
2825 }
2826 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002827 RTCError error =
2828 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2829 if (!error.ok()) {
2830 return error;
2831 }
2832 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002833 if (GetDataMid() && new_content.name != *GetDataMid()) {
2834 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002835 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2836 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002837 continue;
2838 }
2839 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2840 if (!error.ok()) {
2841 return error;
2842 }
Steve Antondcc3c022017-12-22 16:02:54 -08002843 } else {
2844 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2845 "Unknown section type.");
2846 }
2847 }
2848
2849 return RTCError::OK();
2850}
2851
2852RTCError PeerConnection::UpdateTransceiverChannel(
2853 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2854 transceiver,
2855 const cricket::ContentInfo& content,
2856 const cricket::ContentGroup* bundle_group) {
2857 RTC_DCHECK(IsUnifiedPlan());
2858 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002859 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002860 if (content.rejected) {
2861 if (channel) {
2862 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002863 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002864 }
2865 } else {
2866 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002867 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002868 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002869 } else {
Steve Anton69470252018-02-09 11:43:08 -08002870 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002871 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002872 }
2873 if (!channel) {
2874 LOG_AND_RETURN_ERROR(
2875 RTCErrorType::INTERNAL_ERROR,
2876 "Failed to create channel for mid=" + content.name);
2877 }
2878 transceiver->internal()->SetChannel(channel);
2879 }
2880 }
2881 return RTCError::OK();
2882}
2883
Steve Antonfa2260d2017-12-28 16:38:23 -08002884RTCError PeerConnection::UpdateDataChannel(
2885 cricket::ContentSource source,
2886 const cricket::ContentInfo& content,
2887 const cricket::ContentGroup* bundle_group) {
2888 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002889 // If data channels are disabled, ignore this media section. CreateAnswer
2890 // will take care of rejecting it.
2891 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002892 }
2893 if (content.rejected) {
2894 DestroyDataChannel();
2895 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002896 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002897 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002898 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2899 "Failed to create data channel.");
2900 }
2901 }
2902 if (source == cricket::CS_REMOTE) {
2903 const MediaContentDescription* data_desc = content.media_description();
2904 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2905 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2906 }
2907 }
2908 }
2909 return RTCError::OK();
2910}
2911
Steve Antondcc3c022017-12-22 16:02:54 -08002912RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2913PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002914 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002915 size_t mline_index,
2916 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002917 const ContentInfo* old_local_content,
2918 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002919 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002920 // If this is an offer then the m= section might be recycled. If the m=
2921 // section is being recycled (defined as: rejected in the current local or
2922 // remote description and not rejected in new description), dissociate the
2923 // currently associated RtpTransceiver by setting its mid property to null,
2924 // and discard the mapping between the transceiver and its m= section index.
2925 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2926 old_remote_content)) {
2927 // We want to dissociate the transceiver that has the rejected mid.
2928 const std::string& old_mid =
2929 (old_local_content && old_local_content->rejected)
2930 ? old_local_content->name
2931 : old_remote_content->name;
2932 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002933 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002934 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2935 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002936 old_transceiver->internal()->set_mid(absl::nullopt);
2937 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002938 }
2939 }
2940 const MediaContentDescription* media_desc = content.media_description();
2941 auto transceiver = GetAssociatedTransceiver(content.name);
2942 if (source == cricket::CS_LOCAL) {
2943 // Find the RtpTransceiver that corresponds to this m= section, using the
2944 // mapping between transceivers and m= section indices established when
2945 // creating the offer.
2946 if (!transceiver) {
2947 transceiver = GetTransceiverByMLineIndex(mline_index);
2948 }
2949 if (!transceiver) {
2950 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2951 "Unknown transceiver");
2952 }
2953 } else {
2954 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2955 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2956 // of the same type...
2957 if (!transceiver &&
2958 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2959 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2960 }
2961 // If no RtpTransceiver was found in the previous step, create one with a
2962 // recvonly direction.
2963 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002964 RTC_LOG(LS_INFO) << "Adding "
2965 << cricket::MediaTypeToString(media_desc->type())
2966 << " transceiver for MID=" << content.name
2967 << " at i=" << mline_index
2968 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002969 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002970 auto sender =
2971 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002972 std::string receiver_id;
2973 if (!media_desc->streams().empty()) {
2974 receiver_id = media_desc->streams()[0].id;
2975 } else {
2976 receiver_id = rtc::CreateRandomUuid();
2977 }
2978 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002979 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002980 transceiver->internal()->set_direction(
2981 RtpTransceiverDirection::kRecvOnly);
2982 }
2983 }
2984 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002985 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002986 LOG_AND_RETURN_ERROR(
2987 RTCErrorType::INVALID_PARAMETER,
2988 "Transceiver type does not match media description type.");
2989 }
2990 // Associate the found or created RtpTransceiver with the m= section by
2991 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2992 // section, and establish a mapping between the transceiver and the index of
2993 // the m= section.
2994 transceiver->internal()->set_mid(content.name);
2995 transceiver->internal()->set_mline_index(mline_index);
2996 return std::move(transceiver);
2997}
2998
2999rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3000PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3001 RTC_DCHECK(IsUnifiedPlan());
3002 for (auto transceiver : transceivers_) {
3003 if (transceiver->mid() == mid) {
3004 return transceiver;
3005 }
3006 }
3007 return nullptr;
3008}
3009
3010rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3011PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3012 RTC_DCHECK(IsUnifiedPlan());
3013 for (auto transceiver : transceivers_) {
3014 if (transceiver->internal()->mline_index() == mline_index) {
3015 return transceiver;
3016 }
3017 }
3018 return nullptr;
3019}
3020
3021rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3022PeerConnection::FindAvailableTransceiverToReceive(
3023 cricket::MediaType media_type) const {
3024 RTC_DCHECK(IsUnifiedPlan());
3025 // From JSEP section 5.10 (Applying a Remote Description):
3026 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3027 // the same type that were added to the PeerConnection by addTrack and are not
3028 // associated with any m= section and are not stopped, find the first such
3029 // RtpTransceiver.
3030 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003031 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003032 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3033 !transceiver->stopped()) {
3034 return transceiver;
3035 }
3036 }
3037 return nullptr;
3038}
3039
Steve Antoned10bd92017-12-05 10:52:59 -08003040const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3041 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3042 transceiver,
3043 const SessionDescriptionInterface* sdesc) const {
3044 RTC_DCHECK(transceiver);
3045 RTC_DCHECK(sdesc);
3046 if (IsUnifiedPlan()) {
3047 if (!transceiver->internal()->mid()) {
3048 // This transceiver is not associated with a media section yet.
3049 return nullptr;
3050 }
3051 return sdesc->description()->GetContentByName(
3052 *transceiver->internal()->mid());
3053 } else {
3054 // Plan B only allows at most one audio and one video section, so use the
3055 // first media section of that type.
3056 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003057 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003058 }
3059}
3060
deadbeef46c73892016-11-16 19:42:04 -08003061PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3062 return configuration_;
3063}
3064
deadbeef293e9262017-01-11 12:28:30 -08003065bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3066 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003067 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003068 if (IsClosed()) {
3069 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3070 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3071 }
3072
Qingsi Wanga2d60672018-04-11 16:57:45 -07003073 // According to JSEP, after setLocalDescription, changing the candidate pool
3074 // size is not allowed, and changing the set of ICE servers will not result
3075 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003076 if (local_description() && configuration.ice_candidate_pool_size !=
3077 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003078 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3079 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003080 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003081 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003082
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003083 if (local_description() &&
3084 configuration.use_media_transport != configuration_.use_media_transport) {
3085 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3086 "SetLocalDescription.";
3087 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3088 }
3089
3090 if (remote_description() &&
3091 configuration.use_media_transport != configuration_.use_media_transport) {
3092 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3093 "SetRemoteDescription.";
3094 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3095 }
3096
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003097 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003098 configuration.use_media_transport_for_data_channels !=
3099 configuration_.use_media_transport_for_data_channels) {
3100 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3101 "after calling SetLocalDescription.";
3102 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3103 }
3104
3105 if (remote_description() &&
3106 configuration.use_media_transport_for_data_channels !=
3107 configuration_.use_media_transport_for_data_channels) {
3108 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3109 "after calling SetRemoteDescription.";
3110 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3111 }
3112
3113 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003114 configuration.crypto_options != configuration_.crypto_options) {
3115 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3116 "SetLocalDescription.";
3117 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3118 }
3119
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003120 if (configuration.use_media_transport_for_data_channels ||
3121 configuration.use_media_transport) {
3122 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3123 << "Media transport requires MaxBundle policy.";
3124 }
3125
deadbeef293e9262017-01-11 12:28:30 -08003126 // The simplest (and most future-compatible) way to tell if the config was
3127 // modified in an invalid way is to copy each property we do support
3128 // modifying, then use operator==. There are far more properties we don't
3129 // support modifying than those we do, and more could be added.
3130 RTCConfiguration modified_config = configuration_;
3131 modified_config.servers = configuration.servers;
3132 modified_config.type = configuration.type;
3133 modified_config.ice_candidate_pool_size =
3134 configuration.ice_candidate_pool_size;
3135 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003136 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003137 modified_config.ice_check_interval_strong_connectivity =
3138 configuration.ice_check_interval_strong_connectivity;
3139 modified_config.ice_check_interval_weak_connectivity =
3140 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003141 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3142 modified_config.ice_unwritable_min_checks =
3143 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003144 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003145 modified_config.stun_candidate_keepalive_interval =
3146 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003147 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003148 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003149 modified_config.active_reset_srtp_params =
3150 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003151 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003152 modified_config.use_media_transport_for_data_channels =
3153 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003154 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003155 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003156 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3157 }
3158
Steve Anton038834f2017-07-14 15:59:59 -07003159 // Validate the modified configuration.
3160 RTCError validate_error = ValidateConfiguration(modified_config);
3161 if (!validate_error.ok()) {
3162 return SafeSetError(std::move(validate_error), error);
3163 }
3164
deadbeef293e9262017-01-11 12:28:30 -08003165 // Note that this isn't possible through chromium, since it's an unsigned
3166 // short in WebIDL.
3167 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003168 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003169 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3170 }
3171
3172 // Parse ICE servers before hopping to network thread.
3173 cricket::ServerAddresses stun_servers;
3174 std::vector<cricket::RelayServerConfig> turn_servers;
3175 RTCErrorType parse_error =
3176 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3177 if (parse_error != RTCErrorType::NONE) {
3178 return SafeSetError(parse_error, error);
3179 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003180 // Note if STUN or TURN servers were supplied.
3181 if (!stun_servers.empty()) {
3182 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3183 }
3184 if (!turn_servers.empty()) {
3185 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3186 }
deadbeef293e9262017-01-11 12:28:30 -08003187
3188 // In theory this shouldn't fail.
3189 if (!network_thread()->Invoke<bool>(
3190 RTC_FROM_HERE,
3191 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3192 stun_servers, turn_servers, modified_config.type,
3193 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003194 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003195 modified_config.turn_customizer,
3196 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003197 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003198 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3199 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003200
deadbeefd1a38b52016-12-10 13:15:33 -08003201 // As described in JSEP, calling setConfiguration with new ICE servers or
3202 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3203 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003204 if (modified_config.servers != configuration_.servers ||
3205 modified_config.type != configuration_.type ||
3206 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003207 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003208 }
skvladd1f5fda2017-02-03 16:54:05 -08003209
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003210 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003211 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003212 modified_config.use_media_transport ||
3213 modified_config.use_media_transport_for_data_channels
3214 ? factory_->media_transport_factory()
3215 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003216
Zhi Huangb57e1692018-06-12 11:41:11 -07003217 if (configuration_.active_reset_srtp_params !=
3218 modified_config.active_reset_srtp_params) {
3219 transport_controller_->SetActiveResetSrtpParams(
3220 modified_config.active_reset_srtp_params);
3221 }
3222
deadbeef293e9262017-01-11 12:28:30 -08003223 configuration_ = modified_config;
3224 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003225}
3226
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003227bool PeerConnection::AddIceCandidate(
3228 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003229 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003230 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003231 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003232 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003233 return false;
3234 }
Steve Antond25da372017-11-06 14:50:29 -08003235
3236 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003237 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003238 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003239 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003240 return false;
3241 }
3242
3243 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003244 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003245 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003246 return false;
3247 }
3248
3249 bool valid = false;
3250 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3251 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003252 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003253 return false;
3254 }
3255
3256 // Add this candidate to the remote session description.
3257 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003258 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003259 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003260 return false;
3261 }
3262
3263 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003264 bool result = UseCandidate(ice_candidate);
3265 if (result) {
3266 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3267 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3268 } else {
3269 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3270 }
3271 return result;
Steve Antond25da372017-11-06 14:50:29 -08003272 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003273 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003274 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003275 return true;
3276 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277}
3278
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003279bool PeerConnection::RemoveIceCandidates(
3280 const std::vector<cricket::Candidate>& candidates) {
3281 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003282 if (IsClosed()) {
3283 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3284 return false;
3285 }
3286
Steve Antond25da372017-11-06 14:50:29 -08003287 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003288 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3289 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003290 return false;
3291 }
3292
3293 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003294 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003295 return false;
3296 }
3297
3298 size_t number_removed =
3299 mutable_remote_description()->RemoveCandidates(candidates);
3300 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003301 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003302 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003303 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003304 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003305 }
3306
3307 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003308 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3309 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003310 RTC_LOG(LS_ERROR)
3311 << "RemoveIceCandidates: Error when removing remote candidates: "
3312 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003313 }
3314 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003315}
3316
Niels Möller0c4f7be2018-05-07 14:01:37 +02003317RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003318 if (!worker_thread()->IsCurrent()) {
3319 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003320 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003321 }
3322
Niels Möller0c4f7be2018-05-07 14:01:37 +02003323 const bool has_min = bitrate.min_bitrate_bps.has_value();
3324 const bool has_start = bitrate.start_bitrate_bps.has_value();
3325 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003326 if (has_min && *bitrate.min_bitrate_bps < 0) {
3327 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3328 "min_bitrate_bps <= 0");
3329 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003330 if (has_start) {
3331 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003332 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003333 "start_bitrate_bps < min_bitrate_bps");
3334 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003335 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3336 "curent_bitrate_bps < 0");
3337 }
3338 }
3339 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003340 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003341 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003342 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003343 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3345 "max_bitrate_bps < min_bitrate_bps");
3346 } else if (*bitrate.max_bitrate_bps < 0) {
3347 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3348 "max_bitrate_bps < 0");
3349 }
3350 }
3351
zstein4b979802017-06-02 14:37:37 -07003352 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003353 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003354
3355 return RTCError::OK();
3356}
3357
Alex Narest78609d52017-10-20 10:37:47 +02003358void PeerConnection::SetBitrateAllocationStrategy(
3359 std::unique_ptr<rtc::BitrateAllocationStrategy>
3360 bitrate_allocation_strategy) {
3361 rtc::Thread* worker_thread = factory_->worker_thread();
3362 if (!worker_thread->IsCurrent()) {
3363 rtc::BitrateAllocationStrategy* strategy_raw =
3364 bitrate_allocation_strategy.release();
3365 auto functor = [this, strategy_raw]() {
3366 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003367 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003368 };
3369 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3370 return;
3371 }
3372 RTC_DCHECK(call_.get());
3373 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3374}
3375
henrika5f6bf242017-11-01 11:06:56 +01003376void PeerConnection::SetAudioPlayout(bool playout) {
3377 if (!worker_thread()->IsCurrent()) {
3378 worker_thread()->Invoke<void>(
3379 RTC_FROM_HERE,
3380 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3381 return;
3382 }
3383 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003384 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003385 audio_state->SetPlayout(playout);
3386}
3387
3388void PeerConnection::SetAudioRecording(bool recording) {
3389 if (!worker_thread()->IsCurrent()) {
3390 worker_thread()->Invoke<void>(
3391 RTC_FROM_HERE,
3392 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3393 return;
3394 }
3395 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003396 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003397 audio_state->SetRecording(recording);
3398}
3399
Steve Anton8c0f7a72017-10-03 10:03:10 -07003400std::unique_ptr<rtc::SSLCertificate>
3401PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003402 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3403 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003404 return nullptr;
3405 }
Steve Antonf25303e2018-10-16 15:23:31 -07003406 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003407}
3408
Zhi Huang70b820f2018-01-27 14:16:15 -08003409std::unique_ptr<rtc::SSLCertChain>
3410PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003411 auto audio_transceiver = GetFirstAudioTransceiver();
3412 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003413 return nullptr;
3414 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003415 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003416 audio_transceiver->internal()->channel()->transport_name());
3417}
3418
3419rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3420PeerConnection::GetFirstAudioTransceiver() const {
3421 for (auto transceiver : transceivers_) {
3422 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3423 return transceiver;
3424 }
3425 }
3426 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003427}
3428
ivoc14d5dbe2016-07-04 07:06:55 -07003429bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3430 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003431 // TODO(eladalon): It would be better to not allow negative values into PC.
3432 const size_t max_size = (max_size_bytes < 0)
3433 ? RtcEventLog::kUnlimitedOutput
3434 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003435 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3436 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3437 output_period_ms = 5000;
3438 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003439 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003440 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003441 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003442}
3443
Bjorn Tereliusde939432017-11-20 17:38:14 +01003444bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3445 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003446 // TODO(eladalon): In C++14, this can be done with a lambda.
3447 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003448 bool operator()() {
3449 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3450 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003451 PeerConnection* const pc;
3452 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003453 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003454 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003455 return worker_thread()->Invoke<bool>(
3456 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003457}
3458
3459void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003460 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003461 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3462}
3463
Harald Alvestrandad88c882018-11-28 16:47:46 +01003464rtc::scoped_refptr<DtlsTransportInterface>
3465PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3466 return transport_controller_->LookupDtlsTransportByMid(mid);
3467}
3468
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003469rtc::scoped_refptr<DtlsTransport>
3470PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3471 return transport_controller_->LookupDtlsTransportByMid(mid);
3472}
3473
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003474const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003475 return pending_local_description_ ? pending_local_description_.get()
3476 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003477}
3478
3479const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003480 return pending_remote_description_ ? pending_remote_description_.get()
3481 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003482}
3483
deadbeeffe4a8a42016-12-20 17:56:17 -08003484const SessionDescriptionInterface* PeerConnection::current_local_description()
3485 const {
Steve Anton75737c02017-11-06 10:37:17 -08003486 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003487}
3488
3489const SessionDescriptionInterface* PeerConnection::current_remote_description()
3490 const {
Steve Anton75737c02017-11-06 10:37:17 -08003491 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003492}
3493
3494const SessionDescriptionInterface* PeerConnection::pending_local_description()
3495 const {
Steve Anton75737c02017-11-06 10:37:17 -08003496 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003497}
3498
3499const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3500 const {
Steve Anton75737c02017-11-06 10:37:17 -08003501 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003502}
3503
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003504void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003505 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506 // Update stats here so that we have the most recent stats for tracks and
3507 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003508 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003509
Steve Anton75737c02017-11-06 10:37:17 -08003510 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003511 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003512
Steve Anton8af21862017-12-15 11:20:13 -08003513 for (auto transceiver : transceivers_) {
3514 transceiver->Stop();
3515 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003516
3517 // Ensure that all asynchronous stats requests are completed before destroying
3518 // the transport controller below.
3519 if (stats_collector_) {
3520 stats_collector_->WaitForPendingRequest();
3521 }
3522
3523 // Don't destroy BaseChannels until after stats has been cleaned up so that
3524 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003525 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003526
Qingsi Wang93a84392018-01-30 17:13:09 -08003527 // The event log is used in the transport controller, which must be outlived
3528 // by the former. CreateOffer by the peer connection is implemented
3529 // asynchronously and if the peer connection is closed without resetting the
3530 // WebRTC session description factory, the session description factory would
3531 // call the transport controller.
3532 webrtc_session_desc_factory_.reset();
3533 transport_controller_.reset();
3534
deadbeef42a42632017-03-10 15:18:00 -08003535 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003536 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3537 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003538
Steve Anton978b8762017-09-29 12:15:02 -07003539 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003540 call_.reset();
3541 // The event log must outlive call (and any other object that uses it).
3542 event_log_.reset();
3543 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003544 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003545 // The .h file says that observer can be discarded after close() returns.
3546 // Make sure this is true.
3547 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003548}
3549
Steve Antonad182762018-09-05 20:22:40 +00003550void PeerConnection::OnMessage(rtc::Message* msg) {
3551 switch (msg->message_id) {
3552 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3553 SetSessionDescriptionMsg* param =
3554 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3555 param->observer->OnSuccess();
3556 delete param;
3557 break;
3558 }
3559 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3560 SetSessionDescriptionMsg* param =
3561 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3562 param->observer->OnFailure(std::move(param->error));
3563 delete param;
3564 break;
3565 }
3566 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3567 CreateSessionDescriptionMsg* param =
3568 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3569 param->observer->OnFailure(std::move(param->error));
3570 delete param;
3571 break;
3572 }
3573 case MSG_GETSTATS: {
3574 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3575 StatsReports reports;
3576 stats_->GetStats(param->track, &reports);
3577 param->observer->OnComplete(reports);
3578 delete param;
3579 break;
3580 }
3581 case MSG_FREE_DATACHANNELS: {
3582 sctp_data_channels_to_free_.clear();
3583 break;
3584 }
3585 case MSG_REPORT_USAGE_PATTERN: {
3586 ReportUsagePattern();
3587 break;
3588 }
3589 default:
3590 RTC_NOTREACHED() << "Not implemented";
3591 break;
3592 }
3593}
3594
Steve Antonafb0bb72018-02-20 11:35:37 -08003595cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3596 RTC_DCHECK(!IsUnifiedPlan());
3597 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3598 GetAudioTransceiver()->internal()->channel());
3599 if (voice_channel) {
3600 return voice_channel->media_channel();
3601 } else {
3602 return nullptr;
3603 }
3604}
3605
3606cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3607 RTC_DCHECK(!IsUnifiedPlan());
3608 auto* video_channel = static_cast<cricket::VideoChannel*>(
3609 GetVideoTransceiver()->internal()->channel());
3610 if (video_channel) {
3611 return video_channel->media_channel();
3612 } else {
3613 return nullptr;
3614 }
3615}
3616
Steve Anton4171afb2017-11-20 10:20:22 -08003617void PeerConnection::CreateAudioReceiver(
3618 MediaStreamInterface* stream,
3619 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003620 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3621 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003622 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3623 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003624 auto* audio_receiver = new AudioRtpReceiver(
3625 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003626 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003627 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3628 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3629 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003630 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003631 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003632 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003633}
3634
Steve Anton4171afb2017-11-20 10:20:22 -08003635void PeerConnection::CreateVideoReceiver(
3636 MediaStreamInterface* stream,
3637 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003638 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3639 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003640 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3641 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003642 auto* video_receiver = new VideoRtpReceiver(
3643 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003644 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003645 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3646 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3647 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003648 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003649 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003650 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003651}
3652
deadbeef70ab1a12015-09-28 16:53:55 -07003653// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3654// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003655rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003656 const RtpSenderInfo& remote_sender_info) {
3657 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3658 if (!receiver) {
3659 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3660 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003661 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003662 }
Steve Anton4171afb2017-11-20 10:20:22 -08003663 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3664 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3665 } else {
3666 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3667 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003668 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003669}
3670
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003671void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3672 MediaStreamInterface* stream) {
3673 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003674 RTC_DCHECK(track);
3675 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003676 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003677 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003678 // We already have a sender for this track, so just change the stream_id
3679 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003680 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003681 return;
3682 }
3683
3684 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003685 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003686 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003687 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003688 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003689 // If the sender has already been configured in SDP, we call SetSsrc,
3690 // which will connect the sender to the underlying transport. This can
3691 // occur if a local session description that contains the ID of the sender
3692 // is set before AddStream is called. It can also occur if the local
3693 // session description is not changed and RemoveStream is called, and
3694 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003695 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003696 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003697 if (sender_info) {
3698 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003699 }
3700}
3701
3702// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3703// indefinitely, when we have unified plan SDP.
3704void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3705 MediaStreamInterface* stream) {
3706 RTC_DCHECK(!IsClosed());
3707 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003708 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003709 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3710 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003711 return;
3712 }
Steve Anton4171afb2017-11-20 10:20:22 -08003713 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003714}
3715
3716void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3717 MediaStreamInterface* stream) {
3718 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003719 RTC_DCHECK(track);
3720 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003721 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003722 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003723 // We already have a sender for this track, so just change the stream_id
3724 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003725 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003726 return;
3727 }
3728
3729 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003730 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003731 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003732 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003733 GetVideoTransceiver()->internal()->AddSender(new_sender);
3734 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003735 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003736 if (sender_info) {
3737 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003738 }
3739}
3740
3741void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3742 MediaStreamInterface* stream) {
3743 RTC_DCHECK(!IsClosed());
3744 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003745 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003746 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3747 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003748 return;
3749 }
Steve Anton4171afb2017-11-20 10:20:22 -08003750 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003751}
3752
Steve Antonba818672017-11-06 10:21:57 -08003753void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003754 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003755 if (ice_connection_state_ == new_state) {
3756 return;
3757 }
3758
deadbeefcbecd352015-09-23 11:50:27 -07003759 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003760 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003761 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003762 return;
3763 }
Steve Antonba818672017-11-06 10:21:57 -08003764
Mirko Bonadei675513b2017-11-09 11:09:25 +01003765 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3766 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003767 RTC_DCHECK(ice_connection_state_ !=
3768 PeerConnectionInterface::kIceConnectionClosed);
3769
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003770 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003771 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003772}
3773
Alex Loiko9289eda2018-11-23 16:18:59 +00003774void PeerConnection::SetStandardizedIceConnectionState(
3775 PeerConnectionInterface::IceConnectionState new_state) {
3776 RTC_DCHECK(signaling_thread()->IsCurrent());
3777 if (standardized_ice_connection_state_ == new_state)
3778 return;
3779 if (IsClosed())
3780 return;
3781 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003782 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003783}
3784
Jonas Olsson635474e2018-10-18 15:58:17 +02003785void PeerConnection::SetConnectionState(
3786 PeerConnectionInterface::PeerConnectionState new_state) {
3787 RTC_DCHECK(signaling_thread()->IsCurrent());
3788 if (connection_state_ == new_state)
3789 return;
3790 if (IsClosed())
3791 return;
3792 connection_state_ = new_state;
3793 Observer()->OnConnectionChange(new_state);
3794}
3795
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003796void PeerConnection::OnIceGatheringChange(
3797 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003798 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003799 if (IsClosed()) {
3800 return;
3801 }
3802 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003803 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003804}
3805
jbauch81bf7b02017-03-25 08:31:12 -07003806void PeerConnection::OnIceCandidate(
3807 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003808 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003809 if (IsClosed()) {
3810 return;
3811 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003812 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003813 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3814 candidate->candidate().address().IsPrivateIP()) {
3815 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3816 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003817 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003818}
3819
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003820void PeerConnection::OnIceCandidatesRemoved(
3821 const std::vector<cricket::Candidate>& candidates) {
3822 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003823 if (IsClosed()) {
3824 return;
3825 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003826 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003827}
3828
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003829void PeerConnection::ChangeSignalingState(
3830 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003831 RTC_DCHECK(signaling_thread()->IsCurrent());
3832 if (signaling_state_ == signaling_state) {
3833 return;
3834 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003835 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3836 << GetSignalingStateString(signaling_state_)
3837 << " New state: "
3838 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003839 signaling_state_ = signaling_state;
3840 if (signaling_state == kClosed) {
3841 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003842 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003843 standardized_ice_connection_state_ =
3844 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003845 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3846 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003847 if (ice_gathering_state_ != kIceGatheringComplete) {
3848 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003849 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003850 }
3851 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003852 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003853}
3854
deadbeefeb459812015-12-15 19:24:43 -08003855void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3856 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003857 if (IsClosed()) {
3858 return;
3859 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003860 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003861 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003862}
3863
deadbeefeb459812015-12-15 19:24:43 -08003864void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3865 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003866 if (IsClosed()) {
3867 return;
3868 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003869 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003870 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003871}
3872
3873void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3874 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003875 if (IsClosed()) {
3876 return;
3877 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003878 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003879 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003880}
3881
3882void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3883 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003884 if (IsClosed()) {
3885 return;
3886 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003887 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003888 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003889}
3890
Henrik Boström31638672017-11-23 17:48:32 +01003891void PeerConnection::PostSetSessionDescriptionSuccess(
3892 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003893 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3894 signaling_thread()->Post(RTC_FROM_HERE, this,
3895 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003896}
3897
deadbeefab9b2d12015-10-14 11:33:11 -07003898void PeerConnection::PostSetSessionDescriptionFailure(
3899 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003900 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003901 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003902 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3903 msg->error = std::move(error);
3904 signaling_thread()->Post(RTC_FROM_HERE, this,
3905 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003906}
3907
3908void PeerConnection::PostCreateSessionDescriptionFailure(
3909 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003910 RTCError error) {
3911 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003912 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3913 msg->error = std::move(error);
3914 signaling_thread()->Post(RTC_FROM_HERE, this,
3915 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003916}
3917
zhihuang1c378ed2017-08-17 14:10:50 -07003918void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003919 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003920 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003921 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003922
Steve Antondcc3c022017-12-22 16:02:54 -08003923 if (IsUnifiedPlan()) {
3924 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3925 } else {
3926 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3927 }
3928
Steve Antonfa2260d2017-12-28 16:38:23 -08003929 // Intentionally unset the data channel type for RTP data channel with the
3930 // second condition. Otherwise the RTP data channels would be successfully
3931 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3932 // when building with chromium. We want to leave RTP data channels broken, so
3933 // people won't try to use them.
3934 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3935 session_options->data_channel_type = data_channel_type();
3936 }
3937
Steve Antondcc3c022017-12-22 16:02:54 -08003938 // Apply ICE restart flag and renomination flag.
3939 for (auto& options : session_options->media_description_options) {
3940 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3941 options.transport_options.enable_ice_renomination =
3942 configuration_.enable_ice_renomination;
3943 }
3944
3945 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003946 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003947 session_options->pooled_ice_credentials =
3948 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3949 RTC_FROM_HERE,
3950 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3951 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003952 session_options->offer_extmap_allow_mixed =
3953 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003954}
3955
3956void PeerConnection::GetOptionsForPlanBOffer(
3957 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3958 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003959 // Figure out transceiver directional preferences.
3960 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3961 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3962
3963 // By default, generate sendrecv/recvonly m= sections.
3964 bool recv_audio = true;
3965 bool recv_video = true;
3966
3967 // By default, only offer a new m= section if we have media to send with it.
3968 bool offer_new_audio_description = send_audio;
3969 bool offer_new_video_description = send_video;
3970 bool offer_new_data_description = HasDataChannels();
3971
3972 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003973 if (offer_answer_options.offer_to_receive_audio !=
3974 RTCOfferAnswerOptions::kUndefined) {
3975 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003976 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003977 offer_new_audio_description ||
3978 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003979 }
Steve Antondcc3c022017-12-22 16:02:54 -08003980 if (offer_answer_options.offer_to_receive_video !=
3981 RTCOfferAnswerOptions::kUndefined) {
3982 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003983 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003984 offer_new_video_description ||
3985 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003986 }
3987
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003988 absl::optional<size_t> audio_index;
3989 absl::optional<size_t> video_index;
3990 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003991 // If a current description exists, generate m= sections in the same order,
3992 // using the first audio/video/data section that appears and rejecting
3993 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003994 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003995 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003996 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003997 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3998 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3999 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004000 }
4001
zhihuang1c378ed2017-08-17 14:10:50 -07004002 // Add audio/video/data m= sections to the end if needed.
4003 if (!audio_index && offer_new_audio_description) {
4004 session_options->media_description_options.push_back(
4005 cricket::MediaDescriptionOptions(
4006 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004007 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4008 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004009 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004010 }
zhihuang1c378ed2017-08-17 14:10:50 -07004011 if (!video_index && offer_new_video_description) {
4012 session_options->media_description_options.push_back(
4013 cricket::MediaDescriptionOptions(
4014 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004015 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4016 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004017 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004018 }
zhihuang1c378ed2017-08-17 14:10:50 -07004019 if (!data_index && offer_new_data_description) {
4020 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004021 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004022 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004023 }
4024
4025 cricket::MediaDescriptionOptions* audio_media_description_options =
4026 !audio_index ? nullptr
4027 : &session_options->media_description_options[*audio_index];
4028 cricket::MediaDescriptionOptions* video_media_description_options =
4029 !video_index ? nullptr
4030 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004031
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004032 AddPlanBRtpSenderOptions(GetSendersInternal(),
4033 audio_media_description_options,
4034 video_media_description_options,
4035 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004036}
4037
Steve Antondcc3c022017-12-22 16:02:54 -08004038static cricket::MediaDescriptionOptions
4039GetMediaDescriptionOptionsForTransceiver(
4040 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4041 transceiver,
4042 const std::string& mid) {
4043 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004044 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004045 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004046 // This behavior is specified in JSEP. The gist is that:
4047 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4048 // sendrecv.
4049 // 2. If the MSID is included, then it must be included in any subsequent
4050 // offer/answer exactly the same until the RtpTransceiver is stopped.
4051 if (!transceiver->stopped() &&
4052 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
4053 transceiver->internal()->has_ever_been_used_to_send())) {
4054 cricket::SenderOptions sender_options;
4055 sender_options.track_id = transceiver->sender()->id();
4056 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02004057 int num_send_encoding_layers =
4058 transceiver->sender()->init_send_encodings().size();
4059 sender_options.num_sim_layers =
4060 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08004061 media_description_options.sender_options.push_back(sender_options);
4062 }
Steve Antondcc3c022017-12-22 16:02:54 -08004063 return media_description_options;
4064}
4065
Steve Anton5c72e712018-12-10 14:25:30 -08004066// Returns the ContentInfo at mline index |i|, or null if none exists.
4067static const ContentInfo* GetContentByIndex(
4068 const SessionDescriptionInterface* sdesc,
4069 size_t i) {
4070 if (!sdesc) {
4071 return nullptr;
4072 }
4073 const ContentInfos& contents = sdesc->description()->contents();
4074 return (i < contents.size() ? &contents[i] : nullptr);
4075}
4076
Steve Antondcc3c022017-12-22 16:02:54 -08004077void PeerConnection::GetOptionsForUnifiedPlanOffer(
4078 const RTCOfferAnswerOptions& offer_answer_options,
4079 cricket::MediaSessionOptions* session_options) {
4080 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4081 // Offers) and 5.2.2 (Subsequent Offers).
4082 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4083 const ContentInfos& local_contents =
4084 (local_description() ? local_description()->description()->contents()
4085 : ContentInfos());
4086 const ContentInfos& remote_contents =
4087 (remote_description() ? remote_description()->description()->contents()
4088 : ContentInfos());
4089 // The mline indices that can be recycled. New transceivers should reuse these
4090 // slots first.
4091 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004092 // First, go through each media section that exists in either the local or
4093 // remote description and generate a media section in this offer for the
4094 // associated transceiver. If a media section can be recycled, generate a
4095 // default, rejected media section here that can be later overwritten.
4096 for (size_t i = 0;
4097 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4098 // Either |local_content| or |remote_content| is non-null.
4099 const ContentInfo* local_content =
4100 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004101 const ContentInfo* current_local_content =
4102 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004103 const ContentInfo* remote_content =
4104 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004105 const ContentInfo* current_remote_content =
4106 GetContentByIndex(current_remote_description(), i);
4107 bool had_been_rejected =
4108 (current_local_content && current_local_content->rejected) ||
4109 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004110 const std::string& mid =
4111 (local_content ? local_content->name : remote_content->name);
4112 cricket::MediaType media_type =
4113 (local_content ? local_content->media_description()->type()
4114 : remote_content->media_description()->type());
4115 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4116 media_type == cricket::MEDIA_TYPE_VIDEO) {
4117 auto transceiver = GetAssociatedTransceiver(mid);
4118 RTC_CHECK(transceiver);
4119 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004120 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004121 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004122 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004123 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4124 RtpTransceiverDirection::kInactive,
4125 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004126 recycleable_mline_indices.push(i);
4127 } else {
4128 session_options->media_description_options.push_back(
4129 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4130 // CreateOffer shouldn't really cause any state changes in
4131 // PeerConnection, but we need a way to match new transceivers to new
4132 // media sections in SetLocalDescription and JSEP specifies this is done
4133 // by recording the index of the media section generated for the
4134 // transceiver in the offer.
4135 transceiver->internal()->set_mline_index(i);
4136 }
4137 } else {
4138 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004139 RTC_CHECK(GetDataMid());
4140 if (had_been_rejected || mid != *GetDataMid()) {
4141 session_options->media_description_options.push_back(
4142 GetMediaDescriptionOptionsForRejectedData(mid));
4143 } else {
4144 session_options->media_description_options.push_back(
4145 GetMediaDescriptionOptionsForActiveData(mid));
4146 }
Steve Antondcc3c022017-12-22 16:02:54 -08004147 }
4148 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004149
Steve Antondcc3c022017-12-22 16:02:54 -08004150 // Next, look for transceivers that are newly added (that is, are not stopped
4151 // and not associated). Reuse media sections marked as recyclable first,
4152 // otherwise append to the end of the offer. New media sections should be
4153 // added in the order they were added to the PeerConnection.
4154 for (auto transceiver : transceivers_) {
4155 if (transceiver->mid() || transceiver->stopped()) {
4156 continue;
4157 }
4158 size_t mline_index;
4159 if (!recycleable_mline_indices.empty()) {
4160 mline_index = recycleable_mline_indices.front();
4161 recycleable_mline_indices.pop();
4162 session_options->media_description_options[mline_index] =
4163 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004164 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004165 } else {
4166 mline_index = session_options->media_description_options.size();
4167 session_options->media_description_options.push_back(
4168 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004169 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004170 }
4171 // See comment above for why CreateOffer changes the transceiver's state.
4172 transceiver->internal()->set_mline_index(mline_index);
4173 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004174 // Lastly, add a m-section if we have local data channels and an m section
4175 // does not already exist.
4176 if (!GetDataMid() && HasDataChannels()) {
4177 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004178 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004179 }
Steve Antondcc3c022017-12-22 16:02:54 -08004180}
4181
4182void PeerConnection::GetOptionsForAnswer(
4183 const RTCOfferAnswerOptions& offer_answer_options,
4184 cricket::MediaSessionOptions* session_options) {
4185 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4186
4187 if (IsUnifiedPlan()) {
4188 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4189 } else {
4190 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4191 }
4192
Steve Antonfa2260d2017-12-28 16:38:23 -08004193 // Intentionally unset the data channel type for RTP data channel. Otherwise
4194 // the RTP data channels would be successfully negotiated by default and the
4195 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4196 // We want to leave RTP data channels broken, so people won't try to use them.
4197 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4198 session_options->data_channel_type = data_channel_type();
4199 }
4200
Steve Antondcc3c022017-12-22 16:02:54 -08004201 // Apply ICE renomination flag.
4202 for (auto& options : session_options->media_description_options) {
4203 options.transport_options.enable_ice_renomination =
4204 configuration_.enable_ice_renomination;
4205 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004206
4207 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004208 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004209 session_options->pooled_ice_credentials =
4210 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4211 RTC_FROM_HERE,
4212 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4213 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004214}
4215
Steve Antondcc3c022017-12-22 16:02:54 -08004216void PeerConnection::GetOptionsForPlanBAnswer(
4217 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004218 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004219 // Figure out transceiver directional preferences.
4220 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4221 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4222
4223 // By default, generate sendrecv/recvonly m= sections. The direction is also
4224 // restricted by the direction in the offer.
4225 bool recv_audio = true;
4226 bool recv_video = true;
4227
4228 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004229 if (offer_answer_options.offer_to_receive_audio !=
4230 RTCOfferAnswerOptions::kUndefined) {
4231 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004232 }
Steve Antondcc3c022017-12-22 16:02:54 -08004233 if (offer_answer_options.offer_to_receive_video !=
4234 RTCOfferAnswerOptions::kUndefined) {
4235 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004236 }
4237
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004238 absl::optional<size_t> audio_index;
4239 absl::optional<size_t> video_index;
4240 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004241
4242 // Generate m= sections that match those in the offer.
4243 // Note that mediasession.cc will handle intersection our preferred
4244 // direction with the offered direction.
4245 GenerateMediaDescriptionOptions(
4246 remote_description(),
4247 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4248 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4249 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004250
4251 cricket::MediaDescriptionOptions* audio_media_description_options =
4252 !audio_index ? nullptr
4253 : &session_options->media_description_options[*audio_index];
4254 cricket::MediaDescriptionOptions* video_media_description_options =
4255 !video_index ? nullptr
4256 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004257
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004258 AddPlanBRtpSenderOptions(GetSendersInternal(),
4259 audio_media_description_options,
4260 video_media_description_options,
4261 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004262}
zhihuangaf388472016-11-02 16:49:48 -07004263
Steve Antondcc3c022017-12-22 16:02:54 -08004264void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4265 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4266 cricket::MediaSessionOptions* session_options) {
4267 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4268 // Answers) and 5.3.2 (Subsequent Answers).
4269 RTC_DCHECK(remote_description());
4270 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4271 for (const ContentInfo& content :
4272 remote_description()->description()->contents()) {
4273 cricket::MediaType media_type = content.media_description()->type();
4274 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4275 media_type == cricket::MEDIA_TYPE_VIDEO) {
4276 auto transceiver = GetAssociatedTransceiver(content.name);
4277 RTC_CHECK(transceiver);
4278 session_options->media_description_options.push_back(
4279 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4280 } else {
4281 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004282 // Reject all data sections if data channels are disabled.
4283 // Reject a data section if it has already been rejected.
4284 // Reject all data sections except for the first one.
4285 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4286 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004287 session_options->media_description_options.push_back(
4288 GetMediaDescriptionOptionsForRejectedData(content.name));
4289 } else {
4290 session_options->media_description_options.push_back(
4291 GetMediaDescriptionOptionsForActiveData(content.name));
4292 }
Steve Antondcc3c022017-12-22 16:02:54 -08004293 }
4294 }
htaa2a49d92016-03-04 02:51:39 -08004295}
4296
zhihuang1c378ed2017-08-17 14:10:50 -07004297void PeerConnection::GenerateMediaDescriptionOptions(
4298 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004299 RtpTransceiverDirection audio_direction,
4300 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004301 absl::optional<size_t>* audio_index,
4302 absl::optional<size_t>* video_index,
4303 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004304 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004305 for (const cricket::ContentInfo& content :
4306 session_desc->description()->contents()) {
4307 if (IsAudioContent(&content)) {
4308 // If we already have an audio m= section, reject this extra one.
4309 if (*audio_index) {
4310 session_options->media_description_options.push_back(
4311 cricket::MediaDescriptionOptions(
4312 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004313 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004314 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004315 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004316 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004317 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4318 content.name, audio_direction,
4319 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004320 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004321 }
4322 } else if (IsVideoContent(&content)) {
4323 // If we already have an video m= section, reject this extra one.
4324 if (*video_index) {
4325 session_options->media_description_options.push_back(
4326 cricket::MediaDescriptionOptions(
4327 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004328 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004329 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004330 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004331 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004332 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4333 content.name, video_direction,
4334 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004335 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004336 }
4337 } else {
4338 RTC_DCHECK(IsDataContent(&content));
4339 // If we already have an data m= section, reject this extra one.
4340 if (*data_index) {
4341 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004342 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004343 } else {
4344 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004345 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004346 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004347 }
4348 }
htaa2a49d92016-03-04 02:51:39 -08004349 }
deadbeefab9b2d12015-10-14 11:33:11 -07004350}
4351
Steve Antonfa2260d2017-12-28 16:38:23 -08004352cricket::MediaDescriptionOptions
4353PeerConnection::GetMediaDescriptionOptionsForActiveData(
4354 const std::string& mid) const {
4355 // Direction for data sections is meaningless, but legacy endpoints might
4356 // expect sendrecv.
4357 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4358 RtpTransceiverDirection::kSendRecv,
4359 /*stopped=*/false);
4360 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4361 return options;
4362}
4363
4364cricket::MediaDescriptionOptions
4365PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4366 const std::string& mid) const {
4367 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4368 RtpTransceiverDirection::kInactive,
4369 /*stopped=*/true);
4370 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4371 return options;
4372}
4373
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004374absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004375 switch (data_channel_type_) {
4376 case cricket::DCT_RTP:
4377 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004378 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004379 }
4380 return rtp_data_channel_->content_name();
4381 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004382 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004383 case cricket::DCT_MEDIA_TRANSPORT:
4384 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004385 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004386 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004387 }
4388}
4389
Steve Anton4171afb2017-11-20 10:20:22 -08004390void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4391 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4392 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004393 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004394}
4395
Steve Anton4171afb2017-11-20 10:20:22 -08004396void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004397 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004398 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004399 cricket::MediaType media_type,
4400 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004401 RTC_DCHECK(!IsUnifiedPlan());
4402
Steve Anton4171afb2017-11-20 10:20:22 -08004403 std::vector<RtpSenderInfo>* current_senders =
4404 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004405
Steve Anton4171afb2017-11-20 10:20:22 -08004406 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004407 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004408 for (auto sender_it = current_senders->begin();
4409 sender_it != current_senders->end();
4410 /* incremented manually */) {
4411 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004412 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004413 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004414 std::string params_stream_id;
4415 if (params) {
4416 params_stream_id =
4417 (!params->first_stream_id().empty() ? params->first_stream_id()
4418 : kDefaultStreamId);
4419 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004420 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004421 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004422 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004423 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004424 sender_exists) {
4425 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004426 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004427 OnRemoteSenderRemoved(info, media_type);
4428 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004429 }
4430 }
4431
Steve Anton4171afb2017-11-20 10:20:22 -08004432 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004433 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004434 if (!params.has_ssrcs()) {
4435 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4436 // sender, this means it is coming from a Unified Plan endpoint,so we just
4437 // create a default.
4438 default_sender_needed = true;
4439 break;
4440 }
4441
Seth Hampson845e8782018-03-02 11:34:10 -08004442 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004443 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004444 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4445 // not supported in Plan B, we just take the first here and create the
4446 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004447 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004448 (!params.first_stream_id().empty() ? params.first_stream_id()
4449 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004450 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004451 uint32_t ssrc = params.first_ssrc();
4452
4453 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004454 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004455 if (!stream) {
4456 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004457 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004458 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004459 remote_streams_->AddStream(stream);
4460 new_streams->AddStream(stream);
4461 }
4462
Steve Anton4171afb2017-11-20 10:20:22 -08004463 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004464 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004465 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004466 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004467 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004468 }
4469 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004470
Steve Anton4171afb2017-11-20 10:20:22 -08004471 // Add default sender if necessary.
4472 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004473 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004474 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004475 if (!default_stream) {
4476 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004477 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004478 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004479 remote_streams_->AddStream(default_stream);
4480 new_streams->AddStream(default_stream);
4481 }
Steve Anton4171afb2017-11-20 10:20:22 -08004482 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4483 ? kDefaultAudioSenderId
4484 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004485 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004486 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004487 if (!default_sender_info) {
4488 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004489 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004490 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004491 }
4492 }
deadbeefab9b2d12015-10-14 11:33:11 -07004493}
4494
Steve Anton4171afb2017-11-20 10:20:22 -08004495void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4496 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004497 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4498 << " receiver for track_id=" << sender_info.sender_id
4499 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004500
Steve Anton3d954a62018-04-02 11:27:23 -07004501 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004502 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004503 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004504 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004505 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004506 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004507 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004508 }
4509}
4510
Steve Anton4171afb2017-11-20 10:20:22 -08004511void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4512 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004513 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4514 << " receiver for track_id=" << sender_info.sender_id
4515 << " and stream_id=" << sender_info.stream_id;
4516
Seth Hampson845e8782018-03-02 11:34:10 -08004517 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004518
Henrik Boström933d8b02017-10-10 10:05:16 -07004519 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004520 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004521 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4522 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004523 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004524 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004525 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004526 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004527 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004528 }
4529 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004530 // Stopping or destroying a VideoRtpReceiver will end the
4531 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004532 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004533 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004534 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004535 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004536 // There's no guarantee the track is still available, e.g. the track may
4537 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004538 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004539 }
4540 } else {
nisseede5da42017-01-12 05:15:36 -08004541 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004542 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004543 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004544 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004545 }
deadbeefab9b2d12015-10-14 11:33:11 -07004546}
4547
4548void PeerConnection::UpdateEndedRemoteMediaStreams() {
4549 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4550 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4551 MediaStreamInterface* stream = remote_streams_->at(i);
4552 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4553 streams_to_remove.push_back(stream);
4554 }
4555 }
4556
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004557 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004558 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004559 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004560 }
4561}
4562
Steve Anton4171afb2017-11-20 10:20:22 -08004563void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004564 const std::vector<cricket::StreamParams>& streams,
4565 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004566 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004567
Seth Hampson845e8782018-03-02 11:34:10 -08004568 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004569 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004570 for (auto sender_it = current_senders->begin();
4571 sender_it != current_senders->end();
4572 /* incremented manually */) {
4573 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004574 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004575 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4576 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004577 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004578 OnLocalSenderRemoved(info, media_type);
4579 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004580 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004581 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004582 }
4583 }
4584
Steve Anton4171afb2017-11-20 10:20:22 -08004585 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004586 for (const cricket::StreamParams& params : streams) {
4587 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004588 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004589 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004590 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004591 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004592 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004593 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004594 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004595 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004596 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004597 }
4598 }
4599}
4600
Steve Anton4171afb2017-11-20 10:20:22 -08004601void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4602 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004603 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004604 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004605 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004606 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4607 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004608 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004609 return;
4610 }
4611
deadbeeffac06552015-11-25 11:26:01 -08004612 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004613 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004614 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004615 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004616 }
deadbeeffac06552015-11-25 11:26:01 -08004617
Seth Hampson5b4f0752018-04-02 16:31:36 -07004618 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004619 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004620}
4621
Steve Anton4171afb2017-11-20 10:20:22 -08004622void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4623 cricket::MediaType media_type) {
4624 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004625 if (!sender) {
4626 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004627 // SessionDescriptions has been renegotiated.
4628 return;
4629 }
deadbeeffac06552015-11-25 11:26:01 -08004630
4631 // A sender has been removed from the SessionDescription but it's still
4632 // associated with the PeerConnection. This only occurs if the SDP doesn't
4633 // match with the calls to CreateSender, AddStream and RemoveStream.
4634 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004635 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004636 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004637 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004638 }
deadbeeffac06552015-11-25 11:26:01 -08004639
Steve Anton4171afb2017-11-20 10:20:22 -08004640 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004641}
4642
4643void PeerConnection::UpdateLocalRtpDataChannels(
4644 const cricket::StreamParamsVec& streams) {
4645 std::vector<std::string> existing_channels;
4646
4647 // Find new and active data channels.
4648 for (const cricket::StreamParams& params : streams) {
4649 // |it->sync_label| is actually the data channel label. The reason is that
4650 // we use the same naming of data channels as we do for
4651 // MediaStreams and Tracks.
4652 // For MediaStreams, the sync_label is the MediaStream label and the
4653 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004654 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004655 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004656 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004657 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004658 continue;
4659 }
4660 // Set the SSRC the data channel should use for sending.
4661 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4662 existing_channels.push_back(data_channel_it->first);
4663 }
4664
4665 UpdateClosingRtpDataChannels(existing_channels, true);
4666}
4667
4668void PeerConnection::UpdateRemoteRtpDataChannels(
4669 const cricket::StreamParamsVec& streams) {
4670 std::vector<std::string> existing_channels;
4671
4672 // Find new and active data channels.
4673 for (const cricket::StreamParams& params : streams) {
4674 // The data channel label is either the mslabel or the SSRC if the mslabel
4675 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004676 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004677 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004678 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004679 auto data_channel_it = rtp_data_channels_.find(label);
4680 if (data_channel_it == rtp_data_channels_.end()) {
4681 // This is a new data channel.
4682 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4683 } else {
4684 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4685 }
4686 existing_channels.push_back(label);
4687 }
4688
4689 UpdateClosingRtpDataChannels(existing_channels, false);
4690}
4691
4692void PeerConnection::UpdateClosingRtpDataChannels(
4693 const std::vector<std::string>& active_channels,
4694 bool is_local_update) {
4695 auto it = rtp_data_channels_.begin();
4696 while (it != rtp_data_channels_.end()) {
4697 DataChannel* data_channel = it->second;
4698 if (std::find(active_channels.begin(), active_channels.end(),
4699 data_channel->label()) != active_channels.end()) {
4700 ++it;
4701 continue;
4702 }
4703
4704 if (is_local_update) {
4705 data_channel->SetSendSsrc(0);
4706 } else {
4707 data_channel->RemotePeerRequestClose();
4708 }
4709
4710 if (data_channel->state() == DataChannel::kClosed) {
4711 rtp_data_channels_.erase(it);
4712 it = rtp_data_channels_.begin();
4713 } else {
4714 ++it;
4715 }
4716 }
4717}
4718
4719void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4720 uint32_t remote_ssrc) {
4721 rtc::scoped_refptr<DataChannel> channel(
4722 InternalCreateDataChannel(label, nullptr));
4723 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004724 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004725 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004726 return;
4727 }
4728 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004729 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4730 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004731 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004732}
4733
4734rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4735 const std::string& label,
4736 const InternalDataChannelInit* config) {
4737 if (IsClosed()) {
4738 return nullptr;
4739 }
Steve Anton75737c02017-11-06 10:37:17 -08004740 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004741 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004742 << "InternalCreateDataChannel: Data is not supported in this call.";
4743 return nullptr;
4744 }
4745 InternalDataChannelInit new_config =
4746 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004747 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004748 if (new_config.id < 0) {
4749 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004750 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004751 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004752 RTC_LOG(LS_ERROR)
4753 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004754 return nullptr;
4755 }
4756 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004757 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004758 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004759 return nullptr;
4760 }
4761 }
4762
Steve Anton75737c02017-11-06 10:37:17 -08004763 rtc::scoped_refptr<DataChannel> channel(
4764 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004765 if (!channel) {
4766 sid_allocator_.ReleaseSid(new_config.id);
4767 return nullptr;
4768 }
4769
4770 if (channel->data_channel_type() == cricket::DCT_RTP) {
4771 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004772 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4773 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004774 return nullptr;
4775 }
4776 rtp_data_channels_[channel->label()] = channel;
4777 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004778 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004779 sctp_data_channels_.push_back(channel);
4780 channel->SignalClosed.connect(this,
4781 &PeerConnection::OnSctpDataChannelClosed);
4782 }
4783
Steve Anton2d8609c2018-01-23 16:38:46 -08004784 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004785 return channel;
4786}
4787
4788bool PeerConnection::HasDataChannels() const {
4789 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4790}
4791
4792void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4793 for (const auto& channel : sctp_data_channels_) {
4794 if (channel->id() < 0) {
4795 int sid;
4796 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004797 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004798 continue;
4799 }
4800 channel->SetSctpSid(sid);
4801 }
4802 }
4803}
4804
4805void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004806 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004807 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4808 ++it) {
4809 if (it->get() == channel) {
4810 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004811 // After the closing procedure is done, it's safe to use this ID for
4812 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004813 sid_allocator_.ReleaseSid(channel->id());
4814 }
deadbeefbd292462015-12-14 18:15:29 -08004815 // Since this method is triggered by a signal from the DataChannel,
4816 // we can't free it directly here; we need to free it asynchronously.
4817 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004818 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004819 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4820 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004821 return;
4822 }
4823 }
4824}
4825
deadbeefab9b2d12015-10-14 11:33:11 -07004826void PeerConnection::OnDataChannelDestroyed() {
4827 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4828 // DataChannel may callback to us and try to modify the list.
4829 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4830 temp_rtp_dcs.swap(rtp_data_channels_);
4831 for (const auto& kv : temp_rtp_dcs) {
4832 kv.second->OnTransportChannelDestroyed();
4833 }
4834
4835 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4836 temp_sctp_dcs.swap(sctp_data_channels_);
4837 for (const auto& channel : temp_sctp_dcs) {
4838 channel->OnTransportChannelDestroyed();
4839 }
4840}
4841
4842void PeerConnection::OnDataChannelOpenMessage(
4843 const std::string& label,
4844 const InternalDataChannelInit& config) {
4845 rtc::scoped_refptr<DataChannel> channel(
4846 InternalCreateDataChannel(label, &config));
4847 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004848 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004849 return;
4850 }
4851
deadbeefa601f5c2016-06-06 14:27:39 -07004852 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4853 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004854 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004855 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004856}
4857
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004858bool PeerConnection::HandleOpenMessage_s(
4859 const cricket::ReceiveDataParams& params,
4860 const rtc::CopyOnWriteBuffer& buffer) {
4861 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4862 // Received OPEN message; parse and signal that a new data channel should
4863 // be created.
4864 std::string label;
4865 InternalDataChannelInit config;
4866 config.id = params.ssrc;
4867 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4868 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4869 << params.ssrc;
4870 return true;
4871 }
4872 config.open_handshake_role = InternalDataChannelInit::kAcker;
4873 OnDataChannelOpenMessage(label, config);
4874 return true;
4875 }
4876 return false;
4877}
4878
Steve Anton4171afb2017-11-20 10:20:22 -08004879rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4880PeerConnection::GetAudioTransceiver() const {
4881 // This method only works with Plan B SDP, where there is a single
4882 // audio/video transceiver.
4883 RTC_DCHECK(!IsUnifiedPlan());
4884 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004885 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004886 return transceiver;
4887 }
4888 }
4889 RTC_NOTREACHED();
4890 return nullptr;
4891}
4892
4893rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4894PeerConnection::GetVideoTransceiver() const {
4895 // This method only works with Plan B SDP, where there is a single
4896 // audio/video transceiver.
4897 RTC_DCHECK(!IsUnifiedPlan());
4898 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004899 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004900 return transceiver;
4901 }
4902 }
4903 RTC_NOTREACHED();
4904 return nullptr;
4905}
4906
4907// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4908// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004909bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004910 switch (type) {
4911 case cricket::MEDIA_TYPE_AUDIO:
4912 return !GetAudioTransceiver()->internal()->senders().empty();
4913 case cricket::MEDIA_TYPE_VIDEO:
4914 return !GetVideoTransceiver()->internal()->senders().empty();
4915 case cricket::MEDIA_TYPE_DATA:
4916 return false;
4917 }
4918 RTC_NOTREACHED();
4919 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004920}
4921
Steve Anton4171afb2017-11-20 10:20:22 -08004922rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4923PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4924 for (auto transceiver : transceivers_) {
4925 for (auto sender : transceiver->internal()->senders()) {
4926 if (sender->track() == track) {
4927 return sender;
4928 }
4929 }
4930 }
4931 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004932}
4933
Steve Anton4171afb2017-11-20 10:20:22 -08004934rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4935PeerConnection::FindSenderById(const std::string& sender_id) const {
4936 for (auto transceiver : transceivers_) {
4937 for (auto sender : transceiver->internal()->senders()) {
4938 if (sender->id() == sender_id) {
4939 return sender;
4940 }
4941 }
4942 }
4943 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004944}
4945
Steve Anton4171afb2017-11-20 10:20:22 -08004946rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4947PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4948 for (auto transceiver : transceivers_) {
4949 for (auto receiver : transceiver->internal()->receivers()) {
4950 if (receiver->id() == receiver_id) {
4951 return receiver;
4952 }
4953 }
4954 }
4955 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004956}
4957
Steve Anton4171afb2017-11-20 10:20:22 -08004958std::vector<PeerConnection::RtpSenderInfo>*
4959PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4960 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4961 media_type == cricket::MEDIA_TYPE_VIDEO);
4962 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4963 ? &remote_audio_sender_infos_
4964 : &remote_video_sender_infos_;
4965}
4966
4967std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004968 cricket::MediaType media_type) {
4969 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4970 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004971 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4972 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004973}
4974
Steve Anton4171afb2017-11-20 10:20:22 -08004975const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4976 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004977 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004978 const std::string sender_id) const {
4979 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004980 if (sender_info.stream_id == stream_id &&
4981 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004982 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004983 }
4984 }
4985 return nullptr;
4986}
4987
4988DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4989 for (const auto& channel : sctp_data_channels_) {
4990 if (channel->id() == sid) {
4991 return channel;
4992 }
4993 }
4994 return nullptr;
4995}
4996
deadbeef91dd5672016-05-18 16:55:30 -07004997bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004998 const cricket::ServerAddresses& stun_servers,
4999 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005000 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005001 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005002 // To handle both internal and externally created port allocator, we will
5003 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005004 port_allocator_flags_ = port_allocator_->flags();
5005 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5006 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5007 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005008 // If the disable-IPv6 flag was specified, we'll not override it
5009 // by experiment.
5010 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005011 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005012 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5013 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005014 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005015 }
5016
zhihuangb09b3f92017-03-07 14:40:51 -08005017 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005018 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005019 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005020 }
5021
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005022 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005023 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005024 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005025 }
5026
honghaiz60347052016-05-31 18:29:12 -07005027 if (configuration.candidate_network_policy ==
5028 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005029 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005030 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005031 }
5032
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005033 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005034 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005035 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5036 }
5037
Qingsi Wanga2d60672018-04-11 16:57:45 -07005038 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005039 // No step delay is used while allocating ports.
5040 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5041 port_allocator_->set_candidate_filter(
5042 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005043 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005044
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005045 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005046 for (auto& turn_server : turn_servers_copy) {
5047 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005048 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005049 // Call this last since it may create pooled allocator sessions using the
5050 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005051 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005052 stun_servers, std::move(turn_servers_copy),
5053 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5054 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005055 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005056 return true;
5057}
5058
deadbeef91dd5672016-05-18 16:55:30 -07005059bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005060 const cricket::ServerAddresses& stun_servers,
5061 const std::vector<cricket::RelayServerConfig>& turn_servers,
5062 IceTransportsType type,
5063 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005064 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005065 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005066 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005067 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005068 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005069 // According to JSEP, after setLocalDescription, changing the candidate pool
5070 // size is not allowed, and changing the set of ICE servers will not result
5071 // in new candidates being gathered.
5072 if (local_description()) {
5073 port_allocator_->FreezeCandidatePool();
5074 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005075 // Add the custom tls turn servers if they exist.
5076 auto turn_servers_copy = turn_servers;
5077 for (auto& turn_server : turn_servers_copy) {
5078 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5079 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005080 // Call this last since it may create pooled allocator sessions using the
5081 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005082 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005083 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5084 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005085}
5086
Steve Antonba818672017-11-06 10:21:57 -08005087cricket::ChannelManager* PeerConnection::channel_manager() const {
5088 return factory_->channel_manager();
5089}
5090
Elad Alon99c3fe52017-10-13 16:29:40 +02005091bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005092 std::unique_ptr<RtcEventLogOutput> output,
5093 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005094 if (!event_log_) {
5095 return false;
5096 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005097 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005098}
5099
5100void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005101 if (event_log_) {
5102 event_log_->StopLogging();
5103 }
ivoc14d5dbe2016-07-04 07:06:55 -07005104}
nisseeaabdf62017-05-05 02:23:02 -07005105
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005106cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005107 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005108 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005109 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005110 if (channel && channel->content_name() == content_name) {
5111 return channel;
5112 }
Steve Anton75737c02017-11-06 10:37:17 -08005113 }
5114 if (rtp_data_channel() &&
5115 rtp_data_channel()->content_name() == content_name) {
5116 return rtp_data_channel();
5117 }
5118 return nullptr;
5119}
5120
5121bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005122 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005123 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005124 RTC_LOG(LS_INFO)
5125 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005126 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005127 return false;
5128 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005129 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005130 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005131 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005132 return false;
5133 }
5134
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005135 absl::optional<rtc::SSLRole> dtls_role;
5136 if (sctp_mid_) {
5137 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5138 } else if (is_caller_) {
5139 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5140 }
Zhi Huange830e682018-03-30 10:48:35 -07005141 if (dtls_role) {
5142 *role = *dtls_role;
5143 return true;
5144 }
5145 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005146}
5147
5148bool PeerConnection::GetSslRole(const std::string& content_name,
5149 rtc::SSLRole* role) {
5150 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005151 RTC_LOG(LS_INFO)
5152 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005153 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005154 return false;
5155 }
5156
Zhi Huange830e682018-03-30 10:48:35 -07005157 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5158 if (dtls_role) {
5159 *role = *dtls_role;
5160 return true;
5161 }
5162 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005163}
5164
Steve Antonf8470812017-12-04 10:46:21 -08005165void PeerConnection::SetSessionError(SessionError error,
5166 const std::string& error_desc) {
5167 RTC_DCHECK_RUN_ON(signaling_thread());
5168 if (error != session_error_) {
5169 session_error_ = error;
5170 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005171 }
5172}
5173
Zhi Huange830e682018-03-30 10:48:35 -07005174RTCError PeerConnection::UpdateSessionState(
5175 SdpType type,
5176 cricket::ContentSource source,
5177 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005178 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005179
5180 // If there's already a pending error then no state transition should happen.
5181 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005182 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005183
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005184 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005185 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005186 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005187 }
5188
5189 // Update the signaling state according to the specified state machine (see
5190 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005191 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005192 ChangeSignalingState(source == cricket::CS_LOCAL
5193 ? PeerConnectionInterface::kHaveLocalOffer
5194 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005195 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005196 ChangeSignalingState(source == cricket::CS_LOCAL
5197 ? PeerConnectionInterface::kHaveLocalPrAnswer
5198 : PeerConnectionInterface::kHaveRemotePrAnswer);
5199 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005200 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005201 ChangeSignalingState(PeerConnectionInterface::kStable);
5202 }
5203
5204 // Update internal objects according to the session description's media
5205 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005206 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005207 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005208 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005209 }
5210
Steve Anton8a006912017-12-04 15:25:56 -08005211 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005212}
5213
Steve Anton8a006912017-12-04 15:25:56 -08005214RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005215 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005216 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005217 const SessionDescriptionInterface* sdesc =
5218 (source == cricket::CS_LOCAL ? local_description()
5219 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005220 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005221
5222 // Push down the new SDP media section for each audio/video transceiver.
5223 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005224 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005225 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005226 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005227 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005228 continue;
5229 }
5230 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005231 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005232 if (!content_desc) {
5233 continue;
5234 }
5235 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005236 bool success = (source == cricket::CS_LOCAL)
5237 ? channel->SetLocalContent(content_desc, type, &error)
5238 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005239 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005240 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005241 }
5242 }
5243
5244 // If using the RtpDataChannel, push down the new SDP section for it too.
5245 if (rtp_data_channel_) {
5246 const ContentInfo* data_content =
5247 cricket::GetFirstDataContent(sdesc->description());
5248 if (data_content && !data_content->rejected) {
5249 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005250 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005251 if (data_desc) {
5252 std::string error;
5253 bool success =
5254 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005255 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005256 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005257 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005258 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005259 }
Steve Anton75737c02017-11-06 10:37:17 -08005260 }
5261 }
5262 }
Steve Antoned10bd92017-12-05 10:52:59 -08005263
Steve Anton75737c02017-11-06 10:37:17 -08005264 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5265 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5266 if (sctp_transport_ && local_description() && remote_description() &&
5267 cricket::GetFirstDataContent(local_description()->description()) &&
5268 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005269 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005270 RTC_FROM_HERE,
5271 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005272 if (!success) {
5273 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5274 "Failed to push down SCTP parameters.");
5275 }
Steve Anton75737c02017-11-06 10:37:17 -08005276 }
Steve Antoned10bd92017-12-05 10:52:59 -08005277
Steve Anton8a006912017-12-04 15:25:56 -08005278 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005279}
5280
5281bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5282 RTC_DCHECK(network_thread()->IsCurrent());
5283 RTC_DCHECK(local_description());
5284 RTC_DCHECK(remote_description());
5285 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5286 // When we support "max-message-size", that would also be pushed down here.
5287 return sctp_transport_->Start(
5288 GetSctpPort(local_description()->description()),
5289 GetSctpPort(remote_description()->description()));
5290}
5291
Steve Anton8a006912017-12-04 15:25:56 -08005292RTCError PeerConnection::PushdownTransportDescription(
5293 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005294 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005295 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005296
Zhi Huange830e682018-03-30 10:48:35 -07005297 if (source == cricket::CS_LOCAL) {
5298 const SessionDescriptionInterface* sdesc = local_description();
5299 RTC_DCHECK(sdesc);
5300 return transport_controller_->SetLocalDescription(type,
5301 sdesc->description());
5302 } else {
5303 const SessionDescriptionInterface* sdesc = remote_description();
5304 RTC_DCHECK(sdesc);
5305 return transport_controller_->SetRemoteDescription(type,
5306 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005307 }
Steve Anton75737c02017-11-06 10:37:17 -08005308}
5309
5310bool PeerConnection::GetTransportDescription(
5311 const SessionDescription* description,
5312 const std::string& content_name,
5313 cricket::TransportDescription* tdesc) {
5314 if (!description || !tdesc) {
5315 return false;
5316 }
5317 const TransportInfo* transport_info =
5318 description->GetTransportInfoByName(content_name);
5319 if (!transport_info) {
5320 return false;
5321 }
5322 *tdesc = transport_info->description;
5323 return true;
5324}
5325
Steve Anton75737c02017-11-06 10:37:17 -08005326cricket::IceConfig PeerConnection::ParseIceConfig(
5327 const PeerConnectionInterface::RTCConfiguration& config) const {
5328 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005329 switch (config.continual_gathering_policy) {
5330 case PeerConnectionInterface::GATHER_ONCE:
5331 gathering_policy = cricket::GATHER_ONCE;
5332 break;
5333 case PeerConnectionInterface::GATHER_CONTINUALLY:
5334 gathering_policy = cricket::GATHER_CONTINUALLY;
5335 break;
5336 default:
5337 RTC_NOTREACHED();
5338 gathering_policy = cricket::GATHER_ONCE;
5339 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005340
Steve Anton75737c02017-11-06 10:37:17 -08005341 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005342 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5343 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005344 ice_config.prioritize_most_likely_candidate_pairs =
5345 config.prioritize_most_likely_ice_candidate_pairs;
5346 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005347 RTCConfigurationToIceConfigOptionalInt(
5348 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005349 ice_config.continual_gathering_policy = gathering_policy;
5350 ice_config.presume_writable_when_fully_relayed =
5351 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005352 ice_config.ice_check_interval_strong_connectivity =
5353 config.ice_check_interval_strong_connectivity;
5354 ice_config.ice_check_interval_weak_connectivity =
5355 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005356 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005357 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5358 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005359 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005360 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005361 ice_config.regather_all_networks_interval_range =
5362 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005363 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005364 return ice_config;
5365}
5366
Steve Antona41959e2018-11-28 11:15:33 -08005367static absl::string_view GetTrackIdBySsrc(
5368 const SessionDescriptionInterface* session_description,
5369 uint32_t ssrc) {
5370 if (!session_description) {
5371 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005372 }
Steve Antona41959e2018-11-28 11:15:33 -08005373 for (const cricket::ContentInfo& content :
5374 session_description->description()->contents()) {
5375 const cricket::MediaContentDescription& media =
5376 *content.media_description();
5377 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5378 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5379 const cricket::StreamParams* stream_params =
5380 cricket::GetStreamBySsrc(media.streams(), ssrc);
5381 if (stream_params) {
5382 return stream_params->id;
5383 }
5384 }
5385 }
5386 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005387}
5388
Steve Antona41959e2018-11-28 11:15:33 -08005389absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5390 return GetTrackIdBySsrc(local_description(), ssrc);
5391}
5392
5393absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5394 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005395}
5396
5397bool PeerConnection::SendData(const cricket::SendDataParams& params,
5398 const rtc::CopyOnWriteBuffer& payload,
5399 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005400 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5401 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5402 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005403 return false;
5404 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005405 if (media_transport_) {
5406 SendDataParams send_params;
5407 send_params.type = ToWebrtcDataMessageType(params.type);
5408 send_params.ordered = params.ordered;
5409 if (params.max_rtx_count >= 0) {
5410 send_params.max_rtx_count = params.max_rtx_count;
5411 } else if (params.max_rtx_ms >= 0) {
5412 send_params.max_rtx_ms = params.max_rtx_ms;
5413 }
5414 return media_transport_->SendData(params.sid, send_params, payload).ok();
5415 }
Steve Anton75737c02017-11-06 10:37:17 -08005416 return rtp_data_channel_
5417 ? rtp_data_channel_->SendData(params, payload, result)
5418 : network_thread()->Invoke<bool>(
5419 RTC_FROM_HERE,
5420 Bind(&cricket::SctpTransportInternal::SendData,
5421 sctp_transport_.get(), params, payload, result));
5422}
5423
5424bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005425 RTC_DCHECK_RUN_ON(signaling_thread());
5426 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005427 // Don't log an error here, because DataChannels are expected to call
5428 // ConnectDataChannel in this state. It's the only way to initially tell
5429 // whether or not the underlying transport is ready.
5430 return false;
5431 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005432 if (media_transport_) {
5433 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5434 &DataChannel::OnChannelReady);
5435 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5436 &DataChannel::OnDataReceived);
5437 SignalMediaTransportChannelClosing_s.connect(
5438 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5439 SignalMediaTransportChannelClosed_s.connect(
5440 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5441 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005442 rtp_data_channel_->SignalReadyToSendData.connect(
5443 webrtc_data_channel, &DataChannel::OnChannelReady);
5444 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5445 &DataChannel::OnDataReceived);
5446 } else {
5447 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5448 &DataChannel::OnChannelReady);
5449 SignalSctpDataReceived.connect(webrtc_data_channel,
5450 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005451 SignalSctpClosingProcedureStartedRemotely.connect(
5452 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5453 SignalSctpClosingProcedureComplete.connect(
5454 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005455 }
5456 return true;
5457}
5458
5459void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005460 RTC_DCHECK_RUN_ON(signaling_thread());
5461 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005462 RTC_LOG(LS_ERROR)
5463 << "DisconnectDataChannel called when rtp_data_channel_ and "
5464 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005465 return;
5466 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005467 if (media_transport_) {
5468 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5469 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5470 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5471 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5472 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005473 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5474 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5475 } else {
5476 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5477 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005478 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5479 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005480 }
5481}
5482
5483void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005484 if (media_transport_) {
5485 // No-op. Media transport does not need to add streams.
5486 return;
5487 }
Steve Anton75737c02017-11-06 10:37:17 -08005488 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005489 RTC_LOG(LS_ERROR)
5490 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005491 return;
5492 }
5493 network_thread()->Invoke<void>(
5494 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5495 sctp_transport_.get(), sid));
5496}
5497
5498void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005499 if (media_transport_) {
5500 media_transport_->CloseChannel(sid);
5501 return;
5502 }
Steve Anton75737c02017-11-06 10:37:17 -08005503 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005504 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005505 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005506 return;
5507 }
5508 network_thread()->Invoke<void>(
5509 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5510 sctp_transport_.get(), sid));
5511}
5512
5513bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005514 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005515 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005516 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005517 sctp_ready_to_send_data_;
5518}
5519
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005520void PeerConnection::OnDataReceived(int channel_id,
5521 DataMessageType type,
5522 const rtc::CopyOnWriteBuffer& buffer) {
5523 cricket::ReceiveDataParams params;
5524 params.sid = channel_id;
5525 params.type = ToCricketDataMessageType(type);
5526 media_transport_invoker_->AsyncInvoke<void>(
5527 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5528 RTC_DCHECK_RUN_ON(signaling_thread());
5529 if (!HandleOpenMessage_s(params, buffer)) {
5530 SignalMediaTransportReceivedData_s(params, buffer);
5531 }
5532 });
5533}
5534
5535void PeerConnection::OnChannelClosing(int channel_id) {
5536 media_transport_invoker_->AsyncInvoke<void>(
5537 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5538 RTC_DCHECK_RUN_ON(signaling_thread());
5539 SignalMediaTransportChannelClosing_s(channel_id);
5540 });
5541}
5542
5543void PeerConnection::OnChannelClosed(int channel_id) {
5544 media_transport_invoker_->AsyncInvoke<void>(
5545 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5546 RTC_DCHECK_RUN_ON(signaling_thread());
5547 SignalMediaTransportChannelClosed_s(channel_id);
5548 });
5549}
5550
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005551absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005552 if (sctp_mid_ && transport_controller_) {
5553 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5554 if (dtls_transport) {
5555 return dtls_transport->transport_name();
5556 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005557 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005558 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005559 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005560}
5561
Qingsi Wang72a43a12018-02-20 16:03:18 -08005562cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5563 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005564 network_thread()->Invoke<void>(
5565 RTC_FROM_HERE,
5566 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5567 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005568 return candidate_states_list;
5569}
5570
Steve Anton5dfde182018-02-06 10:34:40 -08005571std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5572 const {
5573 std::map<std::string, std::string> transport_names_by_mid;
5574 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005575 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005576 if (channel) {
5577 transport_names_by_mid[channel->content_name()] =
5578 channel->transport_name();
5579 }
Steve Anton75737c02017-11-06 10:37:17 -08005580 }
Steve Anton5dfde182018-02-06 10:34:40 -08005581 if (rtp_data_channel_) {
5582 transport_names_by_mid[rtp_data_channel_->content_name()] =
5583 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005584 }
5585 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005586 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005587 RTC_DCHECK(transport_name);
5588 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005589 }
Steve Anton5dfde182018-02-06 10:34:40 -08005590 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005591}
5592
Steve Anton5dfde182018-02-06 10:34:40 -08005593std::map<std::string, cricket::TransportStats>
5594PeerConnection::GetTransportStatsByNames(
5595 const std::set<std::string>& transport_names) {
5596 if (!network_thread()->IsCurrent()) {
5597 return network_thread()
5598 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5599 RTC_FROM_HERE,
5600 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005601 }
Steve Anton5dfde182018-02-06 10:34:40 -08005602 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5603 for (const std::string& transport_name : transport_names) {
5604 cricket::TransportStats transport_stats;
5605 bool success =
5606 transport_controller_->GetStats(transport_name, &transport_stats);
5607 if (success) {
5608 transport_stats_by_name[transport_name] = std::move(transport_stats);
5609 } else {
5610 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5611 << transport_name;
5612 }
5613 }
5614 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005615}
5616
5617bool PeerConnection::GetLocalCertificate(
5618 const std::string& transport_name,
5619 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005620 if (!certificate) {
5621 return false;
5622 }
5623 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5624 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005625}
5626
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005627std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005628 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005629 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005630}
5631
5632cricket::DataChannelType PeerConnection::data_channel_type() const {
5633 return data_channel_type_;
5634}
5635
5636bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5637 return pending_ice_restarts_.find(content_name) !=
5638 pending_ice_restarts_.end();
5639}
5640
Steve Anton75737c02017-11-06 10:37:17 -08005641bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5642 return transport_controller_->NeedsIceRestart(content_name);
5643}
5644
5645void PeerConnection::OnCertificateReady(
5646 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5647 transport_controller_->SetLocalCertificate(certificate);
5648}
5649
5650void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005651 SetSessionError(SessionError::kTransport,
5652 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005653}
5654
Alex Loiko9289eda2018-11-23 16:18:59 +00005655void PeerConnection::OnTransportControllerConnectionState(
5656 cricket::IceConnectionState state) {
5657 switch (state) {
5658 case cricket::kIceConnectionConnecting:
5659 // If the current state is Connected or Completed, then there were
5660 // writable channels but now there are not, so the next state must
5661 // be Disconnected.
5662 // kIceConnectionConnecting is currently used as the default,
5663 // un-connected state by the TransportController, so its only use is
5664 // detecting disconnections.
5665 if (ice_connection_state_ ==
5666 PeerConnectionInterface::kIceConnectionConnected ||
5667 ice_connection_state_ ==
5668 PeerConnectionInterface::kIceConnectionCompleted) {
5669 SetIceConnectionState(
5670 PeerConnectionInterface::kIceConnectionDisconnected);
5671 }
5672 break;
5673 case cricket::kIceConnectionFailed:
5674 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5675 break;
5676 case cricket::kIceConnectionConnected:
5677 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5678 "all transports are writable.";
5679 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5680 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5681 break;
5682 case cricket::kIceConnectionCompleted:
5683 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5684 "all transports are complete.";
5685 if (ice_connection_state_ !=
5686 PeerConnectionInterface::kIceConnectionConnected) {
5687 // If jumping directly from "checking" to "connected",
5688 // signal "connected" first.
5689 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5690 }
5691 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5692 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5693 ReportTransportStats();
5694 break;
5695 default:
5696 RTC_NOTREACHED();
5697 }
5698}
5699
Steve Anton75737c02017-11-06 10:37:17 -08005700void PeerConnection::OnTransportControllerCandidatesGathered(
5701 const std::string& transport_name,
5702 const cricket::Candidates& candidates) {
5703 RTC_DCHECK(signaling_thread()->IsCurrent());
5704 int sdp_mline_index;
5705 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005706 RTC_LOG(LS_ERROR)
5707 << "OnTransportControllerCandidatesGathered: content name "
5708 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005709 return;
5710 }
5711
5712 for (cricket::Candidates::const_iterator citer = candidates.begin();
5713 citer != candidates.end(); ++citer) {
5714 // Use transport_name as the candidate media id.
5715 std::unique_ptr<JsepIceCandidate> candidate(
5716 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5717 if (local_description()) {
5718 mutable_local_description()->AddCandidate(candidate.get());
5719 }
5720 OnIceCandidate(std::move(candidate));
5721 }
5722}
5723
5724void PeerConnection::OnTransportControllerCandidatesRemoved(
5725 const std::vector<cricket::Candidate>& candidates) {
5726 RTC_DCHECK(signaling_thread()->IsCurrent());
5727 // Sanity check.
5728 for (const cricket::Candidate& candidate : candidates) {
5729 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005730 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005731 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005732 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005733 return;
5734 }
5735 }
5736
5737 if (local_description()) {
5738 mutable_local_description()->RemoveCandidates(candidates);
5739 }
5740 OnIceCandidatesRemoved(candidates);
5741}
5742
5743void PeerConnection::OnTransportControllerDtlsHandshakeError(
5744 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005745 RTC_HISTOGRAM_ENUMERATION(
5746 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5747 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005748}
5749
Steve Antoned10bd92017-12-05 10:52:59 -08005750void PeerConnection::EnableSending() {
5751 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005752 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005753 if (channel && !channel->enabled()) {
5754 channel->Enable(true);
5755 }
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
5757
Steve Anton4171afb2017-11-20 10:20:22 -08005758 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005759 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005760 }
Steve Anton75737c02017-11-06 10:37:17 -08005761}
5762
5763// Returns the media index for a local ice candidate given the content name.
5764bool PeerConnection::GetLocalCandidateMediaIndex(
5765 const std::string& content_name,
5766 int* sdp_mline_index) {
5767 if (!local_description() || !sdp_mline_index) {
5768 return false;
5769 }
5770
5771 bool content_found = false;
5772 const ContentInfos& contents = local_description()->description()->contents();
5773 for (size_t index = 0; index < contents.size(); ++index) {
5774 if (contents[index].name == content_name) {
5775 *sdp_mline_index = static_cast<int>(index);
5776 content_found = true;
5777 break;
5778 }
5779 }
5780 return content_found;
5781}
5782
5783bool PeerConnection::UseCandidatesInSessionDescription(
5784 const SessionDescriptionInterface* remote_desc) {
5785 if (!remote_desc) {
5786 return true;
5787 }
5788 bool ret = true;
5789
5790 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5791 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5792 for (size_t n = 0; n < candidates->count(); ++n) {
5793 const IceCandidateInterface* candidate = candidates->at(n);
5794 bool valid = false;
5795 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5796 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005797 RTC_LOG(LS_INFO)
5798 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005799 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005800 }
5801 continue;
5802 }
5803 ret = UseCandidate(candidate);
5804 if (!ret) {
5805 break;
5806 }
5807 }
5808 }
5809 return ret;
5810}
5811
5812bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5813 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5814 size_t remote_content_size =
5815 remote_description()->description()->contents().size();
5816 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005817 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005818 return false;
5819 }
5820
5821 cricket::ContentInfo content =
5822 remote_description()->description()->contents()[mediacontent_index];
5823 std::vector<cricket::Candidate> candidates;
5824 candidates.push_back(candidate->candidate());
5825 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005826 RTCError error =
5827 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005828 if (error.ok()) {
5829 // Candidates successfully submitted for checking.
5830 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5831 ice_connection_state_ ==
5832 PeerConnectionInterface::kIceConnectionDisconnected) {
5833 // If state is New, then the session has just gotten its first remote ICE
5834 // candidates, so go to Checking.
5835 // If state is Disconnected, the session is re-using old candidates or
5836 // receiving additional ones, so go to Checking.
5837 // If state is Connected, stay Connected.
5838 // TODO(bemasc): If state is Connected, and the new candidates are for a
5839 // newly added transport, then the state actually _should_ move to
5840 // checking. Add a way to distinguish that case.
5841 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5842 }
5843 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005844 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005845 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005846 }
5847 return true;
5848}
5849
5850void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 // Destroy video channel first since it may have a pointer to the
5852 // voice channel.
5853 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005854 if (!video_info || video_info->rejected) {
5855 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005856 }
5857
Steve Anton6fec8802017-12-04 10:37:29 -08005858 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5859 if (!audio_info || audio_info->rejected) {
5860 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005861 }
5862
5863 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5864 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005865 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005866 }
5867}
5868
Steve Antondcc3c022017-12-22 16:02:54 -08005869RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5870 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005871 const cricket::ContentGroup* bundle_group = nullptr;
5872 if (configuration_.bundle_policy ==
5873 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005874 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005875 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005876 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5877 "max-bundle configured but session description "
5878 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005879 }
5880 }
Steve Antondcc3c022017-12-22 16:02:54 -08005881 return std::move(bundle_group);
5882}
5883
5884RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005885 // Creating the media channels. Transports should already have been created
5886 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005887 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005888 if (voice && !voice->rejected &&
5889 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005890 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005891 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005892 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5893 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005894 }
5895 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5896 }
5897
Steve Antondcc3c022017-12-22 16:02:54 -08005898 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005899 if (video && !video->rejected &&
5900 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005901 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005902 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005903 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5904 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005905 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005906 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005907 }
5908
Steve Antondcc3c022017-12-22 16:02:54 -08005909 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005910 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005911 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005912 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005913 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5914 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005915 }
5916 }
5917
Steve Anton8a006912017-12-04 15:25:56 -08005918 return RTCError::OK();
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::VoiceChannel* PeerConnection::CreateVoiceChannel(
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);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005925 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::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005931 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005932 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5933 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005934 if (!voice_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 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5938 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005939 voice_channel->SignalSentPacket.connect(this,
5940 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005941 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005942
Steve Antoneda6ccd2017-12-04 10:21:55 -08005943 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005944}
5945
Steve Anton4171afb2017-11-20 10:20:22 -08005946// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005947cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005948 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005949 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01005950 MediaTransportInterface* media_transport = nullptr;
5951 if (configuration_.use_media_transport) {
5952 media_transport = GetMediaTransport(mid);
5953 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005954
Steve Anton75737c02017-11-06 10:37:17 -08005955 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01005956 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005957 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5958 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005959 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005960 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005961 }
Steve Anton75737c02017-11-06 10:37:17 -08005962 video_channel->SignalDtlsSrtpSetupFailure.connect(
5963 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005964 video_channel->SignalSentPacket.connect(this,
5965 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005966 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005967
Steve Antoneda6ccd2017-12-04 10:21:55 -08005968 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005969}
5970
Zhi Huange830e682018-03-30 10:48:35 -07005971bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005972 switch (data_channel_type_) {
5973 case cricket::DCT_MEDIA_TRANSPORT:
5974 if (network_thread()->Invoke<bool>(
5975 RTC_FROM_HERE,
5976 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5977 this, mid))) {
5978 for (const auto& channel : sctp_data_channels_) {
5979 channel->OnTransportChannelCreated();
5980 }
5981 return true;
5982 }
Steve Anton75737c02017-11-06 10:37:17 -08005983 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005984 case cricket::DCT_SCTP:
5985 if (!sctp_factory_) {
5986 RTC_LOG(LS_ERROR)
5987 << "Trying to create SCTP transport, but didn't compile with "
5988 "SCTP support (HAVE_SCTP)";
5989 return false;
5990 }
5991 if (!network_thread()->Invoke<bool>(
5992 RTC_FROM_HERE,
5993 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5994 return false;
5995 }
5996 for (const auto& channel : sctp_data_channels_) {
5997 channel->OnTransportChannelCreated();
5998 }
5999 return true;
6000 case cricket::DCT_RTP:
6001 default:
6002 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6003 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6004 configuration_.media_config, rtp_transport, signaling_thread(), mid,
6005 SrtpRequired(), GetCryptoOptions());
6006 if (!rtp_data_channel_) {
6007 return false;
6008 }
6009 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6010 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6011 rtp_data_channel_->SignalSentPacket.connect(
6012 this, &PeerConnection::OnSentPacket_w);
6013 rtp_data_channel_->SetRtpTransport(rtp_transport);
6014 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006015 }
6016
Steve Anton75737c02017-11-06 10:37:17 -08006017 return true;
6018}
6019
6020Call::Stats PeerConnection::GetCallStats() {
6021 if (!worker_thread()->IsCurrent()) {
6022 return worker_thread()->Invoke<Call::Stats>(
6023 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6024 }
6025 if (call_) {
6026 return call_->GetStats();
6027 } else {
6028 return Call::Stats();
6029 }
6030}
6031
Zhi Huange830e682018-03-30 10:48:35 -07006032bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006033 RTC_DCHECK(network_thread()->IsCurrent());
6034 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006035 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006036 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006037 RTC_DCHECK(dtls_transport);
6038 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006039 RTC_DCHECK(sctp_transport_);
6040 sctp_invoker_.reset(new rtc::AsyncInvoker());
6041 sctp_transport_->SignalReadyToSendData.connect(
6042 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6043 sctp_transport_->SignalDataReceived.connect(
6044 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006045 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6046 // another thread. Would be nice if there was a helper class similar to
6047 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6048 // code.
6049 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6050 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6051 sctp_transport_->SignalClosingProcedureComplete.connect(
6052 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006053 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006054 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006055 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006056}
6057
6058void PeerConnection::DestroySctpTransport_n() {
6059 RTC_DCHECK(network_thread()->IsCurrent());
6060 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006061 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006062 sctp_invoker_.reset(nullptr);
6063 sctp_ready_to_send_data_ = false;
6064}
6065
6066void PeerConnection::OnSctpTransportReadyToSendData_n() {
6067 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6068 RTC_DCHECK(network_thread()->IsCurrent());
6069 // Note: Cannot use rtc::Bind here because it will grab a reference to
6070 // PeerConnection and potentially cause PeerConnection to live longer than
6071 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6072 // be destroyed before PeerConnection is destroyed, and at that point all
6073 // pending tasks will be cleared.
6074 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6075 OnSctpTransportReadyToSendData_s(true);
6076 });
6077}
6078
6079void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6080 RTC_DCHECK(signaling_thread()->IsCurrent());
6081 sctp_ready_to_send_data_ = ready;
6082 SignalSctpReadyToSendData(ready);
6083}
6084
6085void PeerConnection::OnSctpTransportDataReceived_n(
6086 const cricket::ReceiveDataParams& params,
6087 const rtc::CopyOnWriteBuffer& payload) {
6088 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6089 RTC_DCHECK(network_thread()->IsCurrent());
6090 // Note: Cannot use rtc::Bind here because it will grab a reference to
6091 // PeerConnection and potentially cause PeerConnection to live longer than
6092 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6093 // be destroyed before PeerConnection is destroyed, and at that point all
6094 // pending tasks will be cleared.
6095 sctp_invoker_->AsyncInvoke<void>(
6096 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6097 OnSctpTransportDataReceived_s(params, payload);
6098 });
6099}
6100
6101void PeerConnection::OnSctpTransportDataReceived_s(
6102 const cricket::ReceiveDataParams& params,
6103 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006104 RTC_DCHECK_RUN_ON(signaling_thread());
6105 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006106 SignalSctpDataReceived(params, payload);
6107 }
6108}
6109
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006110void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006111 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6112 RTC_DCHECK(network_thread()->IsCurrent());
6113 sctp_invoker_->AsyncInvoke<void>(
6114 RTC_FROM_HERE, signaling_thread(),
6115 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006116 &SignalSctpClosingProcedureStartedRemotely, sid));
6117}
6118
6119void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6120 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6121 RTC_DCHECK(network_thread()->IsCurrent());
6122 sctp_invoker_->AsyncInvoke<void>(
6123 RTC_FROM_HERE, signaling_thread(),
6124 rtc::Bind(&sigslot::signal1<int>::operator(),
6125 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006126}
6127
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006128bool PeerConnection::SetupMediaTransportForDataChannels_n(
6129 const std::string& mid) {
6130 media_transport_ = transport_controller_->GetMediaTransport(mid);
6131 if (!media_transport_) {
6132 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6133 return false;
6134 }
6135
6136 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6137 media_transport_->SetDataSink(this);
6138 media_transport_data_mid_ = mid;
6139 transport_controller_->SignalMediaTransportStateChanged.connect(
6140 this, &PeerConnection::OnMediaTransportStateChanged_n);
6141 // Check the initial state right away, in case transport is already writable.
6142 OnMediaTransportStateChanged_n();
6143 return true;
6144}
6145
6146void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6147 if (!media_transport_) {
6148 return;
6149 }
6150 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6151 media_transport_data_mid_.reset();
6152 media_transport_->SetDataSink(nullptr);
6153 media_transport_invoker_ = nullptr;
6154 media_transport_ = nullptr;
6155}
6156
6157void PeerConnection::OnMediaTransportStateChanged_n() {
6158 if (!media_transport_data_mid_ ||
6159 transport_controller_->GetMediaTransportState(
6160 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6161 return;
6162 }
6163 media_transport_invoker_->AsyncInvoke<void>(
6164 RTC_FROM_HERE, signaling_thread(), [this] {
6165 RTC_DCHECK_RUN_ON(signaling_thread());
6166 media_transport_ready_to_send_data_ = true;
6167 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6168 });
6169}
6170
Steve Anton75737c02017-11-06 10:37:17 -08006171// Returns false if bundle is enabled and rtcp_mux is disabled.
6172bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6173 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6174 if (!bundle_enabled)
6175 return true;
6176
6177 const cricket::ContentGroup* bundle_group =
6178 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6179 RTC_DCHECK(bundle_group != NULL);
6180
6181 const cricket::ContentInfos& contents = desc->contents();
6182 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6183 citer != contents.end(); ++citer) {
6184 const cricket::ContentInfo* content = (&*citer);
6185 RTC_DCHECK(content != NULL);
6186 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006187 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006188 if (!HasRtcpMuxEnabled(content))
6189 return false;
6190 }
6191 }
6192 // RTCP-MUX is enabled in all the contents.
6193 return true;
6194}
6195
6196bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006197 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006198}
6199
Steve Anton06817cd2018-12-18 15:55:30 -08006200static RTCError ValidateMids(const cricket::SessionDescription& description) {
6201 std::set<std::string> mids;
6202 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006203 if (content.name.empty()) {
6204 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6205 "A media section is missing a MID attribute.");
6206 }
Steve Anton06817cd2018-12-18 15:55:30 -08006207 if (!mids.insert(content.name).second) {
6208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6209 "Duplicate a=mid value '" + content.name + "'.");
6210 }
6211 }
6212 return RTCError::OK();
6213}
6214
Steve Anton8a006912017-12-04 15:25:56 -08006215RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006216 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006217 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006218 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006219 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006220 }
6221
6222 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006224 }
6225
Steve Anton3828c062017-12-06 10:34:51 -08006226 SdpType type = sdesc->GetType();
6227 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6228 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006229 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006230 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006231 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006232 }
6233
Steve Anton06817cd2018-12-18 15:55:30 -08006234 RTCError error = ValidateMids(*sdesc->description());
6235 if (!error.ok()) {
6236 return error;
6237 }
6238
Steve Anton75737c02017-11-06 10:37:17 -08006239 // Verify crypto settings.
6240 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006241 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6242 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006243 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006244 if (!crypto_error.ok()) {
6245 return crypto_error;
6246 }
Steve Anton75737c02017-11-06 10:37:17 -08006247 }
6248
6249 // Verify ice-ufrag and ice-pwd.
6250 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6252 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006253 }
6254
6255 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006256 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6257 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006258 }
6259
6260 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6261 // m-lines that do not rtcp-mux enabled.
6262
6263 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006264 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006265 // With an answer we want to compare the new answer session description with
6266 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006267 const cricket::SessionDescription* offer_desc =
6268 (source == cricket::CS_LOCAL) ? remote_description()->description()
6269 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006270 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6271 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6272 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6274 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006275 }
6276 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006277 // The re-offers should respect the order of m= sections in current
6278 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006279 // With a re-offer, either the current local or current remote descriptions
6280 // could be the most up to date, so we would like to check against both of
6281 // them if they exist. It could be the case that one of them has a 0 port
6282 // for a media section, but the other does not. This is important to check
6283 // against in the case that we are recycling an m= section.
6284 const cricket::SessionDescription* current_desc = nullptr;
6285 const cricket::SessionDescription* secondary_current_desc = nullptr;
6286 if (local_description()) {
6287 current_desc = local_description()->description();
6288 if (remote_description()) {
6289 secondary_current_desc = remote_description()->description();
6290 }
6291 } else if (remote_description()) {
6292 current_desc = remote_description()->description();
6293 }
Steve Anton75737c02017-11-06 10:37:17 -08006294 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006295 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6296 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006297 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6298 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006299 }
6300 }
6301
Steve Antonba42e992018-04-09 14:10:01 -07006302 if (IsUnifiedPlan()) {
6303 // Ensure that each audio and video media section has at most one
6304 // "StreamParams". This will return an error if receiving a session
6305 // description from a "Plan B" endpoint which adds multiple tracks of the
6306 // same type. With Unified Plan, there can only be at most one track per
6307 // media section.
6308 for (const ContentInfo& content : sdesc->description()->contents()) {
6309 const MediaContentDescription& desc = *content.description;
6310 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6311 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6312 desc.streams().size() > 1u) {
6313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6314 "Media section has more than one track specified "
6315 "with a=ssrc lines which is not supported with "
6316 "Unified Plan.");
6317 }
6318 }
6319 }
6320
Steve Anton8a006912017-12-04 15:25:56 -08006321 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006322}
6323
Steve Anton3828c062017-12-06 10:34:51 -08006324bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006325 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006326 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006327 return (state == PeerConnectionInterface::kStable) ||
6328 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006329 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006330 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006331 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6332 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6333 }
6334}
6335
Steve Anton3828c062017-12-06 10:34:51 -08006336bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006337 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006338 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006339 return (state == PeerConnectionInterface::kStable) ||
6340 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006341 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006342 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006343 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6344 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6345 }
6346}
6347
Steve Antonf8470812017-12-04 10:46:21 -08006348const char* PeerConnection::SessionErrorToString(SessionError error) const {
6349 switch (error) {
6350 case SessionError::kNone:
6351 return "ERROR_NONE";
6352 case SessionError::kContent:
6353 return "ERROR_CONTENT";
6354 case SessionError::kTransport:
6355 return "ERROR_TRANSPORT";
6356 }
6357 RTC_NOTREACHED();
6358 return "";
6359}
6360
Steve Anton75737c02017-11-06 10:37:17 -08006361std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006362 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006363 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6364 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006365 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006366}
6367
Steve Anton8e20f172018-03-06 10:55:04 -08006368void PeerConnection::ReportSdpFormatReceived(
6369 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006370 int num_audio_mlines = 0;
6371 int num_video_mlines = 0;
6372 int num_audio_tracks = 0;
6373 int num_video_tracks = 0;
6374 for (const ContentInfo& content : remote_offer.description()->contents()) {
6375 cricket::MediaType media_type = content.media_description()->type();
6376 int num_tracks = std::max(
6377 1, static_cast<int>(content.media_description()->streams().size()));
6378 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6379 num_audio_mlines += 1;
6380 num_audio_tracks += num_tracks;
6381 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6382 num_video_mlines += 1;
6383 num_video_tracks += num_tracks;
6384 }
6385 }
6386 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6387 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6388 format = kSdpFormatReceivedComplexUnifiedPlan;
6389 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6390 format = kSdpFormatReceivedComplexPlanB;
6391 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6392 format = kSdpFormatReceivedSimple;
6393 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006394 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6395 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006396}
6397
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006398void PeerConnection::NoteUsageEvent(UsageEvent event) {
6399 RTC_DCHECK_RUN_ON(signaling_thread());
6400 usage_event_accumulator_ |= static_cast<int>(event);
6401}
6402
6403void PeerConnection::ReportUsagePattern() const {
6404 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006405 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6406 usage_event_accumulator_,
6407 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006408 const int bad_bits =
6409 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6410 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6411 const int good_bits =
6412 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6413 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6414 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6415 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6416 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006417 // If called after close(), we can't report, because observer may have
6418 // been deallocated, and therefore pointer is null. Write to log instead.
6419 if (observer_) {
6420 Observer()->OnInterestingUsage(usage_event_accumulator_);
6421 } else {
6422 RTC_LOG(LS_INFO) << "Interesting usage signature "
6423 << usage_event_accumulator_
6424 << " observed after observer shutdown";
6425 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006426 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006427}
6428
Steve Anton0ffaaa22018-02-23 10:31:30 -08006429void PeerConnection::ReportNegotiatedSdpSemantics(
6430 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006431 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006432 switch (answer.description()->msid_signaling()) {
6433 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006434 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006435 break;
6436 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006437 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006438 break;
6439 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006440 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006441 break;
6442 case cricket::kMsidSignalingMediaSection |
6443 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006444 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006445 break;
6446 default:
6447 RTC_NOTREACHED();
6448 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6450 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006451}
6452
Steve Anton75737c02017-11-06 10:37:17 -08006453// We need to check the local/remote description for the Transport instead of
6454// the session, because a new Transport added during renegotiation may have
6455// them unset while the session has them set from the previous negotiation.
6456// Not doing so may trigger the auto generation of transport description and
6457// mess up DTLS identity information, ICE credential, etc.
6458bool PeerConnection::ReadyToUseRemoteCandidate(
6459 const IceCandidateInterface* candidate,
6460 const SessionDescriptionInterface* remote_desc,
6461 bool* valid) {
6462 *valid = true;
6463
6464 const SessionDescriptionInterface* current_remote_desc =
6465 remote_desc ? remote_desc : remote_description();
6466
6467 if (!current_remote_desc) {
6468 return false;
6469 }
6470
6471 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6472 size_t remote_content_size =
6473 current_remote_desc->description()->contents().size();
6474 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006475 RTC_LOG(LS_ERROR)
6476 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6477 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006478
6479 *valid = false;
6480 return false;
6481 }
6482
6483 cricket::ContentInfo content =
6484 current_remote_desc->description()->contents()[mediacontent_index];
6485
6486 const std::string transport_name = GetTransportName(content.name);
6487 if (transport_name.empty()) {
6488 return false;
6489 }
Zhi Huange830e682018-03-30 10:48:35 -07006490 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006491}
6492
6493bool PeerConnection::SrtpRequired() const {
6494 return dtls_enabled_ ||
6495 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6496}
6497
6498void PeerConnection::OnTransportControllerGatheringState(
6499 cricket::IceGatheringState state) {
6500 RTC_DCHECK(signaling_thread()->IsCurrent());
6501 if (state == cricket::kIceGatheringGathering) {
6502 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6503 } else if (state == cricket::kIceGatheringComplete) {
6504 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6505 }
6506}
6507
6508void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006509 std::map<std::string, std::set<cricket::MediaType>>
6510 media_types_by_transport_name;
6511 for (auto transceiver : transceivers_) {
6512 if (transceiver->internal()->channel()) {
6513 const std::string& transport_name =
6514 transceiver->internal()->channel()->transport_name();
6515 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006516 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006517 }
Steve Anton75737c02017-11-06 10:37:17 -08006518 }
6519 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006520 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6521 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006522 }
Zhi Huange830e682018-03-30 10:48:35 -07006523
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006524 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006525 if (transport_name) {
6526 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006527 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006528 }
Zhi Huange830e682018-03-30 10:48:35 -07006529
Steve Antonc7b964c2018-02-01 14:39:45 -08006530 for (const auto& entry : media_types_by_transport_name) {
6531 const std::string& transport_name = entry.first;
6532 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006533 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006534 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006535 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006536 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006537 }
6538 }
6539}
6540// Walk through the ConnectionInfos to gather best connection usage
6541// for IPv4 and IPv6.
6542void PeerConnection::ReportBestConnectionState(
6543 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006544 for (const cricket::TransportChannelStats& channel_stats :
6545 stats.channel_stats) {
6546 for (const cricket::ConnectionInfo& connection_info :
6547 channel_stats.connection_infos) {
6548 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006549 continue;
6550 }
6551
Steve Antonc7b964c2018-02-01 14:39:45 -08006552 const cricket::Candidate& local = connection_info.local_candidate;
6553 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006554
6555 // Increment the counter for IceCandidatePairType.
6556 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6557 (local.type() == RELAY_PORT_TYPE &&
6558 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006559 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6560 GetIceCandidatePairCounter(local, remote),
6561 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006562 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006563 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6564 GetIceCandidatePairCounter(local, remote),
6565 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006566 } else {
6567 RTC_CHECK(0);
6568 }
Steve Anton75737c02017-11-06 10:37:17 -08006569
6570 // Increment the counter for IP type.
6571 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006572 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6573 kBestConnections_IPv4,
6574 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006575 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006576 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6577 kBestConnections_IPv6,
6578 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006579 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006580 RTC_CHECK(!local.address().hostname().empty() &&
6581 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006582 }
6583
6584 return;
6585 }
6586 }
6587}
6588
6589void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006590 const cricket::TransportStats& stats,
6591 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006592 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6593 return;
6594 }
6595
6596 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6597 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6598 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6599 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6600 return;
6601 }
6602
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006603 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
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.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6609 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6610 break;
6611 case cricket::MEDIA_TYPE_VIDEO:
6612 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6613 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6614 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6615 break;
6616 case cricket::MEDIA_TYPE_DATA:
6617 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6618 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6619 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6620 break;
6621 default:
6622 RTC_NOTREACHED();
6623 continue;
6624 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006625 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006626 }
6627
6628 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6629 for (cricket::MediaType media_type : media_types) {
6630 switch (media_type) {
6631 case cricket::MEDIA_TYPE_AUDIO:
6632 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6633 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6634 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6635 break;
6636 case cricket::MEDIA_TYPE_VIDEO:
6637 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6638 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6639 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6640 break;
6641 case cricket::MEDIA_TYPE_DATA:
6642 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6643 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6644 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6645 break;
6646 default:
6647 RTC_NOTREACHED();
6648 continue;
6649 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006650 }
Steve Anton75737c02017-11-06 10:37:17 -08006651 }
6652}
6653
6654void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6655 RTC_DCHECK(worker_thread()->IsCurrent());
6656 RTC_DCHECK(call_);
6657 call_->OnSentPacket(sent_packet);
6658}
6659
6660const std::string PeerConnection::GetTransportName(
6661 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006662 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006663 if (channel) {
6664 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006665 }
Steve Anton6fec8802017-12-04 10:37:29 -08006666 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006667 RTC_DCHECK(sctp_mid_);
6668 if (content_name == *sctp_mid_) {
6669 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006670 }
6671 }
6672 // Return an empty string if failed to retrieve the transport name.
6673 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006674}
6675
Steve Anton6fec8802017-12-04 10:37:29 -08006676void PeerConnection::DestroyTransceiverChannel(
6677 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6678 transceiver) {
6679 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006680
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006681 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006682 if (channel) {
6683 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006684 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006685 }
6686}
6687
6688void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006689 if (rtp_data_channel_) {
6690 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006691 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006692 rtp_data_channel_ = nullptr;
6693 }
6694
6695 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6696 // grab a reference to this PeerConnection. If this is called from the
6697 // PeerConnection destructor, the RefCountedObject vtable will have already
6698 // been destroyed (since it is a subclass of PeerConnection) and using
6699 // rtc::Bind will cause "Pure virtual function called" error to appear.
6700
6701 if (sctp_transport_) {
6702 OnDataChannelDestroyed();
6703 network_thread()->Invoke<void>(RTC_FROM_HERE,
6704 [this] { DestroySctpTransport_n(); });
6705 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006706
6707 if (media_transport_) {
6708 OnDataChannelDestroyed();
6709 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6710 RTC_DCHECK_RUN_ON(network_thread());
6711 TeardownMediaTransportForDataChannels_n();
6712 });
6713 }
Steve Anton6fec8802017-12-04 10:37:29 -08006714}
6715
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006716void PeerConnection::DestroyChannelInterface(
6717 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006718 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006719 switch (channel->media_type()) {
6720 case cricket::MEDIA_TYPE_AUDIO:
6721 channel_manager()->DestroyVoiceChannel(
6722 static_cast<cricket::VoiceChannel*>(channel));
6723 break;
6724 case cricket::MEDIA_TYPE_VIDEO:
6725 channel_manager()->DestroyVideoChannel(
6726 static_cast<cricket::VideoChannel*>(channel));
6727 break;
6728 case cricket::MEDIA_TYPE_DATA:
6729 channel_manager()->DestroyRtpDataChannel(
6730 static_cast<cricket::RtpDataChannel*>(channel));
6731 break;
6732 default:
6733 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6734 break;
6735 }
Zhi Huange830e682018-03-30 10:48:35 -07006736}
Steve Anton6fec8802017-12-04 10:37:29 -08006737
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006738bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006739 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006740 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006741 cricket::DtlsTransportInternal* dtls_transport,
6742 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006743 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006744 auto base_channel = GetChannel(mid);
6745 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006746 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006747 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006748 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006749 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006750 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006751
6752 call_->MediaTransportChange(media_transport);
6753
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006754 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006755}
6756
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006757PeerConnectionObserver* PeerConnection::Observer() const {
6758 // In earlier production code, the pointer was not cleared on close,
6759 // which might have led to undefined behavior if the observer was not
6760 // deallocated, or strange crashes if it was.
6761 // We use CHECK in order to catch such behavior if it exists.
6762 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6763 RTC_CHECK(observer_);
6764 return observer_;
6765}
6766
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006767CryptoOptions PeerConnection::GetCryptoOptions() {
6768 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6769 // after it has been removed.
6770 return configuration_.crypto_options.has_value()
6771 ? *configuration_.crypto_options
6772 : factory_->options().crypto_options;
6773}
6774
Harald Alvestrand89061872018-01-02 14:08:34 +01006775void PeerConnection::ClearStatsCache() {
6776 if (stats_collector_) {
6777 stats_collector_->ClearCachedStatsReport();
6778 }
6779}
6780
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006781void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006782 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6783 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006784}
6785
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006786} // namespace webrtc