blob: bf501d534eb9397a2e2e3da94b3490869380120a [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
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
27#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020030#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "logging/rtc_event_log/rtc_event_log.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "media/sctp/sctp_transport.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010033#include "pc/audio_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080034#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080035#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "pc/channel_manager.h"
37#include "pc/dtmf_sender.h"
38#include "pc/media_stream.h"
39#include "pc/media_stream_observer.h"
40#include "pc/remote_audio_source.h"
41#include "pc/rtp_media_utils.h"
42#include "pc/rtp_receiver.h"
43#include "pc/rtp_sender.h"
Harald Alvestrandc85328f2019-02-28 07:51:00 +010044#include "pc/sctp_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080045#include "pc/sctp_utils.h"
46#include "pc/sdp_utils.h"
47#include "pc/stream_collection.h"
Ruslan Burakov501bfba2019-02-11 10:29:19 +010048#include "pc/video_rtp_receiver.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/bind.h"
51#include "rtc_base/checks.h"
52#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010053#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080054#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020055#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020056#include "rtc_base/trace_event.h"
57#include "system_wrappers/include/clock.h"
58#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070059#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::ContentInfo;
62using cricket::ContentInfos;
63using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080064using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080065using cricket::RidDescription;
66using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080067using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::SimulcastDescription;
69using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080070using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080071using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080072using cricket::TransportInfo;
73
74using cricket::LOCAL_PORT_TYPE;
75using cricket::STUN_PORT_TYPE;
76using cricket::RELAY_PORT_TYPE;
77using cricket::PRFLX_PORT_TYPE;
78
Steve Antonba818672017-11-06 10:21:57 -080079namespace webrtc {
80
Steve Anton75737c02017-11-06 10:37:17 -080081// Error messages
82const char kBundleWithoutRtcpMux[] =
83 "rtcp-mux must be enabled when BUNDLE "
84 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080085const char kInvalidCandidates[] = "Description contains invalid candidates.";
86const char kInvalidSdp[] = "Invalid session description.";
87const char kMlineMismatchInAnswer[] =
88 "The order of m-lines in answer doesn't match order in offer. Rejecting "
89 "answer.";
90const char kMlineMismatchInSubsequentOffer[] =
91 "The order of m-lines in subsequent offer doesn't match order from "
92 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080093const char kSdpWithoutDtlsFingerprint[] =
94 "Called with SDP without DTLS fingerprint.";
95const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
96const char kSdpWithoutIceUfragPwd[] =
97 "Called with SDP without ice-ufrag and ice-pwd.";
98const char kSessionError[] = "Session error code: ";
99const char kSessionErrorDesc[] = "Session error description: ";
100const char kDtlsSrtpSetupFailureRtp[] =
101 "Couldn't set up DTLS-SRTP on RTP channel.";
102const char kDtlsSrtpSetupFailureRtcp[] =
103 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104
Steve Anton75737c02017-11-06 10:37:17 -0800105namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800107// UMA metric names.
108const char kSimulcastVersionApplyLocalDescription[] =
109 "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
110const char kSimulcastVersionApplyRemoteDescription[] =
111 "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
112const char kSimulcastNumberOfEncodings[] =
113 "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
114const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
115
Seth Hampson845e8782018-03-02 11:34:10 -0800116static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800117static const char kDefaultAudioSenderId[] = "defaulta0";
118static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700119
zhihuang8f65cdf2016-05-06 18:40:30 -0700120// The length of RTCP CNAMEs.
121static const int kRtcpCnameLength = 16;
122
Steve Antonad182762018-09-05 20:22:40 +0000123enum {
124 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
125 MSG_SET_SESSIONDESCRIPTION_FAILED,
126 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
127 MSG_GETSTATS,
128 MSG_FREE_DATACHANNELS,
129 MSG_REPORT_USAGE_PATTERN,
130};
131
Harald Alvestrand19793842018-06-25 12:03:50 +0200132static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
133
Steve Antonad182762018-09-05 20:22:40 +0000134struct SetSessionDescriptionMsg : public rtc::MessageData {
135 explicit SetSessionDescriptionMsg(
136 webrtc::SetSessionDescriptionObserver* observer)
137 : observer(observer) {}
138
139 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
140 RTCError error;
141};
142
143struct CreateSessionDescriptionMsg : public rtc::MessageData {
144 explicit CreateSessionDescriptionMsg(
145 webrtc::CreateSessionDescriptionObserver* observer)
146 : observer(observer) {}
147
148 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
149 RTCError error;
150};
151
152struct GetStatsMsg : public rtc::MessageData {
153 GetStatsMsg(webrtc::StatsObserver* observer,
154 webrtc::MediaStreamTrackInterface* track)
155 : observer(observer), track(track) {}
156 rtc::scoped_refptr<webrtc::StatsObserver> observer;
157 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
158};
159
deadbeefab9b2d12015-10-14 11:33:11 -0700160// Check if we can send |new_stream| on a PeerConnection.
161bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
162 webrtc::MediaStreamInterface* new_stream) {
163 if (!new_stream || !current_streams) {
164 return false;
165 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700166 if (current_streams->find(new_stream->id()) != nullptr) {
167 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100168 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700169 return false;
170 }
171 return true;
172}
173
deadbeef5e97fb52015-10-15 12:49:08 -0700174// If the direction is "recvonly" or "inactive", treat the description
175// as containing no streams.
176// See: https://code.google.com/p/webrtc/issues/detail?id=5054
177std::vector<cricket::StreamParams> GetActiveStreams(
178 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800179 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700180 ? desc->streams()
181 : std::vector<cricket::StreamParams>();
182}
183
deadbeefab9b2d12015-10-14 11:33:11 -0700184bool IsValidOfferToReceiveMedia(int value) {
185 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
186 return (value >= Options::kUndefined) &&
187 (value <= Options::kMaxOfferToReceiveMedia);
188}
189
zhihuang1c378ed2017-08-17 14:10:50 -0700190// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800191void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700192 const std::vector<rtc::scoped_refptr<
193 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700194 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200195 cricket::MediaDescriptionOptions* video_media_description_options,
196 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700197 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700198 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
199 if (audio_media_description_options) {
200 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700201 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700202 }
203 } else {
204 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
205 if (video_media_description_options) {
206 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800207 sender->id(), sender->internal()->stream_ids(), {},
208 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700209 }
210 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700211 }
zhihuang1c378ed2017-08-17 14:10:50 -0700212}
olka3c747662017-08-17 06:50:32 -0700213
zhihuang1c378ed2017-08-17 14:10:50 -0700214// Add options to |session_options| from |rtp_data_channels|.
215void AddRtpDataChannelOptions(
216 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
217 rtp_data_channels,
218 cricket::MediaDescriptionOptions* data_media_description_options) {
219 if (!data_media_description_options) {
220 return;
221 }
deadbeefab9b2d12015-10-14 11:33:11 -0700222 // Check for data channels.
223 for (const auto& kv : rtp_data_channels) {
224 const DataChannel* channel = kv.second;
225 if (channel->state() == DataChannel::kConnecting ||
226 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700227 // Legacy RTP data channels are signaled with the track/stream ID set to
228 // the data channel's label.
229 data_media_description_options->AddRtpDataChannel(channel->label(),
230 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700231 }
232 }
233}
234
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700235uint32_t ConvertIceTransportTypeToCandidateFilter(
236 PeerConnectionInterface::IceTransportsType type) {
237 switch (type) {
238 case PeerConnectionInterface::kNone:
239 return cricket::CF_NONE;
240 case PeerConnectionInterface::kRelay:
241 return cricket::CF_RELAY;
242 case PeerConnectionInterface::kNoHost:
243 return (cricket::CF_ALL & ~cricket::CF_HOST);
244 case PeerConnectionInterface::kAll:
245 return cricket::CF_ALL;
246 default:
nissec80e7412017-01-11 05:56:46 -0800247 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700248 }
249 return cricket::CF_NONE;
250}
251
deadbeef293e9262017-01-11 12:28:30 -0800252// Helper to set an error and return from a method.
253bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
254 if (error) {
255 error->set_type(type);
256 }
257 return type == webrtc::RTCErrorType::NONE;
258}
259
Steve Anton038834f2017-07-14 15:59:59 -0700260bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700261 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700262 if (error_out) {
263 *error_out = std::move(error);
264 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700265 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700266}
267
Steve Antonba818672017-11-06 10:21:57 -0800268std::string GetSignalingStateString(
269 PeerConnectionInterface::SignalingState state) {
270 switch (state) {
271 case PeerConnectionInterface::kStable:
272 return "kStable";
273 case PeerConnectionInterface::kHaveLocalOffer:
274 return "kHaveLocalOffer";
275 case PeerConnectionInterface::kHaveLocalPrAnswer:
276 return "kHavePrAnswer";
277 case PeerConnectionInterface::kHaveRemoteOffer:
278 return "kHaveRemoteOffer";
279 case PeerConnectionInterface::kHaveRemotePrAnswer:
280 return "kHaveRemotePrAnswer";
281 case PeerConnectionInterface::kClosed:
282 return "kClosed";
283 }
284 RTC_NOTREACHED();
285 return "";
286}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700287
Steve Anton75737c02017-11-06 10:37:17 -0800288IceCandidatePairType GetIceCandidatePairCounter(
289 const cricket::Candidate& local,
290 const cricket::Candidate& remote) {
291 const auto& l = local.type();
292 const auto& r = remote.type();
293 const auto& host = LOCAL_PORT_TYPE;
294 const auto& srflx = STUN_PORT_TYPE;
295 const auto& relay = RELAY_PORT_TYPE;
296 const auto& prflx = PRFLX_PORT_TYPE;
297 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800298 bool local_hostname =
299 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
300 bool remote_hostname = !remote.address().hostname().empty() &&
301 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800302 bool local_private = IPIsPrivate(local.address().ipaddr());
303 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800304 if (local_hostname) {
305 if (remote_hostname) {
306 return kIceCandidatePairHostNameHostName;
307 } else if (remote_private) {
308 return kIceCandidatePairHostNameHostPrivate;
309 } else {
310 return kIceCandidatePairHostNameHostPublic;
311 }
312 } else if (local_private) {
313 if (remote_hostname) {
314 return kIceCandidatePairHostPrivateHostName;
315 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800316 return kIceCandidatePairHostPrivateHostPrivate;
317 } else {
318 return kIceCandidatePairHostPrivateHostPublic;
319 }
320 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800321 if (remote_hostname) {
322 return kIceCandidatePairHostPublicHostName;
323 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800324 return kIceCandidatePairHostPublicHostPrivate;
325 } else {
326 return kIceCandidatePairHostPublicHostPublic;
327 }
328 }
329 }
330 if (l == host && r == srflx)
331 return kIceCandidatePairHostSrflx;
332 if (l == host && r == relay)
333 return kIceCandidatePairHostRelay;
334 if (l == host && r == prflx)
335 return kIceCandidatePairHostPrflx;
336 if (l == srflx && r == host)
337 return kIceCandidatePairSrflxHost;
338 if (l == srflx && r == srflx)
339 return kIceCandidatePairSrflxSrflx;
340 if (l == srflx && r == relay)
341 return kIceCandidatePairSrflxRelay;
342 if (l == srflx && r == prflx)
343 return kIceCandidatePairSrflxPrflx;
344 if (l == relay && r == host)
345 return kIceCandidatePairRelayHost;
346 if (l == relay && r == srflx)
347 return kIceCandidatePairRelaySrflx;
348 if (l == relay && r == relay)
349 return kIceCandidatePairRelayRelay;
350 if (l == relay && r == prflx)
351 return kIceCandidatePairRelayPrflx;
352 if (l == prflx && r == host)
353 return kIceCandidatePairPrflxHost;
354 if (l == prflx && r == srflx)
355 return kIceCandidatePairPrflxSrflx;
356 if (l == prflx && r == relay)
357 return kIceCandidatePairPrflxRelay;
358 return kIceCandidatePairMax;
359}
360
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800361// Logic to decide if an m= section can be recycled. This means that the new
362// m= section is not rejected, but the old local or remote m= section is
363// rejected. |old_content_one| and |old_content_two| refer to the m= section
364// of the old remote and old local descriptions in no particular order.
365// We need to check both the old local and remote because either
366// could be the most current from the latest negotation.
367bool IsMediaSectionBeingRecycled(SdpType type,
368 const ContentInfo& content,
369 const ContentInfo* old_content_one,
370 const ContentInfo* old_content_two) {
371 return type == SdpType::kOffer && !content.rejected &&
372 ((old_content_one && old_content_one->rejected) ||
373 (old_content_two && old_content_two->rejected));
374}
375
Steve Anton75737c02017-11-06 10:37:17 -0800376// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800377// |current_desc|. The number of m= sections in |new_desc| should be no
378// less than |current_desc|. In the case of checking an answer's
379// |new_desc|, the |current_desc| is the last offer that was set as the
380// local or remote. In the case of checking an offer's |new_desc| we
381// check against the local and remote descriptions stored from the last
382// negotiation, because either of these could be the most up to date for
383// possible rejected m sections. These are the |current_desc| and
384// |secondary_current_desc|.
385bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
386 const SessionDescription* secondary_current_desc,
387 const SessionDescription& new_desc,
388 const SdpType type) {
389 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800390 return false;
391 }
392
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800393 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
394 const cricket::ContentInfo* secondary_content_info = nullptr;
395 if (secondary_current_desc &&
396 i < secondary_current_desc->contents().size()) {
397 secondary_content_info = &secondary_current_desc->contents()[i];
398 }
399 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
400 &current_desc.contents()[i],
401 secondary_content_info)) {
402 // For new offer descriptions, if the media section can be recycled, it's
403 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800404 continue;
405 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800406 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800407 return false;
408 }
409 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800410 new_desc.contents()[i].media_description();
411 const MediaContentDescription* current_desc_mdesc =
412 current_desc.contents()[i].media_description();
413 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800414 return false;
415 }
416 }
417 return true;
418}
419
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800420bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
421 const SessionDescription& desc2) {
422 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800423}
424
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700425void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
426 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200427 // Array of structs needed to map {KeyExchangeProtocolType,
428 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
429 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
430 static constexpr struct {
431 KeyExchangeProtocolType protocol_type;
432 cricket::MediaType media_type;
433 KeyExchangeProtocolMedia protocol_media;
434 } kEnumCounterKeyProtocolMediaMap[] = {
435 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
436 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
437 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
438 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
439 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
440 kEnumCounterKeyProtocolMediaTypeDtlsData},
441 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
442 kEnumCounterKeyProtocolMediaTypeSdesAudio},
443 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
444 kEnumCounterKeyProtocolMediaTypeSdesVideo},
445 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
446 kEnumCounterKeyProtocolMediaTypeSdesData},
447 };
448
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700449 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
450 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100451
Mirko Bonadeiab499822018-09-11 10:43:20 +0200452 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
453 if (i.protocol_type == protocol_type && i.media_type == media_type) {
454 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
455 i.protocol_media,
456 kEnumCounterKeyProtocolMediaTypeMax);
457 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100458 }
459}
460
Harald Alvestrand76829d72018-07-18 23:24:36 +0200461void NoteAddIceCandidateResult(int result) {
462 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
463 kAddIceCandidateMax);
464}
465
Steve Anton75737c02017-11-06 10:37:17 -0800466// Checks that each non-rejected content has SDES crypto keys or a DTLS
467// fingerprint, unless it's in a BUNDLE group, in which case only the
468// BUNDLE-tag section (first media section/description in the BUNDLE group)
469// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
470// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
471// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700472RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800473 const cricket::ContentGroup* bundle =
474 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800475 for (const cricket::ContentInfo& content_info : desc->contents()) {
476 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800477 continue;
478 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100479 // Note what media is used with each crypto protocol, for all sections.
480 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
481 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700482 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800483 const std::string& mid = content_info.name;
484 if (bundle && bundle->HasContentName(mid) &&
485 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 // This isn't the first media section in the BUNDLE group, so it's not
487 // required to have crypto attributes, since only the crypto attributes
488 // from the first section actually get used.
489 continue;
490 }
491
492 // If the content isn't rejected or bundled into another m= section, crypto
493 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800494 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!media || !tinfo) {
497 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800498 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800499 }
500 if (dtls_enabled) {
501 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_WARNING)
503 << "Session description must have DTLS fingerprint if "
504 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800505 return RTCError(RTCErrorType::INVALID_PARAMETER,
506 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800507 }
508 } else {
509 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100510 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800511 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800512 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800513 }
514 }
515 }
Steve Anton8a006912017-12-04 15:25:56 -0800516 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800517}
518
519// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
520// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
521// media section/description in the BUNDLE group) needs a ufrag and pwd.
522bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
523 const cricket::ContentGroup* bundle =
524 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800525 for (const cricket::ContentInfo& content_info : desc->contents()) {
526 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800527 continue;
528 }
Steve Anton8a006912017-12-04 15:25:56 -0800529 const std::string& mid = content_info.name;
530 if (bundle && bundle->HasContentName(mid) &&
531 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800532 // This isn't the first media section in the BUNDLE group, so it's not
533 // required to have ufrag/password, since only the ufrag/password from
534 // the first section actually get used.
535 continue;
536 }
537
538 // If the content isn't rejected or bundled into another m= section,
539 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800540 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800541 if (!tinfo) {
542 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800544 return false;
545 }
546 if (tinfo->description.ice_ufrag.empty() ||
547 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100548 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800549 return false;
550 }
551 }
552 return true;
553}
554
Steve Anton75737c02017-11-06 10:37:17 -0800555// Get the SCTP port out of a SessionDescription.
556// Return -1 if not found.
557int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800558 const cricket::DataContentDescription* data_desc =
559 GetFirstDataContentDescription(session_description);
560 RTC_DCHECK(data_desc);
561 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800562 return -1;
563 }
Steve Anton75737c02017-11-06 10:37:17 -0800564 std::string value;
565 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
566 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800567 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800568 if (!codec.Matches(match_pattern)) {
569 continue;
570 }
571 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
572 return rtc::FromString<int>(value);
573 }
574 }
575 return -1;
576}
577
Steve Anton75737c02017-11-06 10:37:17 -0800578// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
579bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
580 const SessionDescriptionInterface* new_desc,
581 const std::string& content_name) {
582 if (!old_desc) {
583 return false;
584 }
585 const SessionDescription* new_sd = new_desc->description();
586 const SessionDescription* old_sd = old_desc->description();
587 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
588 if (!cinfo || cinfo->rejected) {
589 return false;
590 }
591 // If the content isn't rejected, check if ufrag and password has changed.
592 const cricket::TransportDescription* new_transport_desc =
593 new_sd->GetTransportDescriptionByName(content_name);
594 const cricket::TransportDescription* old_transport_desc =
595 old_sd->GetTransportDescriptionByName(content_name);
596 if (!new_transport_desc || !old_transport_desc) {
597 // No transport description exists. This is not an ICE restart.
598 return false;
599 }
600 if (cricket::IceCredentialsChanged(
601 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
602 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100603 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
604 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800605 return true;
606 }
607 return false;
608}
609
Steve Anton80dd7b52018-02-16 17:08:42 -0800610// Generates a string error message for SetLocalDescription/SetRemoteDescription
611// from an RTCError.
612std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
613 SdpType type,
614 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200615 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800616 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
617 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200618 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800619}
620
Seth Hampson5b4f0752018-04-02 16:31:36 -0700621std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
622 std::string output = "streams=[";
623 const char* separator = "";
624 for (const auto& stream_id : stream_ids) {
625 output.append(separator).append(stream_id);
626 separator = ", ";
627 }
628 output.append("]");
629 return output;
630}
631
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200632absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700633 int rtc_configuration_parameter) {
634 if (rtc_configuration_parameter ==
635 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200636 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700637 }
638 return rtc_configuration_parameter;
639}
640
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800641cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
642 switch (type) {
643 case DataMessageType::kText:
644 return cricket::DMT_TEXT;
645 case DataMessageType::kBinary:
646 return cricket::DMT_BINARY;
647 case DataMessageType::kControl:
648 return cricket::DMT_CONTROL;
649 default:
650 return cricket::DMT_NONE;
651 }
652 return cricket::DMT_NONE;
653}
654
655DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
656 switch (type) {
657 case cricket::DMT_TEXT:
658 return DataMessageType::kText;
659 case cricket::DMT_BINARY:
660 return DataMessageType::kBinary;
661 case cricket::DMT_CONTROL:
662 return DataMessageType::kControl;
663 case cricket::DMT_NONE:
664 default:
665 RTC_NOTREACHED();
666 }
667 return DataMessageType::kControl;
668}
669
Amit Hilbuche2a284d2019-03-05 12:36:31 -0800670void ReportSimulcastApiVersion(const char* name,
671 const SessionDescription& session) {
672 bool has_legacy = false;
673 bool has_spec_compliant = false;
674 for (const ContentInfo& content : session.contents()) {
675 if (!content.description) {
676 continue;
677 }
678 has_spec_compliant |= content.description->HasSimulcast();
679 for (const StreamParams& sp : content.description->streams()) {
680 has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
681 }
682 }
683
684 if (has_legacy) {
685 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
686 kSimulcastApiVersionMax);
687 }
688 if (has_spec_compliant) {
689 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
690 kSimulcastApiVersionMax);
691 }
692 if (!has_legacy && !has_spec_compliant) {
693 RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
694 kSimulcastApiVersionMax);
695 }
696}
697
Steve Anton75737c02017-11-06 10:37:17 -0800698} // namespace
699
Henrik Boström31638672017-11-23 17:48:32 +0100700// Upon completion, posts a task to execute the callback of the
701// SetSessionDescriptionObserver asynchronously on the same thread. At this
702// point, the state of the peer connection might no longer reflect the effects
703// of the SetRemoteDescription operation, as the peer connection could have been
704// modified during the post.
705// TODO(hbos): Remove this class once we remove the version of
706// PeerConnectionInterface::SetRemoteDescription() that takes a
707// SetSessionDescriptionObserver as an argument.
708class PeerConnection::SetRemoteDescriptionObserverAdapter
709 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
710 public:
711 SetRemoteDescriptionObserverAdapter(
712 rtc::scoped_refptr<PeerConnection> pc,
713 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
714 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
715
716 // SetRemoteDescriptionObserverInterface implementation.
717 void OnSetRemoteDescriptionComplete(RTCError error) override {
718 if (error.ok())
719 pc_->PostSetSessionDescriptionSuccess(wrapper_);
720 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100721 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100722 }
723
724 private:
725 rtc::scoped_refptr<PeerConnection> pc_;
726 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
727};
728
deadbeef293e9262017-01-11 12:28:30 -0800729bool PeerConnectionInterface::RTCConfiguration::operator==(
730 const PeerConnectionInterface::RTCConfiguration& o) const {
731 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700732 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800733 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000734 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700735 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800736 BundlePolicy bundle_policy;
737 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700738 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
739 int ice_candidate_pool_size;
740 bool disable_ipv6;
741 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700742 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100743 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700744 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200745 absl::optional<int> screencast_min_bitrate;
746 absl::optional<bool> combined_audio_video_bwe;
747 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800748 TcpCandidatePolicy tcp_candidate_policy;
749 CandidateNetworkPolicy candidate_network_policy;
750 int audio_jitter_buffer_max_packets;
751 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100752 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100753 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800754 int ice_connection_receiving_timeout;
755 int ice_backup_candidate_pair_ping_interval;
756 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800757 bool prioritize_most_likely_ice_candidate_pairs;
758 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800759 bool prune_turn_ports;
760 bool presume_writable_when_fully_relayed;
761 bool enable_ice_renomination;
762 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200763 absl::optional<int> ice_check_interval_strong_connectivity;
764 absl::optional<int> ice_check_interval_weak_connectivity;
765 absl::optional<int> ice_check_min_interval;
766 absl::optional<int> ice_unwritable_timeout;
767 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800768 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200769 absl::optional<int> stun_candidate_keepalive_interval;
770 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200771 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800772 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200773 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700774 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700775 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700776 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700777 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100778 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800779 };
780 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
781 "Did you add something to RTCConfiguration and forget to "
782 "update operator==?");
783 return type == o.type && servers == o.servers &&
784 bundle_policy == o.bundle_policy &&
785 rtcp_mux_policy == o.rtcp_mux_policy &&
786 tcp_candidate_policy == o.tcp_candidate_policy &&
787 candidate_network_policy == o.candidate_network_policy &&
788 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
789 audio_jitter_buffer_fast_accelerate ==
790 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100791 audio_jitter_buffer_min_delay_ms ==
792 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100793 audio_jitter_buffer_enable_rtx_handling ==
794 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800795 ice_connection_receiving_timeout ==
796 o.ice_connection_receiving_timeout &&
797 ice_backup_candidate_pair_ping_interval ==
798 o.ice_backup_candidate_pair_ping_interval &&
799 continual_gathering_policy == o.continual_gathering_policy &&
800 certificates == o.certificates &&
801 prioritize_most_likely_ice_candidate_pairs ==
802 o.prioritize_most_likely_ice_candidate_pairs &&
803 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800804 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700805 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100806 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800807 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800808 screencast_min_bitrate == o.screencast_min_bitrate &&
809 combined_audio_video_bwe == o.combined_audio_video_bwe &&
810 enable_dtls_srtp == o.enable_dtls_srtp &&
811 ice_candidate_pool_size == o.ice_candidate_pool_size &&
812 prune_turn_ports == o.prune_turn_ports &&
813 presume_writable_when_fully_relayed ==
814 o.presume_writable_when_fully_relayed &&
815 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800816 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800817 ice_check_interval_strong_connectivity ==
818 o.ice_check_interval_strong_connectivity &&
819 ice_check_interval_weak_connectivity ==
820 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700821 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700822 ice_unwritable_timeout == o.ice_unwritable_timeout &&
823 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800824 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800825 stun_candidate_keepalive_interval ==
826 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200827 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800828 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800829 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700830 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700831 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700832 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700833 use_media_transport_for_data_channels ==
834 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100835 crypto_options == o.crypto_options &&
836 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800837}
838
839bool PeerConnectionInterface::RTCConfiguration::operator!=(
840 const PeerConnectionInterface::RTCConfiguration& o) const {
841 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800842}
843
zhihuang8f65cdf2016-05-06 18:40:30 -0700844// Generate a RTCP CNAME when a PeerConnection is created.
845std::string GenerateRtcpCname() {
846 std::string cname;
847 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100848 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800849 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700850 }
851 return cname;
852}
853
zhihuang1c378ed2017-08-17 14:10:50 -0700854bool ValidateOfferAnswerOptions(
855 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
856 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
857 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700858}
859
zhihuang1c378ed2017-08-17 14:10:50 -0700860// From |rtc_options|, fill parts of |session_options| shared by all generated
861// m= sections (in other words, nothing that involves a map/array).
862void ExtractSharedMediaSessionOptions(
863 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
864 cricket::MediaSessionOptions* session_options) {
865 session_options->vad_enabled = rtc_options.voice_activity_detection;
866 session_options->bundle_enabled = rtc_options.use_rtp_mux;
867}
zhihuanga77e6bb2017-08-14 18:17:48 -0700868
zhihuang38ede132017-06-15 12:52:32 -0700869PeerConnection::PeerConnection(PeerConnectionFactory* factory,
870 std::unique_ptr<RtcEventLog> event_log,
871 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700873 event_log_(std::move(event_log)),
Karl Wibergb03ab712019-02-14 11:59:57 +0100874 event_log_ptr_(event_log_.get()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700875 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700876 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700877 remote_streams_(StreamCollection::Create()),
Karl Wiberg6cab5c82019-03-26 09:57:01 +0100878 call_(std::move(call)),
879 call_ptr_(call_.get()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000880
881PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100882 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800883 RTC_DCHECK_RUN_ON(signaling_thread());
884
Steve Anton8af21862017-12-15 11:20:13 -0800885 // Need to stop transceivers before destroying the stats collector because
886 // AudioRtpSender has a reference to the StatsCollector it will update when
887 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100888 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800889 transceiver->Stop();
890 }
Steve Anton4171afb2017-11-20 10:20:22 -0800891
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700892 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800893 if (stats_collector_) {
894 stats_collector_->WaitForPendingRequest();
895 stats_collector_ = nullptr;
896 }
Steve Anton75737c02017-11-06 10:37:17 -0800897
Steve Anton8af21862017-12-15 11:20:13 -0800898 // Don't destroy BaseChannels until after stats has been cleaned up so that
899 // the last stats request can still read from the channels.
900 DestroyAllChannels();
901
Mirko Bonadei675513b2017-11-09 11:09:25 +0100902 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800903
904 webrtc_session_desc_factory_.reset();
905 sctp_invoker_.reset();
906 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800907 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800908 transport_controller_.reset();
909
deadbeef91dd5672016-05-18 16:55:30 -0700910 // port_allocator_ lives on the network thread and should be destroyed there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100911 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
912 RTC_DCHECK_RUN_ON(network_thread());
913 port_allocator_.reset();
914 });
eladalon248fd4f2017-09-06 05:18:15 -0700915 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700916 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +0100917 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -0700918 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800919 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700920 event_log_.reset();
921 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922}
923
Steve Anton8af21862017-12-15 11:20:13 -0800924void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800925 // Destroy video channels first since they may have a pointer to a voice
926 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100927 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800928 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800929 DestroyTransceiverChannel(transceiver);
930 }
931 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100932 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800933 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800934 DestroyTransceiverChannel(transceiver);
935 }
936 }
937 DestroyDataChannel();
938}
939
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000941 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700942 PeerConnectionDependencies dependencies) {
Karl Wiberg744310f2019-02-14 10:18:56 +0100943 RTC_DCHECK_RUN_ON(signaling_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +0100944 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +0100945 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700946
947 RTCError config_error = ValidateConfiguration(configuration);
948 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100949 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700950 return false;
951 }
952
Benjamin Wrightcab58882018-05-02 15:12:47 -0700953 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100954 RTC_LOG(LS_ERROR)
955 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100956 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800957 return false;
958 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200959
Benjamin Wrightcab58882018-05-02 15:12:47 -0700960 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800961 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100962 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100963 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800964 return false;
965 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700966
Benjamin Wrightcab58882018-05-02 15:12:47 -0700967 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700968 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700969 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700970 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800971
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200972 cricket::ServerAddresses stun_servers;
973 std::vector<cricket::RelayServerConfig> turn_servers;
974
975 RTCErrorType parse_error =
976 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
977 if (parse_error != RTCErrorType::NONE) {
978 return false;
979 }
980
deadbeef91dd5672016-05-18 16:55:30 -0700981 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700982 // there.
Karl Wibergfb3be392019-03-22 14:13:22 +0100983 const auto pa_result =
984 network_thread()->Invoke<InitializePortAllocatorResult>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200985 RTC_FROM_HERE,
986 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
Karl Wibergfb3be392019-03-22 14:13:22 +0100987 stun_servers, turn_servers, configuration));
988
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200989 // If initialization was successful, note if STUN or TURN servers
990 // were supplied.
991 if (!stun_servers.empty()) {
992 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
993 }
994 if (!turn_servers.empty()) {
995 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
996 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700998 // Send information about IPv4/IPv6 status.
999 PeerConnectionAddressFamilyCounter address_family;
Karl Wibergfb3be392019-03-22 14:13:22 +01001000 if (pa_result.enable_ipv6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001001 address_family = kPeerConnection_IPv6;
1002 } else {
1003 address_family = kPeerConnection_IPv4;
1004 }
1005 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
1006 kPeerConnectionAddressFamilyCounter_Max);
1007
Zhi Huange830e682018-03-30 10:48:35 -07001008 const PeerConnectionFactoryInterface::Options& options = factory_->options();
1009
Steve Anton75737c02017-11-06 10:37:17 -08001010 // RFC 3264: The numeric value of the session id and version in the
1011 // o line MUST be representable with a "64 bit signed integer".
1012 // Due to this constraint session id |session_id_| is max limited to
1013 // LLONG_MAX.
1014 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -07001015 JsepTransportController::Config config;
1016 config.redetermine_role_on_ice_restart =
1017 configuration.redetermine_role_on_ice_restart;
1018 config.ssl_max_version = factory_->options().ssl_max_version;
1019 config.disable_encryption = options.disable_encryption;
1020 config.bundle_policy = configuration.bundle_policy;
1021 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001022 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
1023 // stub.
1024 config.crypto_options = configuration.crypto_options.has_value()
1025 ? *configuration.crypto_options
1026 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -07001027 config.transport_observer = this;
Karl Wibergb03ab712019-02-14 11:59:57 +01001028 config.event_log = event_log_ptr_;
Zhi Huange830e682018-03-30 10:48:35 -07001029#if defined(ENABLE_EXTERNAL_AUTH)
1030 config.enable_external_auth = true;
1031#endif
Zhi Huangb57e1692018-06-12 11:41:11 -07001032 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001033
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001034 if (configuration.use_media_transport ||
1035 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001036 if (!factory_->media_transport_factory()) {
1037 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001038 << "PeerConnecton is initialized with use_media_transport = true or "
1039 << "use_media_transport_for_data_channels = true "
1040 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001041 return false;
1042 }
1043
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08001044 if (configuration.use_media_transport ||
1045 configuration.use_media_transport_for_data_channels) {
1046 // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
1047 // RTP media transport is introduced. But until then, we require SDES to
1048 // be enabled.
1049 if (configuration.enable_dtls_srtp.has_value() &&
1050 configuration.enable_dtls_srtp.value()) {
1051 RTC_LOG(LS_WARNING)
1052 << "When media transport is used, SDES must be enabled. Set "
1053 "configuration.enable_dtls_srtp to false. use_media_transport="
1054 << configuration.use_media_transport
1055 << ", use_media_transport_for_data_channels="
1056 << configuration.use_media_transport_for_data_channels;
1057 return false;
1058 }
1059 }
1060
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08001061 config.use_media_transport_for_media = configuration.use_media_transport;
1062 config.use_media_transport_for_data_channels =
1063 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001064 config.media_transport_factory = factory_->media_transport_factory();
1065 }
1066
Zhi Huange830e682018-03-30 10:48:35 -07001067 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001068 signaling_thread(), network_thread(), port_allocator_.get(),
1069 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001070 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001071 this, &PeerConnection::OnTransportControllerConnectionState);
1072 transport_controller_->SignalStandardizedIceConnectionState.connect(
1073 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001074 transport_controller_->SignalConnectionState.connect(
1075 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001076 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001077 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001078 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001079 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001080 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001081 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1082 transport_controller_->SignalDtlsHandshakeError.connect(
1083 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1084
1085 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001086
deadbeefab9b2d12015-10-14 11:33:11 -07001087 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001088 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001089
Steve Antonba818672017-11-06 10:21:57 -08001090 configuration_ = configuration;
Karl Wiberg5966c502019-02-21 23:55:09 +01001091 use_media_transport_ = configuration.use_media_transport;
Steve Antonba818672017-11-06 10:21:57 -08001092
Steve Anton75737c02017-11-06 10:37:17 -08001093 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1094 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1095 if (!configuration.certificates.empty()) {
1096 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1097 // just picking the first one. The decision should be made based on the DTLS
1098 // handshake. The DTLS negotiations need to know about all certificates.
1099 certificate = configuration.certificates[0];
1100 }
1101
Steve Antond25da372017-11-06 14:50:29 -08001102 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001103
1104 if (options.disable_encryption) {
1105 dtls_enabled_ = false;
1106 } else {
1107 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001108 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001109 // |configuration| can override the default |dtls_enabled_| value.
1110 if (configuration.enable_dtls_srtp) {
1111 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1112 }
1113 }
1114
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001115 if (configuration.use_media_transport_for_data_channels) {
1116 if (configuration.enable_rtp_data_channel) {
1117 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1118 "use_media_transport_for_data_channels are "
1119 "incompatible and cannot both be set to true";
1120 return false;
1121 }
1122 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1123 } else if (configuration.enable_rtp_data_channel) {
1124 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1125 // set. It takes precendence over the disable_sctp_data_channels
1126 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001127 data_channel_type_ = cricket::DCT_RTP;
1128 } else {
1129 // DTLS has to be enabled to use SCTP.
1130 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1131 data_channel_type_ = cricket::DCT_SCTP;
1132 }
1133 }
1134
1135 video_options_.screencast_min_bitrate_kbps =
1136 configuration.screencast_min_bitrate;
1137 audio_options_.combined_audio_video_bwe =
1138 configuration.combined_audio_video_bwe;
1139
1140 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001141 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001142
1143 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001144 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001145
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001146 audio_options_.audio_jitter_buffer_min_delay_ms =
1147 configuration.audio_jitter_buffer_min_delay_ms;
1148
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001149 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1150 configuration.audio_jitter_buffer_enable_rtx_handling;
1151
Steve Anton75737c02017-11-06 10:37:17 -08001152 // Whether the certificate generator/certificate is null or not determines
1153 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1154 // the right instructions by clearing the variables if needed.
1155 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001156 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001157 certificate = nullptr;
1158 } else if (certificate) {
1159 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001160 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001161 }
1162
1163 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1164 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001165 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001166 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1167 this, &PeerConnection::OnCertificateReady);
1168
1169 if (options.disable_encryption) {
1170 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1171 }
1172
1173 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001174 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001175 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001176
Steve Anton4171afb2017-11-20 10:20:22 -08001177 // Add default audio/video transceivers for Plan B SDP.
1178 if (!IsUnifiedPlan()) {
1179 transceivers_.push_back(
1180 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1181 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1182 transceivers_.push_back(
1183 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1184 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1185 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001186 int delay_ms =
1187 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001188 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1189 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001190 return true;
1191}
1192
Steve Anton038834f2017-07-14 15:59:59 -07001193RTCError PeerConnection::ValidateConfiguration(
1194 const RTCConfiguration& config) const {
1195 if (config.ice_regather_interval_range &&
1196 config.continual_gathering_policy == GATHER_ONCE) {
1197 return RTCError(RTCErrorType::INVALID_PARAMETER,
1198 "ice_regather_interval_range specified but continual "
1199 "gathering policy is GATHER_ONCE");
1200 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001201 auto result =
1202 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1203 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001204}
1205
Yves Gerey665174f2018-06-19 15:03:05 +02001206rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001207 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001208 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1209 "Plan SdpSemantics. Please use GetSenders "
1210 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001211 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001212}
1213
Yves Gerey665174f2018-06-19 15:03:05 +02001214rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Karl Wiberg5966c502019-02-21 23:55:09 +01001215 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001216 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1217 "Plan SdpSemantics. Please use GetReceivers "
1218 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001219 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220}
1221
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001222bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001223 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001224 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1225 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001226 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227 if (IsClosed()) {
1228 return false;
1229 }
deadbeefab9b2d12015-10-14 11:33:11 -07001230 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001231 return false;
1232 }
deadbeefab9b2d12015-10-14 11:33:11 -07001233
1234 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001235 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1236 observer->SignalAudioTrackAdded.connect(this,
1237 &PeerConnection::OnAudioTrackAdded);
1238 observer->SignalAudioTrackRemoved.connect(
1239 this, &PeerConnection::OnAudioTrackRemoved);
1240 observer->SignalVideoTrackAdded.connect(this,
1241 &PeerConnection::OnVideoTrackAdded);
1242 observer->SignalVideoTrackRemoved.connect(
1243 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001244 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001245
deadbeefab9b2d12015-10-14 11:33:11 -07001246 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001247 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001248 }
1249 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001250 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001251 }
1252
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001253 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001254 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001255 return true;
1256}
1257
1258void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001259 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001260 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1261 "Plan SdpSemantics. Please use RemoveTrack "
1262 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001263 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001264 if (!IsClosed()) {
1265 for (const auto& track : local_stream->GetAudioTracks()) {
1266 RemoveAudioTrack(track.get(), local_stream);
1267 }
1268 for (const auto& track : local_stream->GetVideoTracks()) {
1269 RemoveVideoTrack(track.get(), local_stream);
1270 }
deadbeefab9b2d12015-10-14 11:33:11 -07001271 }
deadbeefab9b2d12015-10-14 11:33:11 -07001272 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001273 stream_observers_.erase(
1274 std::remove_if(
1275 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001276 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001277 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001278 }),
1279 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001280
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281 if (IsClosed()) {
1282 return;
1283 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001284 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285}
1286
Steve Anton2d6c76a2018-01-05 17:10:52 -08001287RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001288 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001289 const std::vector<std::string>& stream_ids) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001290 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton2d6c76a2018-01-05 17:10:52 -08001291 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001292 if (!track) {
1293 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1294 }
1295 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1296 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1297 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1298 "Track has invalid kind: " + track->kind());
1299 }
Steve Antonf9381f02017-12-14 10:23:57 -08001300 if (IsClosed()) {
1301 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1302 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001303 }
Steve Anton4171afb2017-11-20 10:20:22 -08001304 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001305 LOG_AND_RETURN_ERROR(
1306 RTCErrorType::INVALID_PARAMETER,
1307 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001308 }
Steve Antonf9381f02017-12-14 10:23:57 -08001309 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001310 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1311 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001312 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001313 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001314 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001315 }
1316 return sender_or_error;
1317}
deadbeefe1f9d832016-01-14 15:35:42 -08001318
Steve Antonf9381f02017-12-14 10:23:57 -08001319RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1320PeerConnection::AddTrackPlanB(
1321 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001322 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001323 if (stream_ids.size() > 1u) {
1324 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1325 "AddTrack with more than one stream is not "
1326 "supported with Plan B semantics.");
1327 }
1328 std::vector<std::string> adjusted_stream_ids = stream_ids;
1329 if (adjusted_stream_ids.empty()) {
1330 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1331 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001332 cricket::MediaType media_type =
1333 (track->kind() == MediaStreamTrackInterface::kAudioKind
1334 ? cricket::MEDIA_TYPE_AUDIO
1335 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001336 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001337 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001338 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001339 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001340 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001341 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001342 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001343 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001344 if (sender_info) {
1345 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001346 }
Steve Antonf9381f02017-12-14 10:23:57 -08001347 } else {
1348 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001349 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001350 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001351 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001352 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001353 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001354 if (sender_info) {
1355 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001356 }
deadbeefe1f9d832016-01-14 15:35:42 -08001357 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001358 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001359}
deadbeefe1f9d832016-01-14 15:35:42 -08001360
Steve Antonf9381f02017-12-14 10:23:57 -08001361RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1362PeerConnection::AddTrackUnifiedPlan(
1363 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001364 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001365 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1366 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001367 RTC_LOG(LS_INFO) << "Reusing an existing "
1368 << cricket::MediaTypeToString(transceiver->media_type())
1369 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001370 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001371 transceiver->internal()->set_direction(
1372 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001373 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001374 transceiver->internal()->set_direction(
1375 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001376 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001377 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001378 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001379 } else {
1380 cricket::MediaType media_type =
1381 (track->kind() == MediaStreamTrackInterface::kAudioKind
1382 ? cricket::MEDIA_TYPE_AUDIO
1383 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001384 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1385 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001386 std::string sender_id = track->id();
1387 // Avoid creating a sender with an existing ID by generating a random ID.
1388 // This can happen if this is the second time AddTrack has created a sender
1389 // for this track.
1390 if (FindSenderById(sender_id)) {
1391 sender_id = rtc::CreateRandomUuid();
1392 }
Florent Castelli892acf02018-10-01 22:47:20 +02001393 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001394 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1395 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001396 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001397 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001398 }
Steve Antonf9381f02017-12-14 10:23:57 -08001399 return transceiver->sender();
1400}
1401
1402rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1403PeerConnection::FindFirstTransceiverForAddedTrack(
1404 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1405 RTC_DCHECK(track);
1406 for (auto transceiver : transceivers_) {
1407 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001408 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001409 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001410 !transceiver->internal()->has_ever_been_used_to_send() &&
1411 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001412 return transceiver;
1413 }
1414 }
1415 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001416}
1417
1418bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1419 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001420 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001421}
1422
Steve Anton24db5732018-07-23 10:27:33 -07001423RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001424 rtc::scoped_refptr<RtpSenderInterface> sender) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001425 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonf9381f02017-12-14 10:23:57 -08001426 if (!sender) {
1427 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1428 }
deadbeefe1f9d832016-01-14 15:35:42 -08001429 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1431 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001432 }
Steve Antonf9381f02017-12-14 10:23:57 -08001433 if (IsUnifiedPlan()) {
1434 auto transceiver = FindTransceiverBySender(sender);
1435 if (!transceiver || !sender->track()) {
1436 return RTCError::OK();
1437 }
1438 sender->SetTrack(nullptr);
1439 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001440 transceiver->internal()->set_direction(
1441 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001442 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001443 transceiver->internal()->set_direction(
1444 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001445 }
Steve Anton4171afb2017-11-20 10:20:22 -08001446 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001447 bool removed;
1448 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1449 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1450 } else {
1451 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1452 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1453 }
1454 if (!removed) {
1455 LOG_AND_RETURN_ERROR(
1456 RTCErrorType::INVALID_PARAMETER,
1457 "Couldn't find sender " + sender->id() + " to remove.");
1458 }
Steve Anton4171afb2017-11-20 10:20:22 -08001459 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001460 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001461 return RTCError::OK();
1462}
1463
1464rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1465PeerConnection::FindTransceiverBySender(
1466 rtc::scoped_refptr<RtpSenderInterface> sender) {
1467 for (auto transceiver : transceivers_) {
1468 if (transceiver->sender() == sender) {
1469 return transceiver;
1470 }
1471 }
1472 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001473}
1474
Steve Anton9158ef62017-11-27 13:01:52 -08001475RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1476PeerConnection::AddTransceiver(
1477 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1478 return AddTransceiver(track, RtpTransceiverInit());
1479}
1480
1481RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1482PeerConnection::AddTransceiver(
1483 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1484 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001485 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001486 RTC_CHECK(IsUnifiedPlan())
1487 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001488 if (!track) {
1489 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1490 }
1491 cricket::MediaType media_type;
1492 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1493 media_type = cricket::MEDIA_TYPE_AUDIO;
1494 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1495 media_type = cricket::MEDIA_TYPE_VIDEO;
1496 } else {
1497 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1498 "Track kind is not audio or video");
1499 }
1500 return AddTransceiver(media_type, track, init);
1501}
1502
1503RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1504PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1505 return AddTransceiver(media_type, RtpTransceiverInit());
1506}
1507
1508RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1509PeerConnection::AddTransceiver(cricket::MediaType media_type,
1510 const RtpTransceiverInit& init) {
Karl Wiberg744310f2019-02-14 10:18:56 +01001511 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001512 RTC_CHECK(IsUnifiedPlan())
1513 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001514 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1515 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1516 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1517 "media type is not audio or video");
1518 }
1519 return AddTransceiver(media_type, nullptr, init);
1520}
1521
1522RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1523PeerConnection::AddTransceiver(
1524 cricket::MediaType media_type,
1525 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001526 const RtpTransceiverInit& init,
1527 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001528 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1529 media_type == cricket::MEDIA_TYPE_VIDEO));
1530 if (track) {
1531 RTC_DCHECK_EQ(media_type,
1532 (track->kind() == MediaStreamTrackInterface::kAudioKind
1533 ? cricket::MEDIA_TYPE_AUDIO
1534 : cricket::MEDIA_TYPE_VIDEO));
1535 }
1536
Amit Hilbuche2a284d2019-03-05 12:36:31 -08001537 RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
1538 init.send_encodings.size(), 0, 7, 8);
1539
Amit Hilbuchaa584152019-02-06 17:09:52 -08001540 size_t num_rids = absl::c_count_if(init.send_encodings,
1541 [](const RtpEncodingParameters& encoding) {
1542 return !encoding.rid.empty();
1543 });
1544 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001545 LOG_AND_RETURN_ERROR(
Amit Hilbuchaa584152019-02-06 17:09:52 -08001546 RTCErrorType::INVALID_PARAMETER,
1547 "RIDs must be provided for either all or none of the send encodings.");
Emircan Uysaler78323432019-02-08 20:41:39 +00001548 }
1549
Amit Hilbuchaa584152019-02-06 17:09:52 -08001550 if (absl::c_any_of(init.send_encodings,
1551 [](const RtpEncodingParameters& encoding) {
1552 return encoding.ssrc.has_value();
1553 })) {
1554 LOG_AND_RETURN_ERROR(
1555 RTCErrorType::UNSUPPORTED_PARAMETER,
1556 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001557 }
1558
1559 RtpParameters parameters;
1560 parameters.encodings = init.send_encodings;
Amit Hilbuchaa584152019-02-06 17:09:52 -08001561
1562 // Encodings are dropped from the tail if too many are provided.
1563 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1564 parameters.encodings.erase(
1565 parameters.encodings.begin() + kMaxSimulcastStreams,
1566 parameters.encodings.end());
1567 }
1568
1569 // Single RID should be removed.
1570 if (parameters.encodings.size() == 1 &&
1571 !parameters.encodings[0].rid.empty()) {
1572 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1573 parameters.encodings[0].rid.clear();
1574 }
1575
1576 // If RIDs were not provided, they are generated for simulcast scenario.
1577 if (parameters.encodings.size() > 1 && num_rids == 0) {
1578 rtc::UniqueStringGenerator rid_generator;
1579 for (RtpEncodingParameters& encoding : parameters.encodings) {
1580 encoding.rid = rid_generator();
1581 }
1582 }
1583
Florent Castelli892acf02018-10-01 22:47:20 +02001584 if (UnimplementedRtpParameterHasValue(parameters)) {
1585 LOG_AND_RETURN_ERROR(
1586 RTCErrorType::UNSUPPORTED_PARAMETER,
1587 "Attempted to set an unimplemented parameter of RtpParameters.");
1588 }
Steve Anton9158ef62017-11-27 13:01:52 -08001589
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001590 auto result = cricket::CheckRtpParametersValues(parameters);
1591 if (!result.ok()) {
1592 LOG_AND_RETURN_ERROR(result.type(), result.message());
1593 }
1594
Steve Anton3d954a62018-04-02 11:27:23 -07001595 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1596 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001597 // Set the sender ID equal to the track ID if the track is specified unless
1598 // that sender ID is already in use.
1599 std::string sender_id =
1600 (track && !FindSenderById(track->id()) ? track->id()
1601 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001602 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchaa584152019-02-06 17:09:52 -08001603 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001604 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1605 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1606 transceiver->internal()->set_direction(init.direction);
1607
Steve Anton22da89f2018-01-25 13:58:07 -08001608 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001609 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001610 }
Steve Antonf9381f02017-12-14 10:23:57 -08001611
1612 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1613}
1614
Steve Anton02ee47c2018-01-10 16:26:06 -08001615rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1616PeerConnection::CreateSender(
1617 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001618 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001619 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001620 const std::vector<std::string>& stream_ids,
1621 const std::vector<RtpEncodingParameters>& send_encodings) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001622 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton9158ef62017-11-27 13:01:52 -08001623 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001624 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1625 RTC_DCHECK(!track ||
1626 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1627 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1628 signaling_thread(),
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001629 AudioRtpSender::Create(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001630 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001631 } else {
1632 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1633 RTC_DCHECK(!track ||
1634 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1635 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001636 signaling_thread(), VideoRtpSender::Create(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001637 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001638 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001639 bool set_track_succeeded = sender->SetTrack(track);
1640 RTC_DCHECK(set_track_succeeded);
1641 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001642 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001643 return sender;
1644}
1645
1646rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1647PeerConnection::CreateReceiver(cricket::MediaType media_type,
1648 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001649 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1650 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001651 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001652 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001653 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1654 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001655 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001656 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001657 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001658 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001659 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1660 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001661 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001662 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001663 return receiver;
1664}
1665
1666rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1667PeerConnection::CreateAndAddTransceiver(
1668 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1669 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1670 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001671 // Ensure that the new sender does not have an ID that is already in use by
1672 // another sender.
1673 // Allow receiver IDs to conflict since those come from remote SDP (which
1674 // could be invalid, but should not cause a crash).
1675 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001676 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1677 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001678 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001679 transceiver->internal()->SignalNegotiationNeeded.connect(
1680 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001681 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001682}
1683
Steve Anton52d86772018-02-20 15:48:12 -08001684void PeerConnection::OnNegotiationNeeded() {
1685 RTC_DCHECK_RUN_ON(signaling_thread());
1686 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001687 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001688}
1689
deadbeeffac06552015-11-25 11:26:01 -08001690rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001691 const std::string& kind,
1692 const std::string& stream_id) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001693 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001694 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1695 "Plan SdpSemantics. Please use AddTransceiver "
1696 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001697 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001698 if (IsClosed()) {
1699 return nullptr;
1700 }
Steve Anton4171afb2017-11-20 10:20:22 -08001701
Seth Hampson5b4f0752018-04-02 16:31:36 -07001702 // Internally we need to have one stream with Plan B semantics, so we
1703 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001704 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001705 if (stream_id.empty()) {
1706 stream_ids.push_back(rtc::CreateRandomUuid());
1707 RTC_LOG(LS_INFO)
1708 << "No stream_id specified for sender. Generated stream ID: "
1709 << stream_ids[0];
1710 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001711 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001712 }
1713
Steve Anton4171afb2017-11-20 10:20:22 -08001714 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001715 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001716 if (kind == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001717 auto audio_sender = AudioRtpSender::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001718 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001719 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001720 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001721 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001722 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001723 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Amit Hilbuchea7ef2a2019-02-19 15:20:21 -08001724 auto video_sender =
1725 VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001726 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001727 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001728 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001729 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001730 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001731 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001732 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001733 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001734 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001735
deadbeefe1f9d832016-01-14 15:35:42 -08001736 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001737}
1738
deadbeef70ab1a12015-09-28 16:53:55 -07001739std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1740 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001741 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001742 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001743 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001744 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001745 }
1746 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001747}
1748
Steve Anton4171afb2017-11-20 10:20:22 -08001749std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1750PeerConnection::GetSendersInternal() const {
1751 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1752 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001753 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001754 auto senders = transceiver->internal()->senders();
1755 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1756 }
1757 return all_senders;
1758}
1759
deadbeef70ab1a12015-09-28 16:53:55 -07001760std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1761PeerConnection::GetReceivers() const {
Karl Wiberga58e1692019-03-26 13:33:43 +01001762 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeefa601f5c2016-06-06 14:27:39 -07001763 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001764 for (const auto& receiver : GetReceiversInternal()) {
1765 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001766 }
1767 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001768}
1769
Steve Anton4171afb2017-11-20 10:20:22 -08001770std::vector<
1771 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1772PeerConnection::GetReceiversInternal() const {
1773 std::vector<
1774 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1775 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001776 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001777 auto receivers = transceiver->internal()->receivers();
1778 all_receivers.insert(all_receivers.end(), receivers.begin(),
1779 receivers.end());
1780 }
1781 return all_receivers;
1782}
1783
Steve Anton9158ef62017-11-27 13:01:52 -08001784std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1785PeerConnection::GetTransceivers() const {
Karl Wiberg5966c502019-02-21 23:55:09 +01001786 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonfc853712018-03-01 13:48:58 -08001787 RTC_CHECK(IsUnifiedPlan())
1788 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001789 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001790 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001791 all_transceivers.push_back(transceiver);
1792 }
1793 return all_transceivers;
1794}
1795
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001797 MediaStreamTrackInterface* track,
1798 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001799 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001800 RTC_DCHECK_RUN_ON(signaling_thread());
nisse7ce109a2017-01-31 00:57:56 -08001801 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001802 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 return false;
1804 }
1805
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001806 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001807 // The StatsCollector is used to tell if a track is valid because it may
1808 // remember tracks that the PeerConnection previously removed.
1809 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001810 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1811 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001812 return false;
1813 }
Steve Antonad182762018-09-05 20:22:40 +00001814 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1815 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001816 return true;
1817}
1818
hbos74e1a4f2016-09-15 23:33:01 -07001819void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001820 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001821 RTC_DCHECK_RUN_ON(signaling_thread());
hbos74e1a4f2016-09-15 23:33:01 -07001822 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001823 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001824 stats_collector_->GetStatsReport(callback);
1825}
1826
Henrik Boström1df1bf82018-03-20 13:24:20 +01001827void PeerConnection::GetStats(
1828 rtc::scoped_refptr<RtpSenderInterface> selector,
1829 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1830 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001831 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001832 RTC_DCHECK(callback);
1833 RTC_DCHECK(stats_collector_);
1834 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1835 if (selector) {
1836 for (const auto& proxy_transceiver : transceivers_) {
1837 for (const auto& proxy_sender :
1838 proxy_transceiver->internal()->senders()) {
1839 if (proxy_sender == selector) {
1840 internal_sender = proxy_sender->internal();
1841 break;
1842 }
1843 }
1844 if (internal_sender)
1845 break;
1846 }
1847 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001848 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001849 // belong to the PeerConnection (in Plan B, senders can be removed from the
1850 // PeerConnection). This means that "all the stats objects representing the
1851 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1852 // produces an empty stats report.
1853 stats_collector_->GetStatsReport(internal_sender, callback);
1854}
1855
1856void PeerConnection::GetStats(
1857 rtc::scoped_refptr<RtpReceiverInterface> selector,
1858 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1859 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
Karl Wiberg6cab5c82019-03-26 09:57:01 +01001860 RTC_DCHECK_RUN_ON(signaling_thread());
Henrik Boström1df1bf82018-03-20 13:24:20 +01001861 RTC_DCHECK(callback);
1862 RTC_DCHECK(stats_collector_);
1863 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1864 if (selector) {
1865 for (const auto& proxy_transceiver : transceivers_) {
1866 for (const auto& proxy_receiver :
1867 proxy_transceiver->internal()->receivers()) {
1868 if (proxy_receiver == selector) {
1869 internal_receiver = proxy_receiver->internal();
1870 break;
1871 }
1872 }
1873 if (internal_receiver)
1874 break;
1875 }
1876 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001877 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001878 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1879 // the PeerConnection). This means that "all the stats objects representing
1880 // the selector" is an empty set. Invoking GetStatsReport() with a null
1881 // selector produces an empty stats report.
1882 stats_collector_->GetStatsReport(internal_receiver, callback);
1883}
1884
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001885PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001886 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887 return signaling_state_;
1888}
1889
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001890PeerConnectionInterface::IceConnectionState
1891PeerConnection::ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001892 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 return ice_connection_state_;
1894}
1895
Alex Loiko9289eda2018-11-23 16:18:59 +00001896PeerConnectionInterface::IceConnectionState
1897PeerConnection::standardized_ice_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001898 RTC_DCHECK_RUN_ON(signaling_thread());
Alex Loiko9289eda2018-11-23 16:18:59 +00001899 return standardized_ice_connection_state_;
1900}
1901
Jonas Olsson635474e2018-10-18 15:58:17 +02001902PeerConnectionInterface::PeerConnectionState
1903PeerConnection::peer_connection_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001904 RTC_DCHECK_RUN_ON(signaling_thread());
Jonas Olsson635474e2018-10-18 15:58:17 +02001905 return connection_state_;
1906}
1907
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908PeerConnectionInterface::IceGatheringState
1909PeerConnection::ice_gathering_state() {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01001910 RTC_DCHECK_RUN_ON(signaling_thread());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911 return ice_gathering_state_;
1912}
1913
Yves Gerey665174f2018-06-19 15:03:05 +02001914rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915 const std::string& label,
1916 const DataChannelInit* config) {
Karl Wiberg106d92d2019-02-14 10:17:47 +01001917 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001918 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001919
deadbeefab9b2d12015-10-14 11:33:11 -07001920 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001921
kwibergd1fe2812016-04-27 06:47:29 -07001922 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001923 if (config) {
1924 internal_config.reset(new InternalDataChannelInit(*config));
1925 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001926 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001927 InternalCreateDataChannel(label, internal_config.get()));
1928 if (!channel.get()) {
1929 return nullptr;
1930 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001932 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1933 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001934 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001935 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001936 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001937 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001938 return DataChannelProxy::Create(signaling_thread(), channel.get());
1939}
1940
1941void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001942 const RTCOfferAnswerOptions& options) {
Karl Wiberg5966c502019-02-21 23:55:09 +01001943 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01001944 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001945
nisse7ce109a2017-01-31 00:57:56 -08001946 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001947 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001948 return;
1949 }
deadbeefab9b2d12015-10-14 11:33:11 -07001950
Steve Anton8d3444d2017-10-20 15:30:51 -07001951 if (IsClosed()) {
1952 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001953 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001954 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001955 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001956 return;
1957 }
1958
zhihuang1c378ed2017-08-17 14:10:50 -07001959 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001960 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001961 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001962 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001963 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001964 return;
1965 }
1966
Steve Anton22da89f2018-01-25 13:58:07 -08001967 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1968 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1969 if (IsUnifiedPlan()) {
1970 RTCError error = HandleLegacyOfferOptions(options);
1971 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001972 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001973 return;
1974 }
1975 }
1976
zhihuang1c378ed2017-08-17 14:10:50 -07001977 cricket::MediaSessionOptions session_options;
1978 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001979 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980}
1981
Steve Anton22da89f2018-01-25 13:58:07 -08001982RTCError PeerConnection::HandleLegacyOfferOptions(
1983 const RTCOfferAnswerOptions& options) {
1984 RTC_DCHECK(IsUnifiedPlan());
1985
1986 if (options.offer_to_receive_audio == 0) {
1987 RemoveRecvDirectionFromReceivingTransceiversOfType(
1988 cricket::MEDIA_TYPE_AUDIO);
1989 } else if (options.offer_to_receive_audio == 1) {
1990 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1991 } else if (options.offer_to_receive_audio > 1) {
1992 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1993 "offer_to_receive_audio > 1 is not supported.");
1994 }
1995
1996 if (options.offer_to_receive_video == 0) {
1997 RemoveRecvDirectionFromReceivingTransceiversOfType(
1998 cricket::MEDIA_TYPE_VIDEO);
1999 } else if (options.offer_to_receive_video == 1) {
2000 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
2001 } else if (options.offer_to_receive_video > 1) {
2002 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
2003 "offer_to_receive_video > 1 is not supported.");
2004 }
2005
2006 return RTCError::OK();
2007}
2008
2009void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
2010 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002011 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07002012 RtpTransceiverDirection new_direction =
2013 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
2014 if (new_direction != transceiver->direction()) {
2015 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
2016 << " transceiver (MID="
2017 << transceiver->mid().value_or("<not set>") << ") from "
2018 << RtpTransceiverDirectionToString(
2019 transceiver->direction())
2020 << " to "
2021 << RtpTransceiverDirectionToString(new_direction)
2022 << " since CreateOffer specified offer_to_receive=0";
2023 transceiver->internal()->set_direction(new_direction);
2024 }
Steve Anton22da89f2018-01-25 13:58:07 -08002025 }
2026}
2027
2028void PeerConnection::AddUpToOneReceivingTransceiverOfType(
2029 cricket::MediaType media_type) {
Karl Wiberg744310f2019-02-14 10:18:56 +01002030 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton22da89f2018-01-25 13:58:07 -08002031 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002032 RTC_LOG(LS_INFO)
2033 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
2034 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08002035 RtpTransceiverInit init;
2036 init.direction = RtpTransceiverDirection::kRecvOnly;
2037 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
2038 }
2039}
2040
2041std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2042PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
2043 std::vector<
2044 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2045 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002046 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002047 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08002048 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
2049 receiving_transceivers.push_back(transceiver);
2050 }
2051 }
2052 return receiving_transceivers;
2053}
2054
htaa2a49d92016-03-04 02:51:39 -08002055void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
2056 const RTCOfferAnswerOptions& options) {
Karl Wiberg8d2e2282019-02-17 13:00:07 +01002057 RTC_DCHECK_RUN_ON(signaling_thread());
htaa2a49d92016-03-04 02:51:39 -08002058 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08002059 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002060 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08002061 return;
2062 }
2063
Steve Antondffead82018-02-06 10:31:29 -08002064 if (!(signaling_state_ == kHaveRemoteOffer ||
2065 signaling_state_ == kHaveLocalPrAnswer)) {
2066 std::string error =
2067 "PeerConnection cannot create an answer in a state other than "
2068 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01002069 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002070 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02002071 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002072 return;
2073 }
2074
Steve Antondffead82018-02-06 10:31:29 -08002075 // The remote description should be set if we're in the right state.
2076 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07002077
Steve Anton22da89f2018-01-25 13:58:07 -08002078 if (IsUnifiedPlan()) {
2079 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2080 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
2081 "supported with Unified Plan semantics. Use the "
2082 "RtpTransceiver API instead.";
2083 }
2084 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2085 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
2086 "supported with Unified Plan semantics. Use the "
2087 "RtpTransceiver API instead.";
2088 }
2089 }
2090
htaa2a49d92016-03-04 02:51:39 -08002091 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07002092 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002093
Steve Antond25da372017-11-06 14:50:29 -08002094 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002095}
2096
2097void PeerConnection::SetLocalDescription(
2098 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002099 SessionDescriptionInterface* desc_ptr) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002100 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002101 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002102
Steve Anton80dd7b52018-02-16 17:08:42 -08002103 // The SetLocalDescription contract is that we take ownership of the session
2104 // description regardless of the outcome, so wrap it in a unique_ptr right
2105 // away. Ideally, SetLocalDescription's signature will be changed to take the
2106 // description as a unique_ptr argument to formalize this agreement.
2107 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2108
nisse7ce109a2017-01-31 00:57:56 -08002109 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002110 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002111 return;
2112 }
Steve Anton8a006912017-12-04 15:25:56 -08002113
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002115 PostSetSessionDescriptionFailure(
2116 observer,
2117 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002118 return;
2119 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002120
Steve Anton80dd7b52018-02-16 17:08:42 -08002121 // If a session error has occurred the PeerConnection is in a possibly
2122 // inconsistent state so fail right away.
2123 if (session_error() != SessionError::kNone) {
2124 std::string error_message = GetSessionErrorMsg();
2125 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002126 PostSetSessionDescriptionFailure(
2127 observer,
2128 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002129 return;
2130 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002131
Steve Anton80dd7b52018-02-16 17:08:42 -08002132 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2133 if (!error.ok()) {
2134 std::string error_message = GetSetDescriptionErrorMessage(
2135 cricket::CS_LOCAL, desc->GetType(), error);
2136 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002137 PostSetSessionDescriptionFailure(
2138 observer,
2139 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002140 return;
2141 }
2142
2143 // Grab the description type before moving ownership to ApplyLocalDescription,
2144 // which may destroy it before returning.
2145 const SdpType type = desc->GetType();
2146
2147 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002148 // |desc| may be destroyed at this point.
2149
2150 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002151 // If ApplyLocalDescription fails, the PeerConnection could be in an
2152 // inconsistent state, so act conservatively here and set the session error
2153 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2154 SetSessionError(SessionError::kContent, error.message());
2155 std::string error_message =
2156 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2157 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002158 PostSetSessionDescriptionFailure(
2159 observer,
2160 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002161 return;
2162 }
Steve Anton8a006912017-12-04 15:25:56 -08002163 RTC_DCHECK(local_description());
2164
2165 PostSetSessionDescriptionSuccess(observer);
2166
Steve Antonad182762018-09-05 20:22:40 +00002167 // MaybeStartGathering needs to be called after posting
2168 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2169 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002170 transport_controller_->MaybeStartGathering();
2171
Steve Antona3a92c22017-12-07 10:27:41 -08002172 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002173 // TODO(deadbeef): We already had to hop to the network thread for
2174 // MaybeStartGathering...
2175 network_thread()->Invoke<void>(
2176 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2177 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002178 // Make UMA notes about what was agreed to.
2179 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002180 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002181 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002182}
2183
2184RTCError PeerConnection::ApplyLocalDescription(
2185 std::unique_ptr<SessionDescriptionInterface> desc) {
2186 RTC_DCHECK_RUN_ON(signaling_thread());
2187 RTC_DCHECK(desc);
2188
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189 // Update stats here so that we have the most recent stats for tracks and
2190 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002191 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002192
Steve Antondcc3c022017-12-22 16:02:54 -08002193 // Take a reference to the old local description since it's used below to
2194 // compare against the new local description. When setting the new local
2195 // description, grab ownership of the replaced session description in case it
2196 // is the same as |old_local_description|, to keep it alive for the duration
2197 // of the method.
2198 const SessionDescriptionInterface* old_local_description =
2199 local_description();
2200 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002201 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002202 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002203 replaced_local_description = pending_local_description_
2204 ? std::move(pending_local_description_)
2205 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002206 current_local_description_ = std::move(desc);
2207 pending_local_description_ = nullptr;
2208 current_remote_description_ = std::move(pending_remote_description_);
2209 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002210 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002211 pending_local_description_ = std::move(desc);
2212 }
2213 // The session description to apply now must be accessed by
2214 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002215 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002216
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002217 // Report statistics about any use of simulcast.
2218 ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
2219 *local_description()->description());
2220
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002221 if (!is_caller_) {
2222 if (remote_description()) {
2223 // Remote description was applied first, so this PC is the callee.
2224 is_caller_ = false;
2225 } else {
2226 // Local description is applied first, so this PC is the caller.
2227 is_caller_ = true;
2228 }
2229 }
2230
Zhi Huange830e682018-03-30 10:48:35 -07002231 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2232 if (!error.ok()) {
2233 return error;
2234 }
2235
Steve Antondcc3c022017-12-22 16:02:54 -08002236 if (IsUnifiedPlan()) {
2237 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002238 cricket::CS_LOCAL, *local_description(), old_local_description,
2239 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002240 if (!error.ok()) {
2241 return error;
2242 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002243 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2244 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002245 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002246 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2247 // Note that code paths that don't set MID won't be able to use
2248 // information about DTLS transports.
2249 if (transceiver->mid()) {
2250 auto dtls_transport =
2251 LookupDtlsTransportByMidInternal(*transceiver->mid());
2252 transceiver->internal()->sender_internal()->set_transport(
2253 dtls_transport);
2254 transceiver->internal()->receiver_internal()->set_transport(
2255 dtls_transport);
2256 }
2257
Steve Antondcc3c022017-12-22 16:02:54 -08002258 const ContentInfo* content =
2259 FindMediaSectionForTransceiver(transceiver, local_description());
2260 if (!content) {
2261 continue;
2262 }
2263 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002264 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2265 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002266 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002267 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2268 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2269 // "recvonly", process the removal of a remote track for the media
2270 // description, given transceiver, removeList, and muteTracks.
2271 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2272 (transceiver->internal()->fired_direction() &&
2273 RtpTransceiverDirectionHasRecv(
2274 *transceiver->internal()->fired_direction()))) {
2275 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2276 &removed_streams);
2277 }
2278 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2279 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002280 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002281 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002282 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002283 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002284 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002285 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002286 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002287 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002288 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002289 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002290 }
2291 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002292 // Media channels will be created only when offer is set. These may use new
2293 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002294 if (type == SdpType::kOffer) {
2295 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2296 // description is applied. Restore back to old description.
2297 RTCError error = CreateChannels(*local_description()->description());
2298 if (!error.ok()) {
2299 return error;
2300 }
2301 }
Steve Antondcc3c022017-12-22 16:02:54 -08002302 // Remove unused channels if MediaContentDescription is rejected.
2303 RemoveUnusedChannels(local_description()->description());
2304 }
Steve Anton8a006912017-12-04 15:25:56 -08002305
Zhi Huange830e682018-03-30 10:48:35 -07002306 error = UpdateSessionState(type, cricket::CS_LOCAL,
2307 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002308 if (!error.ok()) {
2309 return error;
2310 }
Steve Antondcc3c022017-12-22 16:02:54 -08002311
Steve Anton8a006912017-12-04 15:25:56 -08002312 if (remote_description()) {
2313 // Now that we have a local description, we can push down remote candidates.
2314 UseCandidatesInSessionDescription(remote_description());
2315 }
2316
2317 pending_ice_restarts_.clear();
2318 if (session_error() != SessionError::kNone) {
2319 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2320 }
2321
deadbeefab9b2d12015-10-14 11:33:11 -07002322 // If setting the description decided our SSL role, allocate any necessary
2323 // SCTP sids.
2324 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002325 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002326 AllocateSctpSids(role);
2327 }
2328
Steve Antond3679212018-01-17 17:41:02 -08002329 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002330 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002331 const ContentInfo* content =
2332 FindMediaSectionForTransceiver(transceiver, local_description());
2333 if (!content) {
2334 continue;
2335 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002336 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2337 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002338 // 0 is a special value meaning "this sender has no associated send
2339 // stream". Need to call this so the sender won't attempt to configure
2340 // a no longer existing stream and run into DCHECKs in the lower
2341 // layers.
2342 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002343 } else {
2344 // Get the StreamParams from the channel which could generate SSRCs.
2345 const std::vector<StreamParams>& streams = channel->local_streams();
2346 transceiver->internal()->sender_internal()->set_stream_ids(
2347 streams[0].stream_ids());
2348 transceiver->internal()->sender_internal()->SetSsrc(
2349 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002350 }
2351 }
2352 } else {
2353 // Plan B semantics.
2354
Steve Antondcc3c022017-12-22 16:02:54 -08002355 // Update state and SSRC of local MediaStreams and DataChannels based on the
2356 // local session description.
2357 const cricket::ContentInfo* audio_content =
2358 GetFirstAudioContent(local_description()->description());
2359 if (audio_content) {
2360 if (audio_content->rejected) {
2361 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2362 } else {
2363 const cricket::AudioContentDescription* audio_desc =
2364 audio_content->media_description()->as_audio();
2365 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2366 }
deadbeeffaac4972015-11-12 15:33:07 -08002367 }
deadbeefab9b2d12015-10-14 11:33:11 -07002368
Steve Antondcc3c022017-12-22 16:02:54 -08002369 const cricket::ContentInfo* video_content =
2370 GetFirstVideoContent(local_description()->description());
2371 if (video_content) {
2372 if (video_content->rejected) {
2373 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2374 } else {
2375 const cricket::VideoContentDescription* video_desc =
2376 video_content->media_description()->as_video();
2377 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2378 }
deadbeeffaac4972015-11-12 15:33:07 -08002379 }
deadbeefab9b2d12015-10-14 11:33:11 -07002380 }
2381
2382 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002383 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002384 if (data_content) {
2385 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002386 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002387 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002388 cricket::kMediaProtocolRtpPrefix)) {
2389 UpdateLocalRtpDataChannels(data_desc->streams());
2390 }
2391 }
2392
Steve Anton8a006912017-12-04 15:25:56 -08002393 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002394}
2395
Steve Anton06817cd2018-12-18 15:55:30 -08002396// The SDP parser used to populate these values by default for the 'content
2397// name' if an a=mid line was absent.
2398static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2399 switch (media_type) {
2400 case cricket::MEDIA_TYPE_AUDIO:
2401 return cricket::CN_AUDIO;
2402 case cricket::MEDIA_TYPE_VIDEO:
2403 return cricket::CN_VIDEO;
2404 case cricket::MEDIA_TYPE_DATA:
2405 return cricket::CN_DATA;
2406 }
2407 RTC_NOTREACHED();
2408 return "";
2409}
2410
2411void PeerConnection::FillInMissingRemoteMids(
Steve Antond7180cc2019-02-07 10:44:53 -08002412 cricket::SessionDescription* new_remote_description) {
2413 RTC_DCHECK(new_remote_description);
Steve Anton06817cd2018-12-18 15:55:30 -08002414 const cricket::ContentInfos& local_contents =
2415 (local_description() ? local_description()->description()->contents()
2416 : cricket::ContentInfos());
Steve Antond7180cc2019-02-07 10:44:53 -08002417 const cricket::ContentInfos& remote_contents =
2418 (remote_description() ? remote_description()->description()->contents()
2419 : cricket::ContentInfos());
2420 for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
2421 cricket::ContentInfo& content = new_remote_description->contents()[i];
Steve Anton06817cd2018-12-18 15:55:30 -08002422 if (!content.name.empty()) {
2423 continue;
2424 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002425 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002426 absl::string_view source_explanation;
2427 if (IsUnifiedPlan()) {
2428 if (i < local_contents.size()) {
2429 new_mid = local_contents[i].name;
2430 source_explanation = "from the matching local media section";
Steve Antond7180cc2019-02-07 10:44:53 -08002431 } else if (i < remote_contents.size()) {
2432 new_mid = remote_contents[i].name;
2433 source_explanation = "from the matching previous remote media section";
Steve Anton06817cd2018-12-18 15:55:30 -08002434 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002435 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002436 source_explanation = "generated just now";
2437 }
2438 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002439 new_mid = std::string(
2440 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002441 source_explanation = "to match pre-existing behavior";
2442 }
Steve Antond7180cc2019-02-07 10:44:53 -08002443 RTC_DCHECK(!new_mid.empty());
Amit Hilbuchae3df542019-01-07 12:13:08 -08002444 content.name = new_mid;
Steve Antond7180cc2019-02-07 10:44:53 -08002445 new_remote_description->transport_infos()[i].content_name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002446 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2447 << " is missing an a=mid line. Filling in the value '"
2448 << new_mid << "' " << source_explanation << ".";
2449 }
2450}
2451
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002452void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002453 SetSessionDescriptionObserver* observer,
2454 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002455 SetRemoteDescription(
2456 std::unique_ptr<SessionDescriptionInterface>(desc),
2457 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2458 new SetRemoteDescriptionObserverAdapter(this, observer)));
2459}
2460
2461void PeerConnection::SetRemoteDescription(
2462 std::unique_ptr<SessionDescriptionInterface> desc,
2463 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Karl Wiberg5966c502019-02-21 23:55:09 +01002464 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01002465 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002466
nisse7ce109a2017-01-31 00:57:56 -08002467 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002468 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002469 return;
2470 }
Steve Anton8a006912017-12-04 15:25:56 -08002471
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002472 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002473 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002474 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002475 return;
2476 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002477
Steve Anton80dd7b52018-02-16 17:08:42 -08002478 // If a session error has occurred the PeerConnection is in a possibly
2479 // inconsistent state so fail right away.
2480 if (session_error() != SessionError::kNone) {
2481 std::string error_message = GetSessionErrorMsg();
2482 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2483 observer->OnSetRemoteDescriptionComplete(
2484 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2485 return;
2486 }
Steve Anton71439a62018-02-15 11:53:06 -08002487
Steve Antonba42e992018-04-09 14:10:01 -07002488 if (desc->GetType() == SdpType::kOffer) {
2489 // Report to UMA the format of the received offer.
2490 ReportSdpFormatReceived(*desc);
2491 }
2492
Steve Anton06817cd2018-12-18 15:55:30 -08002493 // Handle remote descriptions missing a=mid lines for interop with legacy end
2494 // points.
2495 FillInMissingRemoteMids(desc->description());
2496
Steve Anton80dd7b52018-02-16 17:08:42 -08002497 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002498 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002499 std::string error_message = GetSetDescriptionErrorMessage(
2500 cricket::CS_REMOTE, desc->GetType(), error);
2501 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002502 observer->OnSetRemoteDescriptionComplete(
2503 RTCError(error.type(), std::move(error_message)));
2504 return;
2505 }
Steve Anton71439a62018-02-15 11:53:06 -08002506
Steve Anton80dd7b52018-02-16 17:08:42 -08002507 // Grab the description type before moving ownership to
2508 // ApplyRemoteDescription, which may destroy it before returning.
2509 const SdpType type = desc->GetType();
2510
2511 error = ApplyRemoteDescription(std::move(desc));
2512 // |desc| may be destroyed at this point.
2513
2514 if (!error.ok()) {
2515 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2516 // inconsistent state, so act conservatively here and set the session error
2517 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2518 SetSessionError(SessionError::kContent, error.message());
2519 std::string error_message =
2520 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2521 RTC_LOG(LS_ERROR) << error_message;
2522 observer->OnSetRemoteDescriptionComplete(
2523 RTCError(error.type(), std::move(error_message)));
2524 return;
2525 }
2526 RTC_DCHECK(remote_description());
2527
2528 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002529 // TODO(deadbeef): We already had to hop to the network thread for
2530 // MaybeStartGathering...
2531 network_thread()->Invoke<void>(
2532 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2533 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002534 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002535 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002536 }
2537
2538 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002539 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002540}
2541
2542RTCError PeerConnection::ApplyRemoteDescription(
2543 std::unique_ptr<SessionDescriptionInterface> desc) {
2544 RTC_DCHECK_RUN_ON(signaling_thread());
2545 RTC_DCHECK(desc);
2546
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002547 // Update stats here so that we have the most recent stats for tracks and
2548 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002549 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002550
Steve Antondcc3c022017-12-22 16:02:54 -08002551 // Take a reference to the old remote description since it's used below to
2552 // compare against the new remote description. When setting the new remote
2553 // description, grab ownership of the replaced session description in case it
2554 // is the same as |old_remote_description|, to keep it alive for the duration
2555 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002556 const SessionDescriptionInterface* old_remote_description =
2557 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002558 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002559 SdpType type = desc->GetType();
2560 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002561 replaced_remote_description = pending_remote_description_
2562 ? std::move(pending_remote_description_)
2563 : std::move(current_remote_description_);
2564 current_remote_description_ = std::move(desc);
2565 pending_remote_description_ = nullptr;
2566 current_local_description_ = std::move(pending_local_description_);
2567 } else {
2568 replaced_remote_description = std::move(pending_remote_description_);
2569 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002570 }
Steve Anton8a006912017-12-04 15:25:56 -08002571 // The session description to apply now must be accessed by
2572 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002573 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002574
Amit Hilbuche2a284d2019-03-05 12:36:31 -08002575 // Report statistics about any use of simulcast.
2576 ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
2577 *remote_description()->description());
2578
Zhi Huange830e682018-03-30 10:48:35 -07002579 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2580 if (!error.ok()) {
2581 return error;
2582 }
Steve Anton8a006912017-12-04 15:25:56 -08002583 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002584 if (IsUnifiedPlan()) {
2585 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002586 cricket::CS_REMOTE, *remote_description(), local_description(),
2587 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002588 if (!error.ok()) {
2589 return error;
2590 }
Steve Antondcc3c022017-12-22 16:02:54 -08002591 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002592 // Media channels will be created only when offer is set. These may use new
2593 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002594 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002595 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002596 // description is applied. Restore back to old description.
2597 RTCError error = CreateChannels(*remote_description()->description());
2598 if (!error.ok()) {
2599 return error;
2600 }
2601 }
Steve Antondcc3c022017-12-22 16:02:54 -08002602 // Remove unused channels if MediaContentDescription is rejected.
2603 RemoveUnusedChannels(remote_description()->description());
2604 }
Steve Anton8a006912017-12-04 15:25:56 -08002605
Zhi Huange830e682018-03-30 10:48:35 -07002606 // NOTE: Candidates allocation will be initiated only when
2607 // SetLocalDescription is called.
2608 error = UpdateSessionState(type, cricket::CS_REMOTE,
2609 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002610 if (!error.ok()) {
2611 return error;
2612 }
2613
2614 if (local_description() &&
2615 !UseCandidatesInSessionDescription(remote_description())) {
2616 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2617 }
2618
2619 if (old_remote_description) {
2620 for (const cricket::ContentInfo& content :
2621 old_remote_description->description()->contents()) {
2622 // Check if this new SessionDescription contains new ICE ufrag and
2623 // password that indicates the remote peer requests an ICE restart.
2624 // TODO(deadbeef): When we start storing both the current and pending
2625 // remote description, this should reset pending_ice_restarts and compare
2626 // against the current description.
2627 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2628 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002629 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002630 pending_ice_restarts_.insert(content.name);
2631 }
2632 } else {
2633 // We retain all received candidates only if ICE is not restarted.
2634 // When ICE is restarted, all previous candidates belong to an old
2635 // generation and should not be kept.
2636 // TODO(deadbeef): This goes against the W3C spec which says the remote
2637 // description should only contain candidates from the last set remote
2638 // description plus any candidates added since then. We should remove
2639 // this once we're sure it won't break anything.
2640 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2641 old_remote_description, content.name, mutable_remote_description());
2642 }
2643 }
2644 }
2645
2646 if (session_error() != SessionError::kNone) {
2647 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2648 }
2649
2650 // Set the the ICE connection state to connecting since the connection may
2651 // become writable with peer reflexive candidates before any remote candidate
2652 // is signaled.
2653 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2654 // is to have a new signal the indicates a change in checking state from the
2655 // transport and expose a new checking() member from transport that can be
2656 // read to determine the current checking state. The existing SignalConnecting
2657 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002658 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002659 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002660 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2661 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2662 }
2663
deadbeefab9b2d12015-10-14 11:33:11 -07002664 // If setting the description decided our SSL role, allocate any necessary
2665 // SCTP sids.
2666 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002667 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002668 AllocateSctpSids(role);
2669 }
2670
Steve Antondcc3c022017-12-22 16:02:54 -08002671 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002672 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002673 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002674 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002675 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002676 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002677 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002678 const ContentInfo* content =
2679 FindMediaSectionForTransceiver(transceiver, remote_description());
2680 if (!content) {
2681 continue;
2682 }
2683 const MediaContentDescription* media_desc = content->media_description();
2684 RtpTransceiverDirection local_direction =
2685 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002686 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2687 // RTCSessionDescription: Set the associated remote streams given
2688 // transceiver.[[Receiver]], msids, addList, and removeList".
2689 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2690 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2691 std::vector<std::string> stream_ids;
2692 if (!media_desc->streams().empty()) {
2693 // The remote description has signaled the stream IDs.
2694 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002695 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002696 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2697 << " (" << GetStreamIdsString(stream_ids) << ").";
2698 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2699 stream_ids, &added_streams,
2700 &removed_streams);
2701 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2702 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2703 // and transceiver's current direction is neither sendrecv nor recvonly,
2704 // process the addition of a remote track for the media description.
2705 if (!transceiver->fired_direction() ||
2706 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2707 RTC_LOG(LS_INFO)
2708 << "Processing the addition of a remote track for MID="
2709 << content->name << ".";
2710 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002711 }
Steve Antondcc3c022017-12-22 16:02:54 -08002712 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002713 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002714 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2715 // removal of a remote track for the media description, given transceiver,
2716 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002717 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002718 (transceiver->fired_direction() &&
2719 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2720 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2721 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002722 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002723 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002724 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002725 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002726 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002727 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002728 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002729 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002730 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002731 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2732 if (transceiver->mid()) {
2733 auto dtls_transport =
2734 LookupDtlsTransportByMidInternal(*transceiver->mid());
2735 transceiver->internal()->sender_internal()->set_transport(
2736 dtls_transport);
2737 transceiver->internal()->receiver_internal()->set_transport(
2738 dtls_transport);
2739 }
Steve Antondcc3c022017-12-22 16:02:54 -08002740 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002741 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002742 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002743 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002744 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2745 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002746 transceiver->Stop();
2747 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002748 if (!content->rejected &&
2749 RtpTransceiverDirectionHasRecv(local_direction)) {
2750 // Set ssrc to 0 in the case of an unsignalled ssrc.
2751 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002752 if (!media_desc->streams().empty() &&
2753 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002754 ssrc = media_desc->streams()[0].first_ssrc();
2755 }
2756 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002757 }
Steve Antondcc3c022017-12-22 16:02:54 -08002758 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002759 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002760 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002761 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002762 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002763 observer->OnTrack(transceiver);
2764 observer->OnAddTrack(transceiver->receiver(),
2765 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002766 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002767 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002768 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002769 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002770 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002771 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002772 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002773 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002774 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002775 }
Steve Antondcc3c022017-12-22 16:02:54 -08002776 }
2777
Henrik Boströmfdb92012017-11-09 19:55:44 +01002778 const cricket::ContentInfo* audio_content =
2779 GetFirstAudioContent(remote_description()->description());
2780 const cricket::ContentInfo* video_content =
2781 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002782 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002783 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002784 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002785 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002786 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002787 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002788
2789 // Check if the descriptions include streams, just in case the peer supports
2790 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002791 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002792 (audio_desc && !audio_desc->streams().empty()) ||
2793 (video_desc && !video_desc->streams().empty())) {
2794 remote_peer_supports_msid_ = true;
2795 }
deadbeefab9b2d12015-10-14 11:33:11 -07002796
2797 // We wait to signal new streams until we finish processing the description,
2798 // since only at that point will new streams have all their tracks.
2799 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2800
Steve Antondcc3c022017-12-22 16:02:54 -08002801 if (!IsUnifiedPlan()) {
2802 // TODO(steveanton): When removing RTP senders/receivers in response to a
2803 // rejected media section, there is some cleanup logic that expects the
2804 // voice/ video channel to still be set. But in this method the voice/video
2805 // channel would have been destroyed by the SetRemoteDescription caller
2806 // above so the cleanup that relies on them fails to run. The RemoveSenders
2807 // calls should be moved to right before the DestroyChannel calls to fix
2808 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002809
Steve Antondcc3c022017-12-22 16:02:54 -08002810 // Find all audio rtp streams and create corresponding remote AudioTracks
2811 // and MediaStreams.
2812 if (audio_content) {
2813 if (audio_content->rejected) {
2814 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2815 } else {
2816 bool default_audio_track_needed =
2817 !remote_peer_supports_msid_ &&
2818 RtpTransceiverDirectionHasSend(audio_desc->direction());
2819 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2820 default_audio_track_needed, audio_desc->type(),
2821 new_streams);
2822 }
deadbeeffaac4972015-11-12 15:33:07 -08002823 }
deadbeefab9b2d12015-10-14 11:33:11 -07002824
Steve Antondcc3c022017-12-22 16:02:54 -08002825 // Find all video rtp streams and create corresponding remote VideoTracks
2826 // and MediaStreams.
2827 if (video_content) {
2828 if (video_content->rejected) {
2829 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2830 } else {
2831 bool default_video_track_needed =
2832 !remote_peer_supports_msid_ &&
2833 RtpTransceiverDirectionHasSend(video_desc->direction());
2834 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2835 default_video_track_needed, video_desc->type(),
2836 new_streams);
2837 }
deadbeeffaac4972015-11-12 15:33:07 -08002838 }
deadbeefab9b2d12015-10-14 11:33:11 -07002839
Steve Antondcc3c022017-12-22 16:02:54 -08002840 // Update the DataChannels with the information from the remote peer.
2841 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002842 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002843 cricket::kMediaProtocolRtpPrefix)) {
2844 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2845 }
deadbeefab9b2d12015-10-14 11:33:11 -07002846 }
deadbeefab9b2d12015-10-14 11:33:11 -07002847
Steve Antondcc3c022017-12-22 16:02:54 -08002848 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002849 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002850 for (size_t i = 0; i < new_streams->count(); ++i) {
2851 MediaStreamInterface* new_stream = new_streams->at(i);
2852 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002853 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002854 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2855 }
deadbeefab9b2d12015-10-14 11:33:11 -07002856
Steve Antondcc3c022017-12-22 16:02:54 -08002857 UpdateEndedRemoteMediaStreams();
2858 }
deadbeefab9b2d12015-10-14 11:33:11 -07002859
Steve Anton8a006912017-12-04 15:25:56 -08002860 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002861}
2862
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002863void PeerConnection::SetAssociatedRemoteStreams(
2864 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2865 const std::vector<std::string>& stream_ids,
2866 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2867 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2868 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2869 for (const std::string& stream_id : stream_ids) {
2870 rtc::scoped_refptr<MediaStreamInterface> stream =
2871 remote_streams_->find(stream_id);
2872 if (!stream) {
2873 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2874 MediaStream::Create(stream_id));
2875 remote_streams_->AddStream(stream);
2876 added_streams->push_back(stream);
2877 }
2878 media_streams.push_back(stream);
2879 }
2880 // Special case: "a=msid" missing, use random stream ID.
2881 if (media_streams.empty() &&
2882 !(remote_description()->description()->msid_signaling() &
2883 cricket::kMsidSignalingMediaSection)) {
2884 if (!missing_msid_default_stream_) {
2885 missing_msid_default_stream_ = MediaStreamProxy::Create(
2886 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2887 added_streams->push_back(missing_msid_default_stream_);
2888 }
2889 media_streams.push_back(missing_msid_default_stream_);
2890 }
2891 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2892 receiver->streams();
2893 // SetStreams() will add/remove the receiver's track to/from the streams. This
2894 // differs from the spec - the spec uses an "addList" and "removeList" to
2895 // update the stream-track relationships in a later step. We do this earlier,
2896 // changing the order of things, but the end-result is the same.
2897 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2898 // instead. https://crbug.com/webrtc/9480
2899 receiver->SetStreams(media_streams);
2900 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2901}
2902
Steve Anton0f5400a2018-07-17 14:25:36 -07002903void PeerConnection::ProcessRemovalOfRemoteTrack(
2904 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2905 transceiver,
2906 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2907 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2908 RTC_DCHECK(transceiver->mid());
2909 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2910 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002911 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002912 transceiver->internal()->receiver_internal()->streams();
2913 // This will remove the remote track from the streams.
2914 transceiver->internal()->receiver_internal()->set_stream_ids({});
2915 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002916 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2917}
2918
2919void PeerConnection::RemoveRemoteStreamsIfEmpty(
2920 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2921 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2922 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2923 // streams, see if the stream was removed by checking if this was the last
2924 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002925 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002926 if (remote_stream->GetAudioTracks().empty() &&
2927 remote_stream->GetVideoTracks().empty()) {
2928 remote_streams_->RemoveStream(remote_stream);
2929 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002930 }
2931 }
2932}
2933
Steve Antondcc3c022017-12-22 16:02:54 -08002934RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2935 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002936 const SessionDescriptionInterface& new_session,
2937 const SessionDescriptionInterface* old_local_description,
2938 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002939 RTC_DCHECK(IsUnifiedPlan());
2940
Steve Anton7464fca2018-01-19 11:10:37 -08002941 const cricket::ContentGroup* bundle_group = nullptr;
2942 if (new_session.GetType() == SdpType::kOffer) {
2943 auto bundle_group_or_error =
2944 GetEarlyBundleGroup(*new_session.description());
2945 if (!bundle_group_or_error.ok()) {
2946 return bundle_group_or_error.MoveError();
2947 }
2948 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002949 }
Steve Antondcc3c022017-12-22 16:02:54 -08002950
Steve Antondcc3c022017-12-22 16:02:54 -08002951 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002952 for (size_t i = 0; i < new_contents.size(); ++i) {
2953 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002954 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002955 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002956 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2957 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002958 const cricket::ContentInfo* old_local_content = nullptr;
2959 if (old_local_description &&
2960 i < old_local_description->description()->contents().size()) {
2961 old_local_content =
2962 &old_local_description->description()->contents()[i];
2963 }
2964 const cricket::ContentInfo* old_remote_content = nullptr;
2965 if (old_remote_description &&
2966 i < old_remote_description->description()->contents().size()) {
2967 old_remote_content =
2968 &old_remote_description->description()->contents()[i];
2969 }
Steve Antondcc3c022017-12-22 16:02:54 -08002970 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002971 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2972 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002973 if (!transceiver_or_error.ok()) {
2974 return transceiver_or_error.MoveError();
2975 }
2976 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002977 RTCError error =
2978 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2979 if (!error.ok()) {
2980 return error;
2981 }
2982 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002983 if (GetDataMid() && new_content.name != *GetDataMid()) {
2984 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002985 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2986 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002987 continue;
2988 }
2989 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2990 if (!error.ok()) {
2991 return error;
2992 }
Steve Antondcc3c022017-12-22 16:02:54 -08002993 } else {
2994 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2995 "Unknown section type.");
2996 }
2997 }
2998
2999 return RTCError::OK();
3000}
3001
3002RTCError PeerConnection::UpdateTransceiverChannel(
3003 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3004 transceiver,
3005 const cricket::ContentInfo& content,
3006 const cricket::ContentGroup* bundle_group) {
3007 RTC_DCHECK(IsUnifiedPlan());
3008 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003009 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08003010 if (content.rejected) {
3011 if (channel) {
3012 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003013 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08003014 }
3015 } else {
3016 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08003017 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07003018 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003019 } else {
Steve Anton69470252018-02-09 11:43:08 -08003020 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07003021 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08003022 }
3023 if (!channel) {
3024 LOG_AND_RETURN_ERROR(
3025 RTCErrorType::INTERNAL_ERROR,
3026 "Failed to create channel for mid=" + content.name);
3027 }
3028 transceiver->internal()->SetChannel(channel);
3029 }
3030 }
3031 return RTCError::OK();
3032}
3033
Steve Antonfa2260d2017-12-28 16:38:23 -08003034RTCError PeerConnection::UpdateDataChannel(
3035 cricket::ContentSource source,
3036 const cricket::ContentInfo& content,
3037 const cricket::ContentGroup* bundle_group) {
3038 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08003039 // If data channels are disabled, ignore this media section. CreateAnswer
3040 // will take care of rejecting it.
3041 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08003042 }
3043 if (content.rejected) {
3044 DestroyDataChannel();
3045 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003046 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07003047 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003048 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3049 "Failed to create data channel.");
3050 }
3051 }
3052 if (source == cricket::CS_REMOTE) {
3053 const MediaContentDescription* data_desc = content.media_description();
3054 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
3055 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
3056 }
3057 }
3058 }
3059 return RTCError::OK();
3060}
3061
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003062// This method will extract any send encodings that were sent by the remote
3063// connection. This is currently only relevant for Simulcast scenario (where
3064// the number of layers may be communicated by the server).
3065static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
3066 const MediaContentDescription& desc) {
3067 if (!desc.HasSimulcast()) {
3068 return {};
3069 }
3070 std::vector<RtpEncodingParameters> result;
3071 const SimulcastDescription& simulcast = desc.simulcast_description();
3072
3073 // This is a remote description, the parameters we are after should appear
3074 // as receive streams.
3075 for (const auto& alternatives : simulcast.receive_layers()) {
3076 RTC_DCHECK(!alternatives.empty());
3077 // There is currently no way to specify or choose from alternatives.
3078 // We will always use the first alternative, which is the most preferred.
3079 const SimulcastLayer& layer = alternatives[0];
3080 RtpEncodingParameters parameters;
3081 parameters.rid = layer.rid;
3082 parameters.active = !layer.is_paused;
3083 result.push_back(parameters);
3084 }
3085
3086 return result;
3087}
3088
3089static RTCError UpdateSimulcastLayerStatusInSender(
3090 const std::vector<SimulcastLayer>& layers,
Amit Hilbuch2297d332019-02-19 12:49:22 -08003091 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003092 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003093 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003094 std::vector<std::string> disabled_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003095
3096 // The simulcast envelope cannot be changed, only the status of the streams.
3097 // So we will iterate over the send encodings rather than the layers.
3098 for (RtpEncodingParameters& encoding : parameters.encodings) {
3099 auto iter = std::find_if(layers.begin(), layers.end(),
3100 [&encoding](const SimulcastLayer& layer) {
3101 return layer.rid == encoding.rid;
3102 });
3103 // A layer that cannot be found may have been removed by the remote party.
Amit Hilbuch2297d332019-02-19 12:49:22 -08003104 if (iter == layers.end()) {
3105 disabled_layers.push_back(encoding.rid);
3106 continue;
3107 }
3108
3109 encoding.active = !iter->is_paused;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003110 }
3111
Amit Hilbuch619b2942019-02-26 15:55:19 -08003112 RTCError result = sender->SetParametersInternal(parameters);
Amit Hilbuch2297d332019-02-19 12:49:22 -08003113 if (result.ok()) {
3114 result = sender->DisableEncodingLayers(disabled_layers);
3115 }
3116
3117 return result;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003118}
3119
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003120static bool SimulcastIsRejected(
3121 const ContentInfo* local_content,
3122 const MediaContentDescription& answer_media_desc) {
3123 bool simulcast_offered = local_content &&
3124 local_content->media_description() &&
3125 local_content->media_description()->HasSimulcast();
3126 bool simulcast_answered = answer_media_desc.HasSimulcast();
3127 bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
3128 answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
3129 return simulcast_offered && (!simulcast_answered || !rids_supported);
3130}
3131
Amit Hilbuch2297d332019-02-19 12:49:22 -08003132static RTCError DisableSimulcastInSender(
3133 rtc::scoped_refptr<RtpSenderInternal> sender) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003134 RTC_DCHECK(sender);
Amit Hilbuch619b2942019-02-26 15:55:19 -08003135 RtpParameters parameters = sender->GetParametersInternal();
Amit Hilbuch2297d332019-02-19 12:49:22 -08003136 if (parameters.encodings.size() <= 1) {
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003137 return RTCError::OK();
3138 }
3139
Amit Hilbuch2297d332019-02-19 12:49:22 -08003140 std::vector<std::string> disabled_layers;
3141 std::transform(
3142 parameters.encodings.begin() + 1, parameters.encodings.end(),
3143 std::back_inserter(disabled_layers),
3144 [](const RtpEncodingParameters& encoding) { return encoding.rid; });
3145 return sender->DisableEncodingLayers(disabled_layers);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003146}
3147
Steve Antondcc3c022017-12-22 16:02:54 -08003148RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3149PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003150 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003151 size_t mline_index,
3152 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003153 const ContentInfo* old_local_content,
3154 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003155 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003156 // If this is an offer then the m= section might be recycled. If the m=
3157 // section is being recycled (defined as: rejected in the current local or
3158 // remote description and not rejected in new description), dissociate the
3159 // currently associated RtpTransceiver by setting its mid property to null,
3160 // and discard the mapping between the transceiver and its m= section index.
3161 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3162 old_remote_content)) {
3163 // We want to dissociate the transceiver that has the rejected mid.
3164 const std::string& old_mid =
3165 (old_local_content && old_local_content->rejected)
3166 ? old_local_content->name
3167 : old_remote_content->name;
3168 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003169 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003170 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3171 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003172 old_transceiver->internal()->set_mid(absl::nullopt);
3173 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003174 }
3175 }
3176 const MediaContentDescription* media_desc = content.media_description();
3177 auto transceiver = GetAssociatedTransceiver(content.name);
3178 if (source == cricket::CS_LOCAL) {
3179 // Find the RtpTransceiver that corresponds to this m= section, using the
3180 // mapping between transceivers and m= section indices established when
3181 // creating the offer.
3182 if (!transceiver) {
3183 transceiver = GetTransceiverByMLineIndex(mline_index);
3184 }
3185 if (!transceiver) {
3186 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3187 "Unknown transceiver");
3188 }
3189 } else {
3190 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3191 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3192 // of the same type...
Amit Hilbuchaa584152019-02-06 17:09:52 -08003193 // When simulcast is requested, a transceiver cannot be associated because
3194 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003195 if (!transceiver &&
Amit Hilbuchaa584152019-02-06 17:09:52 -08003196 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3197 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003198 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3199 }
3200 // If no RtpTransceiver was found in the previous step, create one with a
3201 // recvonly direction.
3202 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003203 RTC_LOG(LS_INFO) << "Adding "
3204 << cricket::MediaTypeToString(media_desc->type())
3205 << " transceiver for MID=" << content.name
3206 << " at i=" << mline_index
3207 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003208 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003209 std::vector<RtpEncodingParameters> send_encodings =
3210 GetSendEncodingsFromRemoteDescription(*media_desc);
3211 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3212 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003213 std::string receiver_id;
3214 if (!media_desc->streams().empty()) {
3215 receiver_id = media_desc->streams()[0].id;
3216 } else {
3217 receiver_id = rtc::CreateRandomUuid();
3218 }
3219 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003220 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003221 transceiver->internal()->set_direction(
3222 RtpTransceiverDirection::kRecvOnly);
3223 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003224
3225 // Check if the offer indicated simulcast but the answer rejected it.
3226 // This can happen when simulcast is not supported on the remote party.
Amit Hilbuchaabd0362019-03-01 13:14:46 -08003227 if (SimulcastIsRejected(old_local_content, *media_desc)) {
Amit Hilbuche2a284d2019-03-05 12:36:31 -08003228 RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003229 RTCError error =
Amit Hilbuch2297d332019-02-19 12:49:22 -08003230 DisableSimulcastInSender(transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003231 if (!error.ok()) {
3232 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3233 return std::move(error);
3234 }
3235 }
Steve Antondcc3c022017-12-22 16:02:54 -08003236 }
3237 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003238 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003239 LOG_AND_RETURN_ERROR(
3240 RTCErrorType::INVALID_PARAMETER,
3241 "Transceiver type does not match media description type.");
3242 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003243 if (media_desc->HasSimulcast()) {
3244 std::vector<SimulcastLayer> layers =
3245 source == cricket::CS_LOCAL
3246 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3247 : media_desc->simulcast_description()
3248 .receive_layers()
3249 .GetAllLayers();
3250 RTCError error = UpdateSimulcastLayerStatusInSender(
Amit Hilbuch2297d332019-02-19 12:49:22 -08003251 layers, transceiver->internal()->sender_internal());
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003252 if (!error.ok()) {
3253 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3254 return std::move(error);
3255 }
3256 }
Steve Antondcc3c022017-12-22 16:02:54 -08003257 // Associate the found or created RtpTransceiver with the m= section by
3258 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3259 // section, and establish a mapping between the transceiver and the index of
3260 // the m= section.
3261 transceiver->internal()->set_mid(content.name);
3262 transceiver->internal()->set_mline_index(mline_index);
3263 return std::move(transceiver);
3264}
3265
3266rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3267PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3268 RTC_DCHECK(IsUnifiedPlan());
3269 for (auto transceiver : transceivers_) {
3270 if (transceiver->mid() == mid) {
3271 return transceiver;
3272 }
3273 }
3274 return nullptr;
3275}
3276
3277rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3278PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3279 RTC_DCHECK(IsUnifiedPlan());
3280 for (auto transceiver : transceivers_) {
3281 if (transceiver->internal()->mline_index() == mline_index) {
3282 return transceiver;
3283 }
3284 }
3285 return nullptr;
3286}
3287
3288rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3289PeerConnection::FindAvailableTransceiverToReceive(
3290 cricket::MediaType media_type) const {
3291 RTC_DCHECK(IsUnifiedPlan());
3292 // From JSEP section 5.10 (Applying a Remote Description):
3293 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3294 // the same type that were added to the PeerConnection by addTrack and are not
3295 // associated with any m= section and are not stopped, find the first such
3296 // RtpTransceiver.
3297 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003298 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003299 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3300 !transceiver->stopped()) {
3301 return transceiver;
3302 }
3303 }
3304 return nullptr;
3305}
3306
Steve Antoned10bd92017-12-05 10:52:59 -08003307const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3308 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3309 transceiver,
3310 const SessionDescriptionInterface* sdesc) const {
3311 RTC_DCHECK(transceiver);
3312 RTC_DCHECK(sdesc);
3313 if (IsUnifiedPlan()) {
3314 if (!transceiver->internal()->mid()) {
3315 // This transceiver is not associated with a media section yet.
3316 return nullptr;
3317 }
3318 return sdesc->description()->GetContentByName(
3319 *transceiver->internal()->mid());
3320 } else {
3321 // Plan B only allows at most one audio and one video section, so use the
3322 // first media section of that type.
3323 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003324 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003325 }
3326}
3327
deadbeef46c73892016-11-16 19:42:04 -08003328PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
Karl Wiberg5966c502019-02-21 23:55:09 +01003329 RTC_DCHECK_RUN_ON(signaling_thread());
deadbeef46c73892016-11-16 19:42:04 -08003330 return configuration_;
3331}
3332
deadbeef293e9262017-01-11 12:28:30 -08003333bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3334 RTCError* error) {
Karl Wiberg5966c502019-02-21 23:55:09 +01003335 RTC_DCHECK_RUN_ON(signaling_thread());
3336 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Peter Boström1a9d6152015-12-08 22:15:17 +01003337 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003338 if (IsClosed()) {
3339 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3340 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3341 }
3342
Qingsi Wanga2d60672018-04-11 16:57:45 -07003343 // According to JSEP, after setLocalDescription, changing the candidate pool
3344 // size is not allowed, and changing the set of ICE servers will not result
3345 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003346 if (local_description() && configuration.ice_candidate_pool_size !=
3347 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003348 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3349 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003350 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003351 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003352
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003353 if (local_description() &&
3354 configuration.use_media_transport != configuration_.use_media_transport) {
3355 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3356 "SetLocalDescription.";
3357 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3358 }
3359
3360 if (remote_description() &&
3361 configuration.use_media_transport != configuration_.use_media_transport) {
3362 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3363 "SetRemoteDescription.";
3364 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3365 }
3366
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003367 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003368 configuration.use_media_transport_for_data_channels !=
3369 configuration_.use_media_transport_for_data_channels) {
3370 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3371 "after calling SetLocalDescription.";
3372 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3373 }
3374
3375 if (remote_description() &&
3376 configuration.use_media_transport_for_data_channels !=
3377 configuration_.use_media_transport_for_data_channels) {
3378 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3379 "after calling SetRemoteDescription.";
3380 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3381 }
3382
3383 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003384 configuration.crypto_options != configuration_.crypto_options) {
3385 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3386 "SetLocalDescription.";
3387 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3388 }
3389
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003390 if (configuration.use_media_transport_for_data_channels ||
3391 configuration.use_media_transport) {
3392 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3393 << "Media transport requires MaxBundle policy.";
3394 }
3395
deadbeef293e9262017-01-11 12:28:30 -08003396 // The simplest (and most future-compatible) way to tell if the config was
3397 // modified in an invalid way is to copy each property we do support
3398 // modifying, then use operator==. There are far more properties we don't
3399 // support modifying than those we do, and more could be added.
3400 RTCConfiguration modified_config = configuration_;
3401 modified_config.servers = configuration.servers;
3402 modified_config.type = configuration.type;
3403 modified_config.ice_candidate_pool_size =
3404 configuration.ice_candidate_pool_size;
3405 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003406 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003407 modified_config.ice_check_interval_strong_connectivity =
3408 configuration.ice_check_interval_strong_connectivity;
3409 modified_config.ice_check_interval_weak_connectivity =
3410 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003411 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3412 modified_config.ice_unwritable_min_checks =
3413 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003414 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003415 modified_config.stun_candidate_keepalive_interval =
3416 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003417 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003418 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003419 modified_config.active_reset_srtp_params =
3420 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003421 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003422 modified_config.use_media_transport_for_data_channels =
3423 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003424 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003425 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003426 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3427 }
3428
Steve Anton038834f2017-07-14 15:59:59 -07003429 // Validate the modified configuration.
3430 RTCError validate_error = ValidateConfiguration(modified_config);
3431 if (!validate_error.ok()) {
3432 return SafeSetError(std::move(validate_error), error);
3433 }
3434
deadbeef293e9262017-01-11 12:28:30 -08003435 // Note that this isn't possible through chromium, since it's an unsigned
3436 // short in WebIDL.
3437 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003438 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003439 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3440 }
3441
3442 // Parse ICE servers before hopping to network thread.
3443 cricket::ServerAddresses stun_servers;
3444 std::vector<cricket::RelayServerConfig> turn_servers;
3445 RTCErrorType parse_error =
3446 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3447 if (parse_error != RTCErrorType::NONE) {
3448 return SafeSetError(parse_error, error);
3449 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003450 // Note if STUN or TURN servers were supplied.
3451 if (!stun_servers.empty()) {
3452 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3453 }
3454 if (!turn_servers.empty()) {
3455 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3456 }
deadbeef293e9262017-01-11 12:28:30 -08003457
3458 // In theory this shouldn't fail.
3459 if (!network_thread()->Invoke<bool>(
3460 RTC_FROM_HERE,
3461 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3462 stun_servers, turn_servers, modified_config.type,
3463 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003464 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003465 modified_config.turn_customizer,
3466 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003467 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003468 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3469 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003470
deadbeefd1a38b52016-12-10 13:15:33 -08003471 // As described in JSEP, calling setConfiguration with new ICE servers or
3472 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3473 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003474 if (modified_config.servers != configuration_.servers ||
3475 modified_config.type != configuration_.type ||
3476 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003477 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003478 }
skvladd1f5fda2017-02-03 16:54:05 -08003479
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003480 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003481 transport_controller_->SetMediaTransportSettings(
3482 modified_config.use_media_transport,
3483 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003484
Zhi Huangb57e1692018-06-12 11:41:11 -07003485 if (configuration_.active_reset_srtp_params !=
3486 modified_config.active_reset_srtp_params) {
3487 transport_controller_->SetActiveResetSrtpParams(
3488 modified_config.active_reset_srtp_params);
3489 }
3490
deadbeef293e9262017-01-11 12:28:30 -08003491 configuration_ = modified_config;
Karl Wiberg5966c502019-02-21 23:55:09 +01003492 use_media_transport_ = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08003493 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003494}
3495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003496bool PeerConnection::AddIceCandidate(
3497 const IceCandidateInterface* ice_candidate) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003498 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003499 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003500 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003501 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003502 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003503 return false;
3504 }
Steve Antond25da372017-11-06 14:50:29 -08003505
3506 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003507 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003508 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003509 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003510 return false;
3511 }
3512
3513 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003514 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003515 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003516 return false;
3517 }
3518
3519 bool valid = false;
3520 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3521 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003522 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003523 return false;
3524 }
3525
3526 // Add this candidate to the remote session description.
3527 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003528 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003529 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003530 return false;
3531 }
3532
3533 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003534 bool result = UseCandidate(ice_candidate);
3535 if (result) {
3536 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3537 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3538 } else {
3539 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3540 }
3541 return result;
Steve Antond25da372017-11-06 14:50:29 -08003542 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003543 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003544 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003545 return true;
3546 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003547}
3548
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003549bool PeerConnection::RemoveIceCandidates(
3550 const std::vector<cricket::Candidate>& candidates) {
3551 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003552 if (IsClosed()) {
3553 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3554 return false;
3555 }
3556
Steve Antond25da372017-11-06 14:50:29 -08003557 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003558 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3559 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003560 return false;
3561 }
3562
3563 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003564 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003565 return false;
3566 }
3567
3568 size_t number_removed =
3569 mutable_remote_description()->RemoveCandidates(candidates);
3570 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003571 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003572 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003573 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003574 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003575 }
3576
3577 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003578 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3579 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003580 RTC_LOG(LS_ERROR)
3581 << "RemoveIceCandidates: Error when removing remote candidates: "
3582 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003583 }
3584 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003585}
3586
Niels Möller0c4f7be2018-05-07 14:01:37 +02003587RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003588 if (!worker_thread()->IsCurrent()) {
3589 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003590 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003591 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003592 RTC_DCHECK_RUN_ON(worker_thread());
zstein4b979802017-06-02 14:37:37 -07003593
Niels Möller0c4f7be2018-05-07 14:01:37 +02003594 const bool has_min = bitrate.min_bitrate_bps.has_value();
3595 const bool has_start = bitrate.start_bitrate_bps.has_value();
3596 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003597 if (has_min && *bitrate.min_bitrate_bps < 0) {
3598 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3599 "min_bitrate_bps <= 0");
3600 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003601 if (has_start) {
3602 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003603 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003604 "start_bitrate_bps < min_bitrate_bps");
3605 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003606 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3607 "curent_bitrate_bps < 0");
3608 }
3609 }
3610 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003611 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003612 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003613 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003614 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3615 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3616 "max_bitrate_bps < min_bitrate_bps");
3617 } else if (*bitrate.max_bitrate_bps < 0) {
3618 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3619 "max_bitrate_bps < 0");
3620 }
3621 }
3622
zstein4b979802017-06-02 14:37:37 -07003623 RTC_DCHECK(call_.get());
Piotr (Peter) Slatala7fbfaa42019-03-18 10:31:54 -07003624 call_->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003625
3626 return RTCError::OK();
3627}
3628
Alex Narest78609d52017-10-20 10:37:47 +02003629void PeerConnection::SetBitrateAllocationStrategy(
3630 std::unique_ptr<rtc::BitrateAllocationStrategy>
3631 bitrate_allocation_strategy) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003632 if (!worker_thread()->IsCurrent()) {
Karl Wiberg12ba3ad2019-03-26 11:18:39 +01003633 // TODO(kwiberg): Use a lambda instead when C++14 makes it possible to
3634 // move-capture values in lambdas.
3635 struct Task {
3636 PeerConnection* const pc;
3637 std::unique_ptr<rtc::BitrateAllocationStrategy> strategy;
3638 void operator()() {
3639 RTC_DCHECK_RUN_ON(pc->worker_thread());
3640 pc->call_->SetBitrateAllocationStrategy(std::move(strategy));
3641 }
3642 };
3643 worker_thread()->Invoke<void>(
3644 RTC_FROM_HERE, Task{this, std::move(bitrate_allocation_strategy)});
Alex Narest78609d52017-10-20 10:37:47 +02003645 return;
3646 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01003647 RTC_DCHECK_RUN_ON(worker_thread());
Alex Narest78609d52017-10-20 10:37:47 +02003648 RTC_DCHECK(call_.get());
3649 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3650}
3651
henrika5f6bf242017-11-01 11:06:56 +01003652void PeerConnection::SetAudioPlayout(bool playout) {
3653 if (!worker_thread()->IsCurrent()) {
3654 worker_thread()->Invoke<void>(
3655 RTC_FROM_HERE,
3656 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3657 return;
3658 }
3659 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003660 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003661 audio_state->SetPlayout(playout);
3662}
3663
3664void PeerConnection::SetAudioRecording(bool recording) {
3665 if (!worker_thread()->IsCurrent()) {
3666 worker_thread()->Invoke<void>(
3667 RTC_FROM_HERE,
3668 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3669 return;
3670 }
3671 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003672 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003673 audio_state->SetRecording(recording);
3674}
3675
Steve Anton8c0f7a72017-10-03 10:03:10 -07003676std::unique_ptr<rtc::SSLCertificate>
3677PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003678 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3679 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003680 return nullptr;
3681 }
Steve Antonf25303e2018-10-16 15:23:31 -07003682 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003683}
3684
Zhi Huang70b820f2018-01-27 14:16:15 -08003685std::unique_ptr<rtc::SSLCertChain>
3686PeerConnection::GetRemoteAudioSSLCertChain() {
Karl Wiberga58e1692019-03-26 13:33:43 +01003687 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonafb0bb72018-02-20 11:35:37 -08003688 auto audio_transceiver = GetFirstAudioTransceiver();
3689 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003690 return nullptr;
3691 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003692 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003693 audio_transceiver->internal()->channel()->transport_name());
3694}
3695
3696rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3697PeerConnection::GetFirstAudioTransceiver() const {
3698 for (auto transceiver : transceivers_) {
3699 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3700 return transceiver;
3701 }
3702 }
3703 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003704}
3705
ivoc14d5dbe2016-07-04 07:06:55 -07003706bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3707 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003708 // TODO(eladalon): It would be better to not allow negative values into PC.
3709 const size_t max_size = (max_size_bytes < 0)
3710 ? RtcEventLog::kUnlimitedOutput
3711 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003712 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3713 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3714 output_period_ms = 5000;
3715 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003716 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003717 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003718 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003719}
3720
Bjorn Tereliusde939432017-11-20 17:38:14 +01003721bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3722 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003723 // TODO(eladalon): In C++14, this can be done with a lambda.
3724 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003725 bool operator()() {
3726 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3727 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003728 PeerConnection* const pc;
3729 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003730 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003731 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003732 return worker_thread()->Invoke<bool>(
3733 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003734}
3735
3736void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003737 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003738 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3739}
3740
Harald Alvestrandad88c882018-11-28 16:47:46 +01003741rtc::scoped_refptr<DtlsTransportInterface>
3742PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3743 return transport_controller_->LookupDtlsTransportByMid(mid);
3744}
3745
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003746rtc::scoped_refptr<DtlsTransport>
3747PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3748 return transport_controller_->LookupDtlsTransportByMid(mid);
3749}
3750
Harald Alvestrandc85328f2019-02-28 07:51:00 +01003751rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
3752 const {
3753 return sctp_transport_;
3754}
3755
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003756const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003757 return pending_local_description_ ? pending_local_description_.get()
3758 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003759}
3760
3761const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003762 return pending_remote_description_ ? pending_remote_description_.get()
3763 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003764}
3765
deadbeeffe4a8a42016-12-20 17:56:17 -08003766const SessionDescriptionInterface* PeerConnection::current_local_description()
3767 const {
Steve Anton75737c02017-11-06 10:37:17 -08003768 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003769}
3770
3771const SessionDescriptionInterface* PeerConnection::current_remote_description()
3772 const {
Steve Anton75737c02017-11-06 10:37:17 -08003773 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003774}
3775
3776const SessionDescriptionInterface* PeerConnection::pending_local_description()
3777 const {
Steve Anton75737c02017-11-06 10:37:17 -08003778 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003779}
3780
3781const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3782 const {
Steve Anton75737c02017-11-06 10:37:17 -08003783 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003784}
3785
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003786void PeerConnection::Close() {
Karl Wiberg744310f2019-02-14 10:18:56 +01003787 RTC_DCHECK_RUN_ON(signaling_thread());
Peter Boström1a9d6152015-12-08 22:15:17 +01003788 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003789 // Update stats here so that we have the most recent stats for tracks and
3790 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003791 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003792
Steve Anton75737c02017-11-06 10:37:17 -08003793 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003794 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003795
Mirko Bonadei739baf02019-01-27 17:29:42 +01003796 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003797 transceiver->Stop();
3798 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003799
3800 // Ensure that all asynchronous stats requests are completed before destroying
3801 // the transport controller below.
3802 if (stats_collector_) {
3803 stats_collector_->WaitForPendingRequest();
3804 }
3805
3806 // Don't destroy BaseChannels until after stats has been cleaned up so that
3807 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003808 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003809
Qingsi Wang93a84392018-01-30 17:13:09 -08003810 // The event log is used in the transport controller, which must be outlived
3811 // by the former. CreateOffer by the peer connection is implemented
3812 // asynchronously and if the peer connection is closed without resetting the
3813 // WebRTC session description factory, the session description factory would
3814 // call the transport controller.
3815 webrtc_session_desc_factory_.reset();
3816 transport_controller_.reset();
3817
deadbeef42a42632017-03-10 15:18:00 -08003818 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003819 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3820 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003821
Steve Anton978b8762017-09-29 12:15:02 -07003822 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
Karl Wibergb03ab712019-02-14 11:59:57 +01003823 RTC_DCHECK_RUN_ON(worker_thread());
eladalon248fd4f2017-09-06 05:18:15 -07003824 call_.reset();
3825 // The event log must outlive call (and any other object that uses it).
3826 event_log_.reset();
3827 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003828 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003829 // The .h file says that observer can be discarded after close() returns.
3830 // Make sure this is true.
3831 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003832}
3833
Steve Antonad182762018-09-05 20:22:40 +00003834void PeerConnection::OnMessage(rtc::Message* msg) {
Karl Wiberg744310f2019-02-14 10:18:56 +01003835 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Antonad182762018-09-05 20:22:40 +00003836 switch (msg->message_id) {
3837 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3838 SetSessionDescriptionMsg* param =
3839 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3840 param->observer->OnSuccess();
3841 delete param;
3842 break;
3843 }
3844 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3845 SetSessionDescriptionMsg* param =
3846 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3847 param->observer->OnFailure(std::move(param->error));
3848 delete param;
3849 break;
3850 }
3851 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3852 CreateSessionDescriptionMsg* param =
3853 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3854 param->observer->OnFailure(std::move(param->error));
3855 delete param;
3856 break;
3857 }
3858 case MSG_GETSTATS: {
3859 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3860 StatsReports reports;
3861 stats_->GetStats(param->track, &reports);
3862 param->observer->OnComplete(reports);
3863 delete param;
3864 break;
3865 }
3866 case MSG_FREE_DATACHANNELS: {
3867 sctp_data_channels_to_free_.clear();
3868 break;
3869 }
3870 case MSG_REPORT_USAGE_PATTERN: {
3871 ReportUsagePattern();
3872 break;
3873 }
3874 default:
3875 RTC_NOTREACHED() << "Not implemented";
3876 break;
3877 }
3878}
3879
Steve Antonafb0bb72018-02-20 11:35:37 -08003880cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3881 RTC_DCHECK(!IsUnifiedPlan());
3882 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3883 GetAudioTransceiver()->internal()->channel());
3884 if (voice_channel) {
3885 return voice_channel->media_channel();
3886 } else {
3887 return nullptr;
3888 }
3889}
3890
3891cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3892 RTC_DCHECK(!IsUnifiedPlan());
3893 auto* video_channel = static_cast<cricket::VideoChannel*>(
3894 GetVideoTransceiver()->internal()->channel());
3895 if (video_channel) {
3896 return video_channel->media_channel();
3897 } else {
3898 return nullptr;
3899 }
3900}
3901
Steve Anton4171afb2017-11-20 10:20:22 -08003902void PeerConnection::CreateAudioReceiver(
3903 MediaStreamInterface* stream,
3904 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003905 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3906 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003907 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3908 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003909 auto* audio_receiver = new AudioRtpReceiver(
3910 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003911 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003912 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3913 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3914 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003915 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003916 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003917 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003918}
3919
Steve Anton4171afb2017-11-20 10:20:22 -08003920void PeerConnection::CreateVideoReceiver(
3921 MediaStreamInterface* stream,
3922 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003923 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3924 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003925 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3926 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003927 auto* video_receiver = new VideoRtpReceiver(
3928 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003929 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003930 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3931 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3932 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003933 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003934 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003935 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003936}
3937
deadbeef70ab1a12015-09-28 16:53:55 -07003938// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3939// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003940rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003941 const RtpSenderInfo& remote_sender_info) {
3942 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3943 if (!receiver) {
3944 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3945 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003946 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003947 }
Steve Anton4171afb2017-11-20 10:20:22 -08003948 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3949 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3950 } else {
3951 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3952 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003953 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003954}
3955
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003956void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3957 MediaStreamInterface* stream) {
3958 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003959 RTC_DCHECK(track);
3960 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003961 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003962 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003963 // We already have a sender for this track, so just change the stream_id
3964 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003965 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003966 return;
3967 }
3968
3969 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003970 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003971 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003972 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003973 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003974 // If the sender has already been configured in SDP, we call SetSsrc,
3975 // which will connect the sender to the underlying transport. This can
3976 // occur if a local session description that contains the ID of the sender
3977 // is set before AddStream is called. It can also occur if the local
3978 // session description is not changed and RemoveStream is called, and
3979 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003980 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003981 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003982 if (sender_info) {
3983 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003984 }
3985}
3986
3987// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3988// indefinitely, when we have unified plan SDP.
3989void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3990 MediaStreamInterface* stream) {
3991 RTC_DCHECK(!IsClosed());
3992 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003993 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003994 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3995 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003996 return;
3997 }
Steve Anton4171afb2017-11-20 10:20:22 -08003998 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003999}
4000
4001void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
4002 MediaStreamInterface* stream) {
4003 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07004004 RTC_DCHECK(track);
4005 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004006 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004007 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004008 // We already have a sender for this track, so just change the stream_id
4009 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07004010 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004011 return;
4012 }
4013
4014 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07004015 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02004016 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004017 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08004018 GetVideoTransceiver()->internal()->AddSender(new_sender);
4019 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004020 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08004021 if (sender_info) {
4022 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004023 }
4024}
4025
4026void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
4027 MediaStreamInterface* stream) {
4028 RTC_DCHECK(!IsClosed());
4029 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08004030 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004031 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
4032 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004033 return;
4034 }
Steve Anton4171afb2017-11-20 10:20:22 -08004035 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004036}
4037
Steve Antonba818672017-11-06 10:21:57 -08004038void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
Steve Antonba818672017-11-06 10:21:57 -08004039 if (ice_connection_state_ == new_state) {
4040 return;
4041 }
4042
deadbeefcbecd352015-09-23 11:50:27 -07004043 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08004044 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07004045 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07004046 return;
4047 }
Steve Antonba818672017-11-06 10:21:57 -08004048
Mirko Bonadei675513b2017-11-09 11:09:25 +01004049 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
4050 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08004051 RTC_DCHECK(ice_connection_state_ !=
4052 PeerConnectionInterface::kIceConnectionClosed);
4053
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004054 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004055 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004056}
4057
Alex Loiko9289eda2018-11-23 16:18:59 +00004058void PeerConnection::SetStandardizedIceConnectionState(
4059 PeerConnectionInterface::IceConnectionState new_state) {
Alex Loiko9289eda2018-11-23 16:18:59 +00004060 if (standardized_ice_connection_state_ == new_state)
4061 return;
4062 if (IsClosed())
4063 return;
4064 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01004065 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00004066}
4067
Jonas Olsson635474e2018-10-18 15:58:17 +02004068void PeerConnection::SetConnectionState(
4069 PeerConnectionInterface::PeerConnectionState new_state) {
Jonas Olsson635474e2018-10-18 15:58:17 +02004070 if (connection_state_ == new_state)
4071 return;
4072 if (IsClosed())
4073 return;
4074 connection_state_ = new_state;
4075 Observer()->OnConnectionChange(new_state);
4076}
4077
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004078void PeerConnection::OnIceGatheringChange(
4079 PeerConnectionInterface::IceGatheringState new_state) {
4080 if (IsClosed()) {
4081 return;
4082 }
4083 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004084 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004085}
4086
jbauch81bf7b02017-03-25 08:31:12 -07004087void PeerConnection::OnIceCandidate(
4088 std::unique_ptr<IceCandidateInterface> candidate) {
zhihuang29ff8442016-07-27 11:07:25 -07004089 if (IsClosed()) {
4090 return;
4091 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02004092 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02004093 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
4094 candidate->candidate().address().IsPrivateIP()) {
4095 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
4096 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004097 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004098}
4099
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004100void PeerConnection::OnIceCandidatesRemoved(
4101 const std::vector<cricket::Candidate>& candidates) {
zhihuang29ff8442016-07-27 11:07:25 -07004102 if (IsClosed()) {
4103 return;
4104 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004105 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07004106}
4107
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004108void PeerConnection::ChangeSignalingState(
4109 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08004110 if (signaling_state_ == signaling_state) {
4111 return;
4112 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004113 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
4114 << GetSignalingStateString(signaling_state_)
4115 << " New state: "
4116 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004117 signaling_state_ = signaling_state;
4118 if (signaling_state == kClosed) {
4119 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004120 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00004121 standardized_ice_connection_state_ =
4122 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02004123 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
4124 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004125 if (ice_gathering_state_ != kIceGatheringComplete) {
4126 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004127 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004128 }
4129 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004130 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004131}
4132
deadbeefeb459812015-12-15 19:24:43 -08004133void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
4134 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004135 if (IsClosed()) {
4136 return;
4137 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004138 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004139 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004140}
4141
deadbeefeb459812015-12-15 19:24:43 -08004142void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4143 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004144 if (IsClosed()) {
4145 return;
4146 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004147 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004148 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004149}
4150
4151void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4152 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004153 if (IsClosed()) {
4154 return;
4155 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004156 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004157 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004158}
4159
4160void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4161 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004162 if (IsClosed()) {
4163 return;
4164 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004165 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004166 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004167}
4168
Henrik Boström31638672017-11-23 17:48:32 +01004169void PeerConnection::PostSetSessionDescriptionSuccess(
4170 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004171 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4172 signaling_thread()->Post(RTC_FROM_HERE, this,
4173 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004174}
4175
deadbeefab9b2d12015-10-14 11:33:11 -07004176void PeerConnection::PostSetSessionDescriptionFailure(
4177 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004178 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004179 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004180 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4181 msg->error = std::move(error);
4182 signaling_thread()->Post(RTC_FROM_HERE, this,
4183 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004184}
4185
4186void PeerConnection::PostCreateSessionDescriptionFailure(
4187 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004188 RTCError error) {
4189 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004190 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4191 msg->error = std::move(error);
4192 signaling_thread()->Post(RTC_FROM_HERE, this,
4193 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004194}
4195
zhihuang1c378ed2017-08-17 14:10:50 -07004196void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004197 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004198 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004199 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004200
Steve Antondcc3c022017-12-22 16:02:54 -08004201 if (IsUnifiedPlan()) {
4202 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4203 } else {
4204 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4205 }
4206
Steve Antonfa2260d2017-12-28 16:38:23 -08004207 // Intentionally unset the data channel type for RTP data channel with the
4208 // second condition. Otherwise the RTP data channels would be successfully
4209 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4210 // when building with chromium. We want to leave RTP data channels broken, so
4211 // people won't try to use them.
4212 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4213 session_options->data_channel_type = data_channel_type();
4214 }
4215
Steve Antondcc3c022017-12-22 16:02:54 -08004216 // Apply ICE restart flag and renomination flag.
4217 for (auto& options : session_options->media_description_options) {
4218 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4219 options.transport_options.enable_ice_renomination =
4220 configuration_.enable_ice_renomination;
4221 }
4222
4223 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004224 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004225 session_options->pooled_ice_credentials =
4226 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4227 RTC_FROM_HERE,
4228 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4229 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004230 session_options->offer_extmap_allow_mixed =
4231 configuration_.offer_extmap_allow_mixed;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08004232
4233 if (configuration_.enable_dtls_srtp &&
4234 !configuration_.enable_dtls_srtp.value()) {
4235 session_options->media_transport_settings =
4236 transport_controller_->GenerateOrGetLastMediaTransportOffer();
4237 }
Steve Antondcc3c022017-12-22 16:02:54 -08004238}
4239
4240void PeerConnection::GetOptionsForPlanBOffer(
4241 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4242 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004243 // Figure out transceiver directional preferences.
4244 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4245 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4246
4247 // By default, generate sendrecv/recvonly m= sections.
4248 bool recv_audio = true;
4249 bool recv_video = true;
4250
4251 // By default, only offer a new m= section if we have media to send with it.
4252 bool offer_new_audio_description = send_audio;
4253 bool offer_new_video_description = send_video;
4254 bool offer_new_data_description = HasDataChannels();
4255
4256 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004257 if (offer_answer_options.offer_to_receive_audio !=
4258 RTCOfferAnswerOptions::kUndefined) {
4259 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004260 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004261 offer_new_audio_description ||
4262 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004263 }
Steve Antondcc3c022017-12-22 16:02:54 -08004264 if (offer_answer_options.offer_to_receive_video !=
4265 RTCOfferAnswerOptions::kUndefined) {
4266 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004267 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004268 offer_new_video_description ||
4269 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004270 }
4271
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004272 absl::optional<size_t> audio_index;
4273 absl::optional<size_t> video_index;
4274 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004275 // If a current description exists, generate m= sections in the same order,
4276 // using the first audio/video/data section that appears and rejecting
4277 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004278 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004279 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004280 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004281 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4282 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4283 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004284 }
4285
zhihuang1c378ed2017-08-17 14:10:50 -07004286 // Add audio/video/data m= sections to the end if needed.
4287 if (!audio_index && offer_new_audio_description) {
4288 session_options->media_description_options.push_back(
4289 cricket::MediaDescriptionOptions(
4290 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004291 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4292 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004293 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004294 }
zhihuang1c378ed2017-08-17 14:10:50 -07004295 if (!video_index && offer_new_video_description) {
4296 session_options->media_description_options.push_back(
4297 cricket::MediaDescriptionOptions(
4298 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004299 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4300 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004301 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004302 }
zhihuang1c378ed2017-08-17 14:10:50 -07004303 if (!data_index && offer_new_data_description) {
4304 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004305 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004306 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004307 }
4308
4309 cricket::MediaDescriptionOptions* audio_media_description_options =
4310 !audio_index ? nullptr
4311 : &session_options->media_description_options[*audio_index];
4312 cricket::MediaDescriptionOptions* video_media_description_options =
4313 !video_index ? nullptr
4314 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004315
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004316 AddPlanBRtpSenderOptions(GetSendersInternal(),
4317 audio_media_description_options,
4318 video_media_description_options,
4319 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004320}
4321
Steve Antondcc3c022017-12-22 16:02:54 -08004322static cricket::MediaDescriptionOptions
4323GetMediaDescriptionOptionsForTransceiver(
4324 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4325 transceiver,
4326 const std::string& mid) {
4327 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004328 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004329 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004330 // This behavior is specified in JSEP. The gist is that:
4331 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4332 // sendrecv.
4333 // 2. If the MSID is included, then it must be included in any subsequent
4334 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004335 if (transceiver->stopped() ||
4336 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4337 !transceiver->internal()->has_ever_been_used_to_send())) {
4338 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004339 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004340
4341 cricket::SenderOptions sender_options;
4342 sender_options.track_id = transceiver->sender()->id();
4343 sender_options.stream_ids = transceiver->sender()->stream_ids();
4344
4345 // The following sets up RIDs and Simulcast.
4346 // RIDs are included if Simulcast is requested or if any RID was specified.
Amit Hilbuch619b2942019-02-26 15:55:19 -08004347 RtpParameters send_parameters =
4348 transceiver->internal()->sender_internal()->GetParametersInternal();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004349 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4350 send_parameters.encodings.end(),
4351 [](const RtpEncodingParameters& encoding) {
4352 return !encoding.rid.empty();
4353 });
4354
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004355 std::vector<RidDescription> send_rids;
4356 SimulcastLayerList send_layers;
4357 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4358 if (encoding.rid.empty()) {
4359 continue;
4360 }
4361 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4362 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4363 }
4364
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004365 if (has_rids) {
4366 sender_options.rids = send_rids;
4367 }
4368
4369 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004370 // When RIDs are configured, we must set num_sim_layers to 0 to.
4371 // Otherwise, num_sim_layers must be 1 because either there is no
4372 // simulcast, or simulcast is acheived by munging the SDP.
4373 sender_options.num_sim_layers = has_rids ? 0 : 1;
4374 media_description_options.sender_options.push_back(sender_options);
4375
Steve Antondcc3c022017-12-22 16:02:54 -08004376 return media_description_options;
4377}
4378
Steve Anton5c72e712018-12-10 14:25:30 -08004379// Returns the ContentInfo at mline index |i|, or null if none exists.
4380static const ContentInfo* GetContentByIndex(
4381 const SessionDescriptionInterface* sdesc,
4382 size_t i) {
4383 if (!sdesc) {
4384 return nullptr;
4385 }
4386 const ContentInfos& contents = sdesc->description()->contents();
4387 return (i < contents.size() ? &contents[i] : nullptr);
4388}
4389
Steve Antondcc3c022017-12-22 16:02:54 -08004390void PeerConnection::GetOptionsForUnifiedPlanOffer(
4391 const RTCOfferAnswerOptions& offer_answer_options,
4392 cricket::MediaSessionOptions* session_options) {
4393 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4394 // Offers) and 5.2.2 (Subsequent Offers).
4395 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4396 const ContentInfos& local_contents =
4397 (local_description() ? local_description()->description()->contents()
4398 : ContentInfos());
4399 const ContentInfos& remote_contents =
4400 (remote_description() ? remote_description()->description()->contents()
4401 : ContentInfos());
4402 // The mline indices that can be recycled. New transceivers should reuse these
4403 // slots first.
4404 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004405 // First, go through each media section that exists in either the local or
4406 // remote description and generate a media section in this offer for the
4407 // associated transceiver. If a media section can be recycled, generate a
4408 // default, rejected media section here that can be later overwritten.
4409 for (size_t i = 0;
4410 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4411 // Either |local_content| or |remote_content| is non-null.
4412 const ContentInfo* local_content =
4413 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004414 const ContentInfo* current_local_content =
4415 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004416 const ContentInfo* remote_content =
4417 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004418 const ContentInfo* current_remote_content =
4419 GetContentByIndex(current_remote_description(), i);
4420 bool had_been_rejected =
4421 (current_local_content && current_local_content->rejected) ||
4422 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004423 const std::string& mid =
4424 (local_content ? local_content->name : remote_content->name);
4425 cricket::MediaType media_type =
4426 (local_content ? local_content->media_description()->type()
4427 : remote_content->media_description()->type());
4428 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4429 media_type == cricket::MEDIA_TYPE_VIDEO) {
4430 auto transceiver = GetAssociatedTransceiver(mid);
4431 RTC_CHECK(transceiver);
4432 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004433 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004434 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004435 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004436 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4437 RtpTransceiverDirection::kInactive,
4438 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004439 recycleable_mline_indices.push(i);
4440 } else {
4441 session_options->media_description_options.push_back(
4442 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4443 // CreateOffer shouldn't really cause any state changes in
4444 // PeerConnection, but we need a way to match new transceivers to new
4445 // media sections in SetLocalDescription and JSEP specifies this is done
4446 // by recording the index of the media section generated for the
4447 // transceiver in the offer.
4448 transceiver->internal()->set_mline_index(i);
4449 }
4450 } else {
4451 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004452 RTC_CHECK(GetDataMid());
4453 if (had_been_rejected || mid != *GetDataMid()) {
4454 session_options->media_description_options.push_back(
4455 GetMediaDescriptionOptionsForRejectedData(mid));
4456 } else {
4457 session_options->media_description_options.push_back(
4458 GetMediaDescriptionOptionsForActiveData(mid));
4459 }
Steve Antondcc3c022017-12-22 16:02:54 -08004460 }
4461 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004462
Steve Antondcc3c022017-12-22 16:02:54 -08004463 // Next, look for transceivers that are newly added (that is, are not stopped
4464 // and not associated). Reuse media sections marked as recyclable first,
4465 // otherwise append to the end of the offer. New media sections should be
4466 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004467 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004468 if (transceiver->mid() || transceiver->stopped()) {
4469 continue;
4470 }
4471 size_t mline_index;
4472 if (!recycleable_mline_indices.empty()) {
4473 mline_index = recycleable_mline_indices.front();
4474 recycleable_mline_indices.pop();
4475 session_options->media_description_options[mline_index] =
4476 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004477 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004478 } else {
4479 mline_index = session_options->media_description_options.size();
4480 session_options->media_description_options.push_back(
4481 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004482 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004483 }
4484 // See comment above for why CreateOffer changes the transceiver's state.
4485 transceiver->internal()->set_mline_index(mline_index);
4486 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004487 // Lastly, add a m-section if we have local data channels and an m section
4488 // does not already exist.
4489 if (!GetDataMid() && HasDataChannels()) {
4490 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004491 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004492 }
Steve Antondcc3c022017-12-22 16:02:54 -08004493}
4494
4495void PeerConnection::GetOptionsForAnswer(
4496 const RTCOfferAnswerOptions& offer_answer_options,
4497 cricket::MediaSessionOptions* session_options) {
4498 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4499
4500 if (IsUnifiedPlan()) {
4501 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4502 } else {
4503 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4504 }
4505
Steve Antonfa2260d2017-12-28 16:38:23 -08004506 // Intentionally unset the data channel type for RTP data channel. Otherwise
4507 // the RTP data channels would be successfully negotiated by default and the
4508 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4509 // We want to leave RTP data channels broken, so people won't try to use them.
4510 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4511 session_options->data_channel_type = data_channel_type();
4512 }
4513
Steve Antondcc3c022017-12-22 16:02:54 -08004514 // Apply ICE renomination flag.
4515 for (auto& options : session_options->media_description_options) {
4516 options.transport_options.enable_ice_renomination =
4517 configuration_.enable_ice_renomination;
4518 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004519
4520 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004521 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004522 session_options->pooled_ice_credentials =
4523 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4524 RTC_FROM_HERE,
4525 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4526 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004527}
4528
Steve Antondcc3c022017-12-22 16:02:54 -08004529void PeerConnection::GetOptionsForPlanBAnswer(
4530 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004531 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004532 // Figure out transceiver directional preferences.
4533 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4534 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4535
4536 // By default, generate sendrecv/recvonly m= sections. The direction is also
4537 // restricted by the direction in the offer.
4538 bool recv_audio = true;
4539 bool recv_video = true;
4540
4541 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004542 if (offer_answer_options.offer_to_receive_audio !=
4543 RTCOfferAnswerOptions::kUndefined) {
4544 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004545 }
Steve Antondcc3c022017-12-22 16:02:54 -08004546 if (offer_answer_options.offer_to_receive_video !=
4547 RTCOfferAnswerOptions::kUndefined) {
4548 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004549 }
4550
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004551 absl::optional<size_t> audio_index;
4552 absl::optional<size_t> video_index;
4553 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004554
4555 // Generate m= sections that match those in the offer.
4556 // Note that mediasession.cc will handle intersection our preferred
4557 // direction with the offered direction.
4558 GenerateMediaDescriptionOptions(
4559 remote_description(),
4560 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4561 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4562 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004563
4564 cricket::MediaDescriptionOptions* audio_media_description_options =
4565 !audio_index ? nullptr
4566 : &session_options->media_description_options[*audio_index];
4567 cricket::MediaDescriptionOptions* video_media_description_options =
4568 !video_index ? nullptr
4569 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004570
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004571 AddPlanBRtpSenderOptions(GetSendersInternal(),
4572 audio_media_description_options,
4573 video_media_description_options,
4574 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004575}
zhihuangaf388472016-11-02 16:49:48 -07004576
Steve Antondcc3c022017-12-22 16:02:54 -08004577void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4578 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4579 cricket::MediaSessionOptions* session_options) {
4580 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4581 // Answers) and 5.3.2 (Subsequent Answers).
4582 RTC_DCHECK(remote_description());
4583 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4584 for (const ContentInfo& content :
4585 remote_description()->description()->contents()) {
4586 cricket::MediaType media_type = content.media_description()->type();
4587 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4588 media_type == cricket::MEDIA_TYPE_VIDEO) {
4589 auto transceiver = GetAssociatedTransceiver(content.name);
4590 RTC_CHECK(transceiver);
4591 session_options->media_description_options.push_back(
4592 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4593 } else {
4594 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004595 // Reject all data sections if data channels are disabled.
4596 // Reject a data section if it has already been rejected.
4597 // Reject all data sections except for the first one.
4598 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4599 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004600 session_options->media_description_options.push_back(
4601 GetMediaDescriptionOptionsForRejectedData(content.name));
4602 } else {
4603 session_options->media_description_options.push_back(
4604 GetMediaDescriptionOptionsForActiveData(content.name));
4605 }
Steve Antondcc3c022017-12-22 16:02:54 -08004606 }
4607 }
htaa2a49d92016-03-04 02:51:39 -08004608}
4609
zhihuang1c378ed2017-08-17 14:10:50 -07004610void PeerConnection::GenerateMediaDescriptionOptions(
4611 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004612 RtpTransceiverDirection audio_direction,
4613 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004614 absl::optional<size_t>* audio_index,
4615 absl::optional<size_t>* video_index,
4616 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004617 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004618 for (const cricket::ContentInfo& content :
4619 session_desc->description()->contents()) {
4620 if (IsAudioContent(&content)) {
4621 // If we already have an audio m= section, reject this extra one.
4622 if (*audio_index) {
4623 session_options->media_description_options.push_back(
4624 cricket::MediaDescriptionOptions(
4625 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004626 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004627 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004628 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004629 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004630 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4631 content.name, audio_direction,
4632 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004633 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004634 }
4635 } else if (IsVideoContent(&content)) {
4636 // If we already have an video m= section, reject this extra one.
4637 if (*video_index) {
4638 session_options->media_description_options.push_back(
4639 cricket::MediaDescriptionOptions(
4640 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004641 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004642 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004643 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004644 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004645 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4646 content.name, video_direction,
4647 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004648 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004649 }
4650 } else {
4651 RTC_DCHECK(IsDataContent(&content));
4652 // If we already have an data m= section, reject this extra one.
4653 if (*data_index) {
4654 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004655 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004656 } else {
4657 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004658 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004659 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004660 }
4661 }
htaa2a49d92016-03-04 02:51:39 -08004662 }
deadbeefab9b2d12015-10-14 11:33:11 -07004663}
4664
Steve Antonfa2260d2017-12-28 16:38:23 -08004665cricket::MediaDescriptionOptions
4666PeerConnection::GetMediaDescriptionOptionsForActiveData(
4667 const std::string& mid) const {
4668 // Direction for data sections is meaningless, but legacy endpoints might
4669 // expect sendrecv.
4670 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4671 RtpTransceiverDirection::kSendRecv,
4672 /*stopped=*/false);
4673 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4674 return options;
4675}
4676
4677cricket::MediaDescriptionOptions
4678PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4679 const std::string& mid) const {
4680 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4681 RtpTransceiverDirection::kInactive,
4682 /*stopped=*/true);
4683 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4684 return options;
4685}
4686
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004687absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004688 switch (data_channel_type_) {
4689 case cricket::DCT_RTP:
4690 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004691 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004692 }
4693 return rtp_data_channel_->content_name();
4694 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004695 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004696 case cricket::DCT_MEDIA_TRANSPORT:
4697 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004698 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004699 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004700 }
4701}
4702
Steve Anton4171afb2017-11-20 10:20:22 -08004703void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4704 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4705 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004706 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004707}
4708
Steve Anton4171afb2017-11-20 10:20:22 -08004709void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004710 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004711 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004712 cricket::MediaType media_type,
4713 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004714 RTC_DCHECK(!IsUnifiedPlan());
4715
Steve Anton4171afb2017-11-20 10:20:22 -08004716 std::vector<RtpSenderInfo>* current_senders =
4717 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004718
Steve Anton4171afb2017-11-20 10:20:22 -08004719 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004720 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004721 for (auto sender_it = current_senders->begin();
4722 sender_it != current_senders->end();
4723 /* incremented manually */) {
4724 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004725 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004726 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004727 std::string params_stream_id;
4728 if (params) {
4729 params_stream_id =
4730 (!params->first_stream_id().empty() ? params->first_stream_id()
4731 : kDefaultStreamId);
4732 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004733 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004734 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004735 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004736 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004737 sender_exists) {
4738 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004739 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004740 OnRemoteSenderRemoved(info, media_type);
4741 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004742 }
4743 }
4744
Steve Anton4171afb2017-11-20 10:20:22 -08004745 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004746 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004747 if (!params.has_ssrcs()) {
4748 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4749 // sender, this means it is coming from a Unified Plan endpoint,so we just
4750 // create a default.
4751 default_sender_needed = true;
4752 break;
4753 }
4754
Seth Hampson845e8782018-03-02 11:34:10 -08004755 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004756 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004757 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4758 // not supported in Plan B, we just take the first here and create the
4759 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004760 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004761 (!params.first_stream_id().empty() ? params.first_stream_id()
4762 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004763 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004764 uint32_t ssrc = params.first_ssrc();
4765
4766 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004767 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004768 if (!stream) {
4769 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004770 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004771 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004772 remote_streams_->AddStream(stream);
4773 new_streams->AddStream(stream);
4774 }
4775
Steve Anton4171afb2017-11-20 10:20:22 -08004776 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004777 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004778 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004779 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004780 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004781 }
4782 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004783
Steve Anton4171afb2017-11-20 10:20:22 -08004784 // Add default sender if necessary.
4785 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004786 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004787 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004788 if (!default_stream) {
4789 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004790 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004791 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004792 remote_streams_->AddStream(default_stream);
4793 new_streams->AddStream(default_stream);
4794 }
Steve Anton4171afb2017-11-20 10:20:22 -08004795 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4796 ? kDefaultAudioSenderId
4797 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004798 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004799 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004800 if (!default_sender_info) {
4801 current_senders->push_back(
Ruslan Burakov7ea46052019-02-16 02:07:05 +01004802 RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
Steve Anton4171afb2017-11-20 10:20:22 -08004803 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004804 }
4805 }
deadbeefab9b2d12015-10-14 11:33:11 -07004806}
4807
Steve Anton4171afb2017-11-20 10:20:22 -08004808void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4809 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004810 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4811 << " receiver for track_id=" << sender_info.sender_id
4812 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004813
Steve Anton3d954a62018-04-02 11:27:23 -07004814 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004815 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004816 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004817 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004818 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004819 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004820 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004821 }
4822}
4823
Steve Anton4171afb2017-11-20 10:20:22 -08004824void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4825 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004826 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4827 << " receiver for track_id=" << sender_info.sender_id
4828 << " and stream_id=" << sender_info.stream_id;
4829
Seth Hampson845e8782018-03-02 11:34:10 -08004830 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004831
Henrik Boström933d8b02017-10-10 10:05:16 -07004832 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004833 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004834 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4835 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004836 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004837 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004838 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004839 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004840 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004841 }
4842 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004843 // Stopping or destroying a VideoRtpReceiver will end the
4844 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004845 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004846 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004847 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004848 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004849 // There's no guarantee the track is still available, e.g. the track may
4850 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004851 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004852 }
4853 } else {
nisseede5da42017-01-12 05:15:36 -08004854 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004855 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004856 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004857 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004858 }
deadbeefab9b2d12015-10-14 11:33:11 -07004859}
4860
4861void PeerConnection::UpdateEndedRemoteMediaStreams() {
4862 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4863 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4864 MediaStreamInterface* stream = remote_streams_->at(i);
4865 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4866 streams_to_remove.push_back(stream);
4867 }
4868 }
4869
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004870 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004871 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004872 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004873 }
4874}
4875
Steve Anton4171afb2017-11-20 10:20:22 -08004876void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004877 const std::vector<cricket::StreamParams>& streams,
4878 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004879 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004880
Seth Hampson845e8782018-03-02 11:34:10 -08004881 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004882 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004883 for (auto sender_it = current_senders->begin();
4884 sender_it != current_senders->end();
4885 /* incremented manually */) {
4886 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004887 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004888 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4889 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004890 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004891 OnLocalSenderRemoved(info, media_type);
4892 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004893 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004894 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004895 }
4896 }
4897
Steve Anton4171afb2017-11-20 10:20:22 -08004898 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004899 for (const cricket::StreamParams& params : streams) {
4900 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004901 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004902 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004903 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004904 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004905 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004906 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004907 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004908 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004909 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004910 }
4911 }
4912}
4913
Steve Anton4171afb2017-11-20 10:20:22 -08004914void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4915 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004916 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004917 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004918 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004919 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4920 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004921 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004922 return;
4923 }
4924
deadbeeffac06552015-11-25 11:26:01 -08004925 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004926 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004927 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004928 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004929 }
deadbeeffac06552015-11-25 11:26:01 -08004930
Seth Hampson5b4f0752018-04-02 16:31:36 -07004931 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004932 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004933}
4934
Steve Anton4171afb2017-11-20 10:20:22 -08004935void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4936 cricket::MediaType media_type) {
4937 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004938 if (!sender) {
4939 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004940 // SessionDescriptions has been renegotiated.
4941 return;
4942 }
deadbeeffac06552015-11-25 11:26:01 -08004943
4944 // A sender has been removed from the SessionDescription but it's still
4945 // associated with the PeerConnection. This only occurs if the SDP doesn't
4946 // match with the calls to CreateSender, AddStream and RemoveStream.
4947 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004948 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004949 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004950 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004951 }
deadbeeffac06552015-11-25 11:26:01 -08004952
Steve Anton4171afb2017-11-20 10:20:22 -08004953 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004954}
4955
4956void PeerConnection::UpdateLocalRtpDataChannels(
4957 const cricket::StreamParamsVec& streams) {
4958 std::vector<std::string> existing_channels;
4959
4960 // Find new and active data channels.
4961 for (const cricket::StreamParams& params : streams) {
4962 // |it->sync_label| is actually the data channel label. The reason is that
4963 // we use the same naming of data channels as we do for
4964 // MediaStreams and Tracks.
4965 // For MediaStreams, the sync_label is the MediaStream label and the
4966 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004967 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004968 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004969 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004970 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004971 continue;
4972 }
4973 // Set the SSRC the data channel should use for sending.
4974 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4975 existing_channels.push_back(data_channel_it->first);
4976 }
4977
4978 UpdateClosingRtpDataChannels(existing_channels, true);
4979}
4980
4981void PeerConnection::UpdateRemoteRtpDataChannels(
4982 const cricket::StreamParamsVec& streams) {
4983 std::vector<std::string> existing_channels;
4984
4985 // Find new and active data channels.
4986 for (const cricket::StreamParams& params : streams) {
4987 // The data channel label is either the mslabel or the SSRC if the mslabel
4988 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004989 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004990 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004991 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004992 auto data_channel_it = rtp_data_channels_.find(label);
4993 if (data_channel_it == rtp_data_channels_.end()) {
4994 // This is a new data channel.
4995 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4996 } else {
4997 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4998 }
4999 existing_channels.push_back(label);
5000 }
5001
5002 UpdateClosingRtpDataChannels(existing_channels, false);
5003}
5004
5005void PeerConnection::UpdateClosingRtpDataChannels(
5006 const std::vector<std::string>& active_channels,
5007 bool is_local_update) {
5008 auto it = rtp_data_channels_.begin();
5009 while (it != rtp_data_channels_.end()) {
5010 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08005011 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07005012 ++it;
5013 continue;
5014 }
5015
5016 if (is_local_update) {
5017 data_channel->SetSendSsrc(0);
5018 } else {
5019 data_channel->RemotePeerRequestClose();
5020 }
5021
5022 if (data_channel->state() == DataChannel::kClosed) {
5023 rtp_data_channels_.erase(it);
5024 it = rtp_data_channels_.begin();
5025 } else {
5026 ++it;
5027 }
5028 }
5029}
5030
5031void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
5032 uint32_t remote_ssrc) {
5033 rtc::scoped_refptr<DataChannel> channel(
5034 InternalCreateDataChannel(label, nullptr));
5035 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005036 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01005037 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07005038 return;
5039 }
5040 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07005041 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5042 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005043 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07005044}
5045
5046rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
5047 const std::string& label,
5048 const InternalDataChannelInit* config) {
5049 if (IsClosed()) {
5050 return nullptr;
5051 }
Steve Anton75737c02017-11-06 10:37:17 -08005052 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005053 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07005054 << "InternalCreateDataChannel: Data is not supported in this call.";
5055 return nullptr;
5056 }
5057 InternalDataChannelInit new_config =
5058 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005059 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07005060 if (new_config.id < 0) {
5061 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08005062 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07005063 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005064 RTC_LOG(LS_ERROR)
5065 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07005066 return nullptr;
5067 }
5068 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005069 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005070 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07005071 return nullptr;
5072 }
5073 }
5074
Steve Anton75737c02017-11-06 10:37:17 -08005075 rtc::scoped_refptr<DataChannel> channel(
5076 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07005077 if (!channel) {
5078 sid_allocator_.ReleaseSid(new_config.id);
5079 return nullptr;
5080 }
5081
5082 if (channel->data_channel_type() == cricket::DCT_RTP) {
5083 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005084 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
5085 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07005086 return nullptr;
5087 }
5088 rtp_data_channels_[channel->label()] = channel;
5089 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005090 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07005091 sctp_data_channels_.push_back(channel);
5092 channel->SignalClosed.connect(this,
5093 &PeerConnection::OnSctpDataChannelClosed);
5094 }
5095
Steve Anton2d8609c2018-01-23 16:38:46 -08005096 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07005097 return channel;
5098}
5099
5100bool PeerConnection::HasDataChannels() const {
5101 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
5102}
5103
5104void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
5105 for (const auto& channel : sctp_data_channels_) {
5106 if (channel->id() < 0) {
5107 int sid;
5108 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005109 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07005110 continue;
5111 }
5112 channel->SetSctpSid(sid);
5113 }
5114 }
5115}
5116
5117void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08005118 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07005119 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
5120 ++it) {
5121 if (it->get() == channel) {
5122 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005123 // After the closing procedure is done, it's safe to use this ID for
5124 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07005125 sid_allocator_.ReleaseSid(channel->id());
5126 }
deadbeefbd292462015-12-14 18:15:29 -08005127 // Since this method is triggered by a signal from the DataChannel,
5128 // we can't free it directly here; we need to free it asynchronously.
5129 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07005130 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00005131 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
5132 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07005133 return;
5134 }
5135 }
5136}
5137
deadbeefab9b2d12015-10-14 11:33:11 -07005138void PeerConnection::OnDataChannelDestroyed() {
5139 // Use a temporary copy of the RTP/SCTP DataChannel list because the
5140 // DataChannel may callback to us and try to modify the list.
5141 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
5142 temp_rtp_dcs.swap(rtp_data_channels_);
5143 for (const auto& kv : temp_rtp_dcs) {
5144 kv.second->OnTransportChannelDestroyed();
5145 }
5146
5147 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5148 temp_sctp_dcs.swap(sctp_data_channels_);
5149 for (const auto& channel : temp_sctp_dcs) {
5150 channel->OnTransportChannelDestroyed();
5151 }
5152}
5153
5154void PeerConnection::OnDataChannelOpenMessage(
5155 const std::string& label,
5156 const InternalDataChannelInit& config) {
5157 rtc::scoped_refptr<DataChannel> channel(
5158 InternalCreateDataChannel(label, &config));
5159 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005160 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005161 return;
5162 }
5163
deadbeefa601f5c2016-06-06 14:27:39 -07005164 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5165 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005166 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005167 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005168}
5169
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005170bool PeerConnection::HandleOpenMessage_s(
5171 const cricket::ReceiveDataParams& params,
5172 const rtc::CopyOnWriteBuffer& buffer) {
5173 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5174 // Received OPEN message; parse and signal that a new data channel should
5175 // be created.
5176 std::string label;
5177 InternalDataChannelInit config;
5178 config.id = params.ssrc;
5179 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5180 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5181 << params.ssrc;
5182 return true;
5183 }
5184 config.open_handshake_role = InternalDataChannelInit::kAcker;
5185 OnDataChannelOpenMessage(label, config);
5186 return true;
5187 }
5188 return false;
5189}
5190
Steve Anton4171afb2017-11-20 10:20:22 -08005191rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5192PeerConnection::GetAudioTransceiver() const {
5193 // This method only works with Plan B SDP, where there is a single
5194 // audio/video transceiver.
5195 RTC_DCHECK(!IsUnifiedPlan());
5196 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005197 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005198 return transceiver;
5199 }
5200 }
5201 RTC_NOTREACHED();
5202 return nullptr;
5203}
5204
5205rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5206PeerConnection::GetVideoTransceiver() const {
5207 // This method only works with Plan B SDP, where there is a single
5208 // audio/video transceiver.
5209 RTC_DCHECK(!IsUnifiedPlan());
5210 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005211 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005212 return transceiver;
5213 }
5214 }
5215 RTC_NOTREACHED();
5216 return nullptr;
5217}
5218
5219// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5220// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005221bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005222 switch (type) {
5223 case cricket::MEDIA_TYPE_AUDIO:
5224 return !GetAudioTransceiver()->internal()->senders().empty();
5225 case cricket::MEDIA_TYPE_VIDEO:
5226 return !GetVideoTransceiver()->internal()->senders().empty();
5227 case cricket::MEDIA_TYPE_DATA:
5228 return false;
5229 }
5230 RTC_NOTREACHED();
5231 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005232}
5233
Steve Anton4171afb2017-11-20 10:20:22 -08005234rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5235PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005236 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005237 for (auto sender : transceiver->internal()->senders()) {
5238 if (sender->track() == track) {
5239 return sender;
5240 }
5241 }
5242 }
5243 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005244}
5245
Steve Anton4171afb2017-11-20 10:20:22 -08005246rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5247PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005248 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005249 for (auto sender : transceiver->internal()->senders()) {
5250 if (sender->id() == sender_id) {
5251 return sender;
5252 }
5253 }
5254 }
5255 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005256}
5257
Steve Anton4171afb2017-11-20 10:20:22 -08005258rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5259PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005260 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005261 for (auto receiver : transceiver->internal()->receivers()) {
5262 if (receiver->id() == receiver_id) {
5263 return receiver;
5264 }
5265 }
5266 }
5267 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005268}
5269
Steve Anton4171afb2017-11-20 10:20:22 -08005270std::vector<PeerConnection::RtpSenderInfo>*
5271PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5272 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5273 media_type == cricket::MEDIA_TYPE_VIDEO);
5274 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5275 ? &remote_audio_sender_infos_
5276 : &remote_video_sender_infos_;
5277}
5278
5279std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005280 cricket::MediaType media_type) {
5281 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5282 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005283 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5284 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005285}
5286
Steve Anton4171afb2017-11-20 10:20:22 -08005287const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5288 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005289 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005290 const std::string sender_id) const {
5291 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005292 if (sender_info.stream_id == stream_id &&
5293 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005294 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005295 }
5296 }
5297 return nullptr;
5298}
5299
5300DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5301 for (const auto& channel : sctp_data_channels_) {
5302 if (channel->id() == sid) {
5303 return channel;
5304 }
5305 }
5306 return nullptr;
5307}
5308
Karl Wibergfb3be392019-03-22 14:13:22 +01005309PeerConnection::InitializePortAllocatorResult
5310PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005311 const cricket::ServerAddresses& stun_servers,
5312 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005313 const RTCConfiguration& configuration) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005314 RTC_DCHECK_RUN_ON(network_thread());
5315
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005316 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005317 // To handle both internal and externally created port allocator, we will
5318 // enable BUNDLE here.
Karl Wibergfb3be392019-03-22 14:13:22 +01005319 int port_allocator_flags = port_allocator_->flags();
5320 port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5321 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5322 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005323 // If the disable-IPv6 flag was specified, we'll not override it
5324 // by experiment.
5325 if (configuration.disable_ipv6) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005326 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005327 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5328 .find("Disabled") == 0) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005329 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005330 }
5331
zhihuangb09b3f92017-03-07 14:40:51 -08005332 if (configuration.disable_ipv6_on_wifi) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005333 port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005334 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005335 }
5336
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005337 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005338 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005339 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005340 }
5341
honghaiz60347052016-05-31 18:29:12 -07005342 if (configuration.candidate_network_policy ==
5343 kCandidateNetworkPolicyLowCost) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005344 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005345 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005346 }
5347
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005348 if (configuration.disable_link_local_networks) {
Karl Wibergfb3be392019-03-22 14:13:22 +01005349 port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005350 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5351 }
5352
Karl Wibergfb3be392019-03-22 14:13:22 +01005353 port_allocator_->set_flags(port_allocator_flags);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005354 // No step delay is used while allocating ports.
5355 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5356 port_allocator_->set_candidate_filter(
5357 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005358 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005359
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005360 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005361 for (auto& turn_server : turn_servers_copy) {
5362 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005363 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005364 // Call this last since it may create pooled allocator sessions using the
5365 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005366 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005367 stun_servers, std::move(turn_servers_copy),
5368 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5369 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005370 configuration.stun_candidate_keepalive_interval);
Karl Wibergfb3be392019-03-22 14:13:22 +01005371
5372 InitializePortAllocatorResult res;
5373 res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
5374 return res;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005375}
5376
deadbeef91dd5672016-05-18 16:55:30 -07005377bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005378 const cricket::ServerAddresses& stun_servers,
5379 const std::vector<cricket::RelayServerConfig>& turn_servers,
5380 IceTransportsType type,
5381 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005382 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005383 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005384 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005385 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005386 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005387 // According to JSEP, after setLocalDescription, changing the candidate pool
5388 // size is not allowed, and changing the set of ICE servers will not result
5389 // in new candidates being gathered.
5390 if (local_description()) {
5391 port_allocator_->FreezeCandidatePool();
5392 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005393 // Add the custom tls turn servers if they exist.
5394 auto turn_servers_copy = turn_servers;
5395 for (auto& turn_server : turn_servers_copy) {
5396 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5397 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005398 // Call this last since it may create pooled allocator sessions using the
5399 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005400 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005401 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5402 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005403}
5404
Steve Antonba818672017-11-06 10:21:57 -08005405cricket::ChannelManager* PeerConnection::channel_manager() const {
5406 return factory_->channel_manager();
5407}
5408
Elad Alon99c3fe52017-10-13 16:29:40 +02005409bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005410 std::unique_ptr<RtcEventLogOutput> output,
5411 int64_t output_period_ms) {
Karl Wibergb03ab712019-02-14 11:59:57 +01005412 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005413 if (!event_log_) {
5414 return false;
5415 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005416 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005417}
5418
5419void PeerConnection::StopRtcEventLog_w() {
Karl Wibergb03ab712019-02-14 11:59:57 +01005420 RTC_DCHECK_RUN_ON(worker_thread());
zhihuang77985012017-02-07 15:45:16 -08005421 if (event_log_) {
5422 event_log_->StopLogging();
5423 }
ivoc14d5dbe2016-07-04 07:06:55 -07005424}
nisseeaabdf62017-05-05 02:23:02 -07005425
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005426cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005427 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005428 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005429 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005430 if (channel && channel->content_name() == content_name) {
5431 return channel;
5432 }
Steve Anton75737c02017-11-06 10:37:17 -08005433 }
5434 if (rtp_data_channel() &&
5435 rtp_data_channel()->content_name() == content_name) {
5436 return rtp_data_channel();
5437 }
5438 return nullptr;
5439}
5440
5441bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005442 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005443 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005444 RTC_LOG(LS_INFO)
5445 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005446 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005447 return false;
5448 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005449 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005450 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005451 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005452 return false;
5453 }
5454
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005455 absl::optional<rtc::SSLRole> dtls_role;
5456 if (sctp_mid_) {
5457 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5458 } else if (is_caller_) {
5459 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5460 }
Zhi Huange830e682018-03-30 10:48:35 -07005461 if (dtls_role) {
5462 *role = *dtls_role;
5463 return true;
5464 }
5465 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005466}
5467
5468bool PeerConnection::GetSslRole(const std::string& content_name,
5469 rtc::SSLRole* role) {
5470 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005471 RTC_LOG(LS_INFO)
5472 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005473 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005474 return false;
5475 }
5476
Zhi Huange830e682018-03-30 10:48:35 -07005477 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5478 if (dtls_role) {
5479 *role = *dtls_role;
5480 return true;
5481 }
5482 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005483}
5484
Steve Antonf8470812017-12-04 10:46:21 -08005485void PeerConnection::SetSessionError(SessionError error,
5486 const std::string& error_desc) {
5487 RTC_DCHECK_RUN_ON(signaling_thread());
5488 if (error != session_error_) {
5489 session_error_ = error;
5490 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005491 }
5492}
5493
Zhi Huange830e682018-03-30 10:48:35 -07005494RTCError PeerConnection::UpdateSessionState(
5495 SdpType type,
5496 cricket::ContentSource source,
5497 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005498 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005499
5500 // If there's already a pending error then no state transition should happen.
5501 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005502 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005503
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005504 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005505 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005506 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005507 }
5508
5509 // Update the signaling state according to the specified state machine (see
5510 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005511 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005512 ChangeSignalingState(source == cricket::CS_LOCAL
5513 ? PeerConnectionInterface::kHaveLocalOffer
5514 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005515 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005516 ChangeSignalingState(source == cricket::CS_LOCAL
5517 ? PeerConnectionInterface::kHaveLocalPrAnswer
5518 : PeerConnectionInterface::kHaveRemotePrAnswer);
5519 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005520 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005521 ChangeSignalingState(PeerConnectionInterface::kStable);
5522 }
5523
5524 // Update internal objects according to the session description's media
5525 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005526 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005527 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005528 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005529 }
5530
Steve Anton8a006912017-12-04 15:25:56 -08005531 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005532}
5533
Steve Anton8a006912017-12-04 15:25:56 -08005534RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005535 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005536 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005537 const SessionDescriptionInterface* sdesc =
5538 (source == cricket::CS_LOCAL ? local_description()
5539 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005540 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005541
5542 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005543 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005544 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005545 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005546 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005547 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005548 continue;
5549 }
5550 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005551 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005552 if (!content_desc) {
5553 continue;
5554 }
5555 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005556 bool success = (source == cricket::CS_LOCAL)
5557 ? channel->SetLocalContent(content_desc, type, &error)
5558 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005559 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005560 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005561 }
5562 }
5563
5564 // If using the RtpDataChannel, push down the new SDP section for it too.
5565 if (rtp_data_channel_) {
5566 const ContentInfo* data_content =
5567 cricket::GetFirstDataContent(sdesc->description());
5568 if (data_content && !data_content->rejected) {
5569 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005570 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005571 if (data_desc) {
5572 std::string error;
5573 bool success =
5574 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005575 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005576 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005577 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005578 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005579 }
Steve Anton75737c02017-11-06 10:37:17 -08005580 }
5581 }
5582 }
Steve Antoned10bd92017-12-05 10:52:59 -08005583
Steve Anton75737c02017-11-06 10:37:17 -08005584 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5585 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5586 if (sctp_transport_ && local_description() && remote_description() &&
5587 cricket::GetFirstDataContent(local_description()->description()) &&
5588 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005589 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005590 RTC_FROM_HERE,
5591 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005592 if (!success) {
5593 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5594 "Failed to push down SCTP parameters.");
5595 }
Steve Anton75737c02017-11-06 10:37:17 -08005596 }
Steve Antoned10bd92017-12-05 10:52:59 -08005597
Steve Anton8a006912017-12-04 15:25:56 -08005598 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005599}
5600
5601bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5602 RTC_DCHECK(network_thread()->IsCurrent());
5603 RTC_DCHECK(local_description());
5604 RTC_DCHECK(remote_description());
5605 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5606 // When we support "max-message-size", that would also be pushed down here.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005607 return cricket_sctp_transport()->Start(
Steve Anton75737c02017-11-06 10:37:17 -08005608 GetSctpPort(local_description()->description()),
5609 GetSctpPort(remote_description()->description()));
5610}
5611
Steve Anton8a006912017-12-04 15:25:56 -08005612RTCError PeerConnection::PushdownTransportDescription(
5613 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005614 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005615 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005616
Zhi Huange830e682018-03-30 10:48:35 -07005617 if (source == cricket::CS_LOCAL) {
5618 const SessionDescriptionInterface* sdesc = local_description();
5619 RTC_DCHECK(sdesc);
5620 return transport_controller_->SetLocalDescription(type,
5621 sdesc->description());
5622 } else {
5623 const SessionDescriptionInterface* sdesc = remote_description();
5624 RTC_DCHECK(sdesc);
5625 return transport_controller_->SetRemoteDescription(type,
5626 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005627 }
Steve Anton75737c02017-11-06 10:37:17 -08005628}
5629
5630bool PeerConnection::GetTransportDescription(
5631 const SessionDescription* description,
5632 const std::string& content_name,
5633 cricket::TransportDescription* tdesc) {
5634 if (!description || !tdesc) {
5635 return false;
5636 }
5637 const TransportInfo* transport_info =
5638 description->GetTransportInfoByName(content_name);
5639 if (!transport_info) {
5640 return false;
5641 }
5642 *tdesc = transport_info->description;
5643 return true;
5644}
5645
Steve Anton75737c02017-11-06 10:37:17 -08005646cricket::IceConfig PeerConnection::ParseIceConfig(
5647 const PeerConnectionInterface::RTCConfiguration& config) const {
5648 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005649 switch (config.continual_gathering_policy) {
5650 case PeerConnectionInterface::GATHER_ONCE:
5651 gathering_policy = cricket::GATHER_ONCE;
5652 break;
5653 case PeerConnectionInterface::GATHER_CONTINUALLY:
5654 gathering_policy = cricket::GATHER_CONTINUALLY;
5655 break;
5656 default:
5657 RTC_NOTREACHED();
5658 gathering_policy = cricket::GATHER_ONCE;
5659 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005660
Steve Anton75737c02017-11-06 10:37:17 -08005661 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005662 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5663 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005664 ice_config.prioritize_most_likely_candidate_pairs =
5665 config.prioritize_most_likely_ice_candidate_pairs;
5666 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005667 RTCConfigurationToIceConfigOptionalInt(
5668 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005669 ice_config.continual_gathering_policy = gathering_policy;
5670 ice_config.presume_writable_when_fully_relayed =
5671 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005672 ice_config.ice_check_interval_strong_connectivity =
5673 config.ice_check_interval_strong_connectivity;
5674 ice_config.ice_check_interval_weak_connectivity =
5675 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005676 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005677 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5678 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005679 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005680 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005681 ice_config.regather_all_networks_interval_range =
5682 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005683 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005684 return ice_config;
5685}
5686
Steve Antona41959e2018-11-28 11:15:33 -08005687static absl::string_view GetTrackIdBySsrc(
5688 const SessionDescriptionInterface* session_description,
5689 uint32_t ssrc) {
5690 if (!session_description) {
5691 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005692 }
Steve Antona41959e2018-11-28 11:15:33 -08005693 for (const cricket::ContentInfo& content :
5694 session_description->description()->contents()) {
5695 const cricket::MediaContentDescription& media =
5696 *content.media_description();
5697 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5698 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5699 const cricket::StreamParams* stream_params =
5700 cricket::GetStreamBySsrc(media.streams(), ssrc);
5701 if (stream_params) {
5702 return stream_params->id;
5703 }
5704 }
5705 }
5706 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005707}
5708
Steve Antona41959e2018-11-28 11:15:33 -08005709absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5710 return GetTrackIdBySsrc(local_description(), ssrc);
5711}
5712
5713absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5714 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005715}
5716
5717bool PeerConnection::SendData(const cricket::SendDataParams& params,
5718 const rtc::CopyOnWriteBuffer& payload,
5719 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005720 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5721 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5722 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005723 return false;
5724 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005725 if (media_transport_) {
5726 SendDataParams send_params;
5727 send_params.type = ToWebrtcDataMessageType(params.type);
5728 send_params.ordered = params.ordered;
5729 if (params.max_rtx_count >= 0) {
5730 send_params.max_rtx_count = params.max_rtx_count;
5731 } else if (params.max_rtx_ms >= 0) {
5732 send_params.max_rtx_ms = params.max_rtx_ms;
5733 }
5734 return media_transport_->SendData(params.sid, send_params, payload).ok();
5735 }
Steve Anton75737c02017-11-06 10:37:17 -08005736 return rtp_data_channel_
5737 ? rtp_data_channel_->SendData(params, payload, result)
5738 : network_thread()->Invoke<bool>(
5739 RTC_FROM_HERE,
5740 Bind(&cricket::SctpTransportInternal::SendData,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005741 cricket_sctp_transport(), params, payload, result));
Steve Anton75737c02017-11-06 10:37:17 -08005742}
5743
5744bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005745 RTC_DCHECK_RUN_ON(signaling_thread());
5746 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005747 // Don't log an error here, because DataChannels are expected to call
5748 // ConnectDataChannel in this state. It's the only way to initially tell
5749 // whether or not the underlying transport is ready.
5750 return false;
5751 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005752 if (media_transport_) {
5753 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5754 &DataChannel::OnChannelReady);
5755 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5756 &DataChannel::OnDataReceived);
5757 SignalMediaTransportChannelClosing_s.connect(
5758 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5759 SignalMediaTransportChannelClosed_s.connect(
5760 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5761 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005762 rtp_data_channel_->SignalReadyToSendData.connect(
5763 webrtc_data_channel, &DataChannel::OnChannelReady);
5764 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5765 &DataChannel::OnDataReceived);
5766 } else {
5767 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5768 &DataChannel::OnChannelReady);
5769 SignalSctpDataReceived.connect(webrtc_data_channel,
5770 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005771 SignalSctpClosingProcedureStartedRemotely.connect(
5772 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5773 SignalSctpClosingProcedureComplete.connect(
5774 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
5776 return true;
5777}
5778
5779void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005780 RTC_DCHECK_RUN_ON(signaling_thread());
5781 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005782 RTC_LOG(LS_ERROR)
5783 << "DisconnectDataChannel called when rtp_data_channel_ and "
5784 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005785 return;
5786 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005787 if (media_transport_) {
5788 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5789 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5790 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5791 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5792 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005793 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5794 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5795 } else {
5796 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5797 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005798 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5799 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005800 }
5801}
5802
5803void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005804 if (media_transport_) {
Bjorn Mellemf58e43e2019-02-22 10:31:48 -08005805 media_transport_->OpenChannel(sid);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005806 return;
5807 }
Steve Anton75737c02017-11-06 10:37:17 -08005808 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005809 RTC_LOG(LS_ERROR)
5810 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005811 return;
5812 }
5813 network_thread()->Invoke<void>(
5814 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005815 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005816}
5817
5818void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005819 if (media_transport_) {
5820 media_transport_->CloseChannel(sid);
5821 return;
5822 }
Steve Anton75737c02017-11-06 10:37:17 -08005823 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005824 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005825 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005826 return;
5827 }
5828 network_thread()->Invoke<void>(
5829 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01005830 cricket_sctp_transport(), sid));
Steve Anton75737c02017-11-06 10:37:17 -08005831}
5832
5833bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005834 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005835 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005836 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005837 sctp_ready_to_send_data_;
5838}
5839
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005840void PeerConnection::OnDataReceived(int channel_id,
5841 DataMessageType type,
5842 const rtc::CopyOnWriteBuffer& buffer) {
5843 cricket::ReceiveDataParams params;
5844 params.sid = channel_id;
5845 params.type = ToCricketDataMessageType(type);
5846 media_transport_invoker_->AsyncInvoke<void>(
5847 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5848 RTC_DCHECK_RUN_ON(signaling_thread());
5849 if (!HandleOpenMessage_s(params, buffer)) {
5850 SignalMediaTransportReceivedData_s(params, buffer);
5851 }
5852 });
5853}
5854
5855void PeerConnection::OnChannelClosing(int channel_id) {
5856 media_transport_invoker_->AsyncInvoke<void>(
5857 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5858 RTC_DCHECK_RUN_ON(signaling_thread());
5859 SignalMediaTransportChannelClosing_s(channel_id);
5860 });
5861}
5862
5863void PeerConnection::OnChannelClosed(int channel_id) {
5864 media_transport_invoker_->AsyncInvoke<void>(
5865 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5866 RTC_DCHECK_RUN_ON(signaling_thread());
5867 SignalMediaTransportChannelClosed_s(channel_id);
5868 });
5869}
5870
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005871absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005872 if (sctp_mid_ && transport_controller_) {
5873 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5874 if (dtls_transport) {
5875 return dtls_transport->transport_name();
5876 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005877 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005878 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005879 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005880}
5881
Qingsi Wang72a43a12018-02-20 16:03:18 -08005882cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5883 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005884 network_thread()->Invoke<void>(
5885 RTC_FROM_HERE,
5886 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5887 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005888 return candidate_states_list;
5889}
5890
Steve Anton5dfde182018-02-06 10:34:40 -08005891std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5892 const {
Karl Wiberga58e1692019-03-26 13:33:43 +01005893 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton5dfde182018-02-06 10:34:40 -08005894 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005895 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005896 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005897 if (channel) {
5898 transport_names_by_mid[channel->content_name()] =
5899 channel->transport_name();
5900 }
Steve Anton75737c02017-11-06 10:37:17 -08005901 }
Steve Anton5dfde182018-02-06 10:34:40 -08005902 if (rtp_data_channel_) {
5903 transport_names_by_mid[rtp_data_channel_->content_name()] =
5904 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005905 }
5906 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005907 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005908 RTC_DCHECK(transport_name);
5909 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005910 }
Steve Anton5dfde182018-02-06 10:34:40 -08005911 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005912}
5913
Steve Anton5dfde182018-02-06 10:34:40 -08005914std::map<std::string, cricket::TransportStats>
5915PeerConnection::GetTransportStatsByNames(
5916 const std::set<std::string>& transport_names) {
5917 if (!network_thread()->IsCurrent()) {
5918 return network_thread()
5919 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5920 RTC_FROM_HERE,
5921 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005922 }
Steve Anton5dfde182018-02-06 10:34:40 -08005923 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5924 for (const std::string& transport_name : transport_names) {
5925 cricket::TransportStats transport_stats;
5926 bool success =
5927 transport_controller_->GetStats(transport_name, &transport_stats);
5928 if (success) {
5929 transport_stats_by_name[transport_name] = std::move(transport_stats);
5930 } else {
5931 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5932 << transport_name;
5933 }
5934 }
5935 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005936}
5937
5938bool PeerConnection::GetLocalCertificate(
5939 const std::string& transport_name,
5940 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005941 if (!certificate) {
5942 return false;
5943 }
5944 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5945 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005946}
5947
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005948std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005949 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005950 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005951}
5952
5953cricket::DataChannelType PeerConnection::data_channel_type() const {
5954 return data_channel_type_;
5955}
5956
5957bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5958 return pending_ice_restarts_.find(content_name) !=
5959 pending_ice_restarts_.end();
5960}
5961
Steve Anton75737c02017-11-06 10:37:17 -08005962bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5963 return transport_controller_->NeedsIceRestart(content_name);
5964}
5965
5966void PeerConnection::OnCertificateReady(
5967 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5968 transport_controller_->SetLocalCertificate(certificate);
5969}
5970
5971void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005972 SetSessionError(SessionError::kTransport,
5973 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005974}
5975
Alex Loiko9289eda2018-11-23 16:18:59 +00005976void PeerConnection::OnTransportControllerConnectionState(
5977 cricket::IceConnectionState state) {
5978 switch (state) {
5979 case cricket::kIceConnectionConnecting:
5980 // If the current state is Connected or Completed, then there were
5981 // writable channels but now there are not, so the next state must
5982 // be Disconnected.
5983 // kIceConnectionConnecting is currently used as the default,
5984 // un-connected state by the TransportController, so its only use is
5985 // detecting disconnections.
5986 if (ice_connection_state_ ==
5987 PeerConnectionInterface::kIceConnectionConnected ||
5988 ice_connection_state_ ==
5989 PeerConnectionInterface::kIceConnectionCompleted) {
5990 SetIceConnectionState(
5991 PeerConnectionInterface::kIceConnectionDisconnected);
5992 }
5993 break;
5994 case cricket::kIceConnectionFailed:
5995 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5996 break;
5997 case cricket::kIceConnectionConnected:
5998 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5999 "all transports are writable.";
6000 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6001 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6002 break;
6003 case cricket::kIceConnectionCompleted:
6004 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
6005 "all transports are complete.";
6006 if (ice_connection_state_ !=
6007 PeerConnectionInterface::kIceConnectionConnected) {
6008 // If jumping directly from "checking" to "connected",
6009 // signal "connected" first.
6010 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
6011 }
6012 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
6013 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
6014 ReportTransportStats();
6015 break;
6016 default:
6017 RTC_NOTREACHED();
6018 }
6019}
6020
Steve Anton75737c02017-11-06 10:37:17 -08006021void PeerConnection::OnTransportControllerCandidatesGathered(
6022 const std::string& transport_name,
6023 const cricket::Candidates& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006024 int sdp_mline_index;
6025 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006026 RTC_LOG(LS_ERROR)
6027 << "OnTransportControllerCandidatesGathered: content name "
6028 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08006029 return;
6030 }
6031
6032 for (cricket::Candidates::const_iterator citer = candidates.begin();
6033 citer != candidates.end(); ++citer) {
6034 // Use transport_name as the candidate media id.
6035 std::unique_ptr<JsepIceCandidate> candidate(
6036 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
6037 if (local_description()) {
6038 mutable_local_description()->AddCandidate(candidate.get());
6039 }
6040 OnIceCandidate(std::move(candidate));
6041 }
6042}
6043
6044void PeerConnection::OnTransportControllerCandidatesRemoved(
6045 const std::vector<cricket::Candidate>& candidates) {
Steve Anton75737c02017-11-06 10:37:17 -08006046 // Sanity check.
6047 for (const cricket::Candidate& candidate : candidates) {
6048 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006049 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006050 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01006051 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08006052 return;
6053 }
6054 }
6055
6056 if (local_description()) {
6057 mutable_local_description()->RemoveCandidates(candidates);
6058 }
6059 OnIceCandidatesRemoved(candidates);
6060}
6061
6062void PeerConnection::OnTransportControllerDtlsHandshakeError(
6063 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006064 RTC_HISTOGRAM_ENUMERATION(
6065 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
6066 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08006067}
6068
Steve Antoned10bd92017-12-05 10:52:59 -08006069void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01006070 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006071 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08006072 if (channel && !channel->enabled()) {
6073 channel->Enable(true);
6074 }
Steve Anton75737c02017-11-06 10:37:17 -08006075 }
6076
Steve Anton4171afb2017-11-20 10:20:22 -08006077 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08006078 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08006079 }
Steve Anton75737c02017-11-06 10:37:17 -08006080}
6081
6082// Returns the media index for a local ice candidate given the content name.
6083bool PeerConnection::GetLocalCandidateMediaIndex(
6084 const std::string& content_name,
6085 int* sdp_mline_index) {
6086 if (!local_description() || !sdp_mline_index) {
6087 return false;
6088 }
6089
6090 bool content_found = false;
6091 const ContentInfos& contents = local_description()->description()->contents();
6092 for (size_t index = 0; index < contents.size(); ++index) {
6093 if (contents[index].name == content_name) {
6094 *sdp_mline_index = static_cast<int>(index);
6095 content_found = true;
6096 break;
6097 }
6098 }
6099 return content_found;
6100}
6101
6102bool PeerConnection::UseCandidatesInSessionDescription(
6103 const SessionDescriptionInterface* remote_desc) {
6104 if (!remote_desc) {
6105 return true;
6106 }
6107 bool ret = true;
6108
6109 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
6110 const IceCandidateCollection* candidates = remote_desc->candidates(m);
6111 for (size_t n = 0; n < candidates->count(); ++n) {
6112 const IceCandidateInterface* candidate = candidates->at(n);
6113 bool valid = false;
6114 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
6115 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006116 RTC_LOG(LS_INFO)
6117 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01006118 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08006119 }
6120 continue;
6121 }
6122 ret = UseCandidate(candidate);
6123 if (!ret) {
6124 break;
6125 }
6126 }
6127 }
6128 return ret;
6129}
6130
6131bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
6132 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6133 size_t remote_content_size =
6134 remote_description()->description()->contents().size();
6135 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006136 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08006137 return false;
6138 }
6139
6140 cricket::ContentInfo content =
6141 remote_description()->description()->contents()[mediacontent_index];
6142 std::vector<cricket::Candidate> candidates;
6143 candidates.push_back(candidate->candidate());
6144 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07006145 RTCError error =
6146 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00006147 if (error.ok()) {
6148 // Candidates successfully submitted for checking.
6149 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
6150 ice_connection_state_ ==
6151 PeerConnectionInterface::kIceConnectionDisconnected) {
6152 // If state is New, then the session has just gotten its first remote ICE
6153 // candidates, so go to Checking.
6154 // If state is Disconnected, the session is re-using old candidates or
6155 // receiving additional ones, so go to Checking.
6156 // If state is Connected, stay Connected.
6157 // TODO(bemasc): If state is Connected, and the new candidates are for a
6158 // newly added transport, then the state actually _should_ move to
6159 // checking. Add a way to distinguish that case.
6160 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6161 }
6162 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006163 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006164 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006165 }
6166 return true;
6167}
6168
6169void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006170 // Destroy video channel first since it may have a pointer to the
6171 // voice channel.
6172 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006173 if (!video_info || video_info->rejected) {
6174 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006175 }
6176
Steve Anton6fec8802017-12-04 10:37:29 -08006177 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6178 if (!audio_info || audio_info->rejected) {
6179 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006180 }
6181
6182 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6183 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006184 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006185 }
6186}
6187
Steve Antondcc3c022017-12-22 16:02:54 -08006188RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6189 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006190 const cricket::ContentGroup* bundle_group = nullptr;
6191 if (configuration_.bundle_policy ==
6192 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006193 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006194 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006195 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6196 "max-bundle configured but session description "
6197 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006198 }
6199 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006200 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006201}
6202
6203RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006204 // Creating the media channels. Transports should already have been created
6205 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006206 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006207 if (voice && !voice->rejected &&
6208 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006209 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006210 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006211 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6212 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006213 }
6214 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6215 }
6216
Steve Antondcc3c022017-12-22 16:02:54 -08006217 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006218 if (video && !video->rejected &&
6219 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006220 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006221 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006222 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6223 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006224 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006225 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006226 }
6227
Steve Antondcc3c022017-12-22 16:02:54 -08006228 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006229 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006230 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006231 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006232 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6233 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006234 }
6235 }
6236
Steve Anton8a006912017-12-04 15:25:56 -08006237 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006238}
6239
Steve Anton4171afb2017-11-20 10:20:22 -08006240// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006241cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006242 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006243 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006244 MediaTransportInterface* media_transport = nullptr;
6245 if (configuration_.use_media_transport) {
6246 media_transport = GetMediaTransport(mid);
6247 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006248
Steve Anton75737c02017-11-06 10:37:17 -08006249 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006250 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006251 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006252 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006253 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006254 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006255 }
Steve Anton75737c02017-11-06 10:37:17 -08006256 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6257 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006258 voice_channel->SignalSentPacket.connect(this,
6259 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006260 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006261
Steve Antoneda6ccd2017-12-04 10:21:55 -08006262 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006263}
6264
Steve Anton4171afb2017-11-20 10:20:22 -08006265// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006266cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006267 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006268 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006269 MediaTransportInterface* media_transport = nullptr;
6270 if (configuration_.use_media_transport) {
6271 media_transport = GetMediaTransport(mid);
6272 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006273
Steve Anton75737c02017-11-06 10:37:17 -08006274 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006275 call_ptr_, configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006276 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006277 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006278 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006279 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006280 }
Steve Anton75737c02017-11-06 10:37:17 -08006281 video_channel->SignalDtlsSrtpSetupFailure.connect(
6282 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006283 video_channel->SignalSentPacket.connect(this,
6284 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006285 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006286
Steve Antoneda6ccd2017-12-04 10:21:55 -08006287 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006288}
6289
Zhi Huange830e682018-03-30 10:48:35 -07006290bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006291 switch (data_channel_type_) {
6292 case cricket::DCT_MEDIA_TRANSPORT:
6293 if (network_thread()->Invoke<bool>(
6294 RTC_FROM_HERE,
6295 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6296 this, mid))) {
6297 for (const auto& channel : sctp_data_channels_) {
6298 channel->OnTransportChannelCreated();
6299 }
6300 return true;
6301 }
Steve Anton75737c02017-11-06 10:37:17 -08006302 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006303 case cricket::DCT_SCTP:
6304 if (!sctp_factory_) {
6305 RTC_LOG(LS_ERROR)
6306 << "Trying to create SCTP transport, but didn't compile with "
6307 "SCTP support (HAVE_SCTP)";
6308 return false;
6309 }
6310 if (!network_thread()->Invoke<bool>(
6311 RTC_FROM_HERE,
6312 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6313 return false;
6314 }
6315 for (const auto& channel : sctp_data_channels_) {
6316 channel->OnTransportChannelCreated();
6317 }
6318 return true;
6319 case cricket::DCT_RTP:
6320 default:
6321 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6322 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6323 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006324 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006325 if (!rtp_data_channel_) {
6326 return false;
6327 }
6328 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6329 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6330 rtp_data_channel_->SignalSentPacket.connect(
6331 this, &PeerConnection::OnSentPacket_w);
6332 rtp_data_channel_->SetRtpTransport(rtp_transport);
6333 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006334 }
6335
Steve Anton75737c02017-11-06 10:37:17 -08006336 return true;
6337}
6338
6339Call::Stats PeerConnection::GetCallStats() {
6340 if (!worker_thread()->IsCurrent()) {
6341 return worker_thread()->Invoke<Call::Stats>(
6342 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6343 }
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006344 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006345 if (call_) {
6346 return call_->GetStats();
6347 } else {
6348 return Call::Stats();
6349 }
6350}
6351
Zhi Huange830e682018-03-30 10:48:35 -07006352bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006353 RTC_DCHECK(network_thread()->IsCurrent());
6354 RTC_DCHECK(sctp_factory_);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006355 rtc::scoped_refptr<DtlsTransport> webrtc_dtls_transport =
6356 transport_controller_->LookupDtlsTransportByMid(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006357 cricket::DtlsTransportInternal* dtls_transport =
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006358 webrtc_dtls_transport->internal();
Zhi Huang644fde42018-04-02 19:16:26 -07006359 RTC_DCHECK(dtls_transport);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006360 std::unique_ptr<cricket::SctpTransportInternal> cricket_sctp_transport =
6361 sctp_factory_->CreateSctpTransport(dtls_transport);
6362 RTC_DCHECK(cricket_sctp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006363 sctp_invoker_.reset(new rtc::AsyncInvoker());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006364 cricket_sctp_transport->SignalReadyToSendData.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006365 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006366 cricket_sctp_transport->SignalDataReceived.connect(
Steve Anton75737c02017-11-06 10:37:17 -08006367 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006368 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6369 // another thread. Would be nice if there was a helper class similar to
6370 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6371 // code.
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006372 cricket_sctp_transport->SignalClosingProcedureStartedRemotely.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006373 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006374 cricket_sctp_transport->SignalClosingProcedureComplete.connect(
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006375 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006376 sctp_mid_ = mid;
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006377 sctp_transport_ = new rtc::RefCountedObject<SctpTransport>(
6378 std::move(cricket_sctp_transport));
6379 sctp_transport_->SetDtlsTransport(std::move(webrtc_dtls_transport));
Zhi Huange830e682018-03-30 10:48:35 -07006380 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006381}
6382
6383void PeerConnection::DestroySctpTransport_n() {
6384 RTC_DCHECK(network_thread()->IsCurrent());
Harald Alvestrandc85328f2019-02-28 07:51:00 +01006385 sctp_transport_->Clear();
6386 sctp_transport_ = nullptr;
Zhi Huange830e682018-03-30 10:48:35 -07006387 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006388 sctp_invoker_.reset(nullptr);
6389 sctp_ready_to_send_data_ = false;
6390}
6391
6392void PeerConnection::OnSctpTransportReadyToSendData_n() {
6393 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6394 RTC_DCHECK(network_thread()->IsCurrent());
6395 // Note: Cannot use rtc::Bind here because it will grab a reference to
6396 // PeerConnection and potentially cause PeerConnection to live longer than
6397 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6398 // be destroyed before PeerConnection is destroyed, and at that point all
6399 // pending tasks will be cleared.
6400 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6401 OnSctpTransportReadyToSendData_s(true);
6402 });
6403}
6404
6405void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6406 RTC_DCHECK(signaling_thread()->IsCurrent());
6407 sctp_ready_to_send_data_ = ready;
6408 SignalSctpReadyToSendData(ready);
6409}
6410
6411void PeerConnection::OnSctpTransportDataReceived_n(
6412 const cricket::ReceiveDataParams& params,
6413 const rtc::CopyOnWriteBuffer& payload) {
6414 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6415 RTC_DCHECK(network_thread()->IsCurrent());
6416 // Note: Cannot use rtc::Bind here because it will grab a reference to
6417 // PeerConnection and potentially cause PeerConnection to live longer than
6418 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6419 // be destroyed before PeerConnection is destroyed, and at that point all
6420 // pending tasks will be cleared.
6421 sctp_invoker_->AsyncInvoke<void>(
6422 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6423 OnSctpTransportDataReceived_s(params, payload);
6424 });
6425}
6426
6427void PeerConnection::OnSctpTransportDataReceived_s(
6428 const cricket::ReceiveDataParams& params,
6429 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006430 RTC_DCHECK_RUN_ON(signaling_thread());
6431 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006432 SignalSctpDataReceived(params, payload);
6433 }
6434}
6435
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006436void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006437 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6438 RTC_DCHECK(network_thread()->IsCurrent());
6439 sctp_invoker_->AsyncInvoke<void>(
6440 RTC_FROM_HERE, signaling_thread(),
6441 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006442 &SignalSctpClosingProcedureStartedRemotely, sid));
6443}
6444
6445void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6446 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6447 RTC_DCHECK(network_thread()->IsCurrent());
6448 sctp_invoker_->AsyncInvoke<void>(
6449 RTC_FROM_HERE, signaling_thread(),
6450 rtc::Bind(&sigslot::signal1<int>::operator(),
6451 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006452}
6453
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006454bool PeerConnection::SetupMediaTransportForDataChannels_n(
6455 const std::string& mid) {
6456 media_transport_ = transport_controller_->GetMediaTransport(mid);
6457 if (!media_transport_) {
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08006458 RTC_LOG(LS_ERROR)
6459 << "Media transport is not available for data channels, mid=" << mid;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006460 return false;
6461 }
6462
6463 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6464 media_transport_->SetDataSink(this);
6465 media_transport_data_mid_ = mid;
6466 transport_controller_->SignalMediaTransportStateChanged.connect(
6467 this, &PeerConnection::OnMediaTransportStateChanged_n);
6468 // Check the initial state right away, in case transport is already writable.
6469 OnMediaTransportStateChanged_n();
6470 return true;
6471}
6472
6473void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6474 if (!media_transport_) {
6475 return;
6476 }
6477 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6478 media_transport_data_mid_.reset();
6479 media_transport_->SetDataSink(nullptr);
6480 media_transport_invoker_ = nullptr;
6481 media_transport_ = nullptr;
6482}
6483
6484void PeerConnection::OnMediaTransportStateChanged_n() {
6485 if (!media_transport_data_mid_ ||
6486 transport_controller_->GetMediaTransportState(
6487 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6488 return;
6489 }
6490 media_transport_invoker_->AsyncInvoke<void>(
6491 RTC_FROM_HERE, signaling_thread(), [this] {
6492 RTC_DCHECK_RUN_ON(signaling_thread());
6493 media_transport_ready_to_send_data_ = true;
6494 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6495 });
6496}
6497
Steve Anton75737c02017-11-06 10:37:17 -08006498// Returns false if bundle is enabled and rtcp_mux is disabled.
6499bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6500 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6501 if (!bundle_enabled)
6502 return true;
6503
6504 const cricket::ContentGroup* bundle_group =
6505 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6506 RTC_DCHECK(bundle_group != NULL);
6507
6508 const cricket::ContentInfos& contents = desc->contents();
6509 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6510 citer != contents.end(); ++citer) {
6511 const cricket::ContentInfo* content = (&*citer);
6512 RTC_DCHECK(content != NULL);
6513 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006514 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006515 if (!HasRtcpMuxEnabled(content))
6516 return false;
6517 }
6518 }
6519 // RTCP-MUX is enabled in all the contents.
6520 return true;
6521}
6522
6523bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006524 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006525}
6526
Steve Anton06817cd2018-12-18 15:55:30 -08006527static RTCError ValidateMids(const cricket::SessionDescription& description) {
6528 std::set<std::string> mids;
6529 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006530 if (content.name.empty()) {
6531 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6532 "A media section is missing a MID attribute.");
6533 }
Steve Anton06817cd2018-12-18 15:55:30 -08006534 if (!mids.insert(content.name).second) {
6535 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6536 "Duplicate a=mid value '" + content.name + "'.");
6537 }
6538 }
6539 return RTCError::OK();
6540}
6541
Steve Anton8a006912017-12-04 15:25:56 -08006542RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006543 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006544 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006545 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006546 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006547 }
6548
6549 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006550 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006551 }
6552
Steve Anton3828c062017-12-06 10:34:51 -08006553 SdpType type = sdesc->GetType();
6554 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6555 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006556 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006557 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006558 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006559 }
6560
Steve Anton06817cd2018-12-18 15:55:30 -08006561 RTCError error = ValidateMids(*sdesc->description());
6562 if (!error.ok()) {
6563 return error;
6564 }
6565
Steve Anton75737c02017-11-06 10:37:17 -08006566 // Verify crypto settings.
6567 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006568 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6569 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006570 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006571 if (!crypto_error.ok()) {
6572 return crypto_error;
6573 }
Steve Anton75737c02017-11-06 10:37:17 -08006574 }
6575
6576 // Verify ice-ufrag and ice-pwd.
6577 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006578 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6579 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006580 }
6581
6582 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006583 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6584 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006585 }
6586
6587 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6588 // m-lines that do not rtcp-mux enabled.
6589
6590 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006591 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006592 // With an answer we want to compare the new answer session description with
6593 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006594 const cricket::SessionDescription* offer_desc =
6595 (source == cricket::CS_LOCAL) ? remote_description()->description()
6596 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006597 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6598 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6599 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006600 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6601 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006602 }
6603 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006604 // The re-offers should respect the order of m= sections in current
6605 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006606 // With a re-offer, either the current local or current remote descriptions
6607 // could be the most up to date, so we would like to check against both of
6608 // them if they exist. It could be the case that one of them has a 0 port
6609 // for a media section, but the other does not. This is important to check
6610 // against in the case that we are recycling an m= section.
6611 const cricket::SessionDescription* current_desc = nullptr;
6612 const cricket::SessionDescription* secondary_current_desc = nullptr;
6613 if (local_description()) {
6614 current_desc = local_description()->description();
6615 if (remote_description()) {
6616 secondary_current_desc = remote_description()->description();
6617 }
6618 } else if (remote_description()) {
6619 current_desc = remote_description()->description();
6620 }
Steve Anton75737c02017-11-06 10:37:17 -08006621 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006622 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6623 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006624 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6625 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006626 }
6627 }
6628
Steve Antonba42e992018-04-09 14:10:01 -07006629 if (IsUnifiedPlan()) {
6630 // Ensure that each audio and video media section has at most one
6631 // "StreamParams". This will return an error if receiving a session
6632 // description from a "Plan B" endpoint which adds multiple tracks of the
6633 // same type. With Unified Plan, there can only be at most one track per
6634 // media section.
6635 for (const ContentInfo& content : sdesc->description()->contents()) {
6636 const MediaContentDescription& desc = *content.description;
6637 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6638 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6639 desc.streams().size() > 1u) {
6640 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6641 "Media section has more than one track specified "
6642 "with a=ssrc lines which is not supported with "
6643 "Unified Plan.");
6644 }
6645 }
6646 }
6647
Steve Anton8a006912017-12-04 15:25:56 -08006648 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006649}
6650
Steve Anton3828c062017-12-06 10:34:51 -08006651bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006652 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006653 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006654 return (state == PeerConnectionInterface::kStable) ||
6655 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006656 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006657 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006658 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6659 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6660 }
6661}
6662
Steve Anton3828c062017-12-06 10:34:51 -08006663bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006664 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006665 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006666 return (state == PeerConnectionInterface::kStable) ||
6667 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006668 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006669 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006670 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6671 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6672 }
6673}
6674
Steve Antonf8470812017-12-04 10:46:21 -08006675const char* PeerConnection::SessionErrorToString(SessionError error) const {
6676 switch (error) {
6677 case SessionError::kNone:
6678 return "ERROR_NONE";
6679 case SessionError::kContent:
6680 return "ERROR_CONTENT";
6681 case SessionError::kTransport:
6682 return "ERROR_TRANSPORT";
6683 }
6684 RTC_NOTREACHED();
6685 return "";
6686}
6687
Steve Anton75737c02017-11-06 10:37:17 -08006688std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006689 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006690 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6691 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006692 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006693}
6694
Steve Anton8e20f172018-03-06 10:55:04 -08006695void PeerConnection::ReportSdpFormatReceived(
6696 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006697 int num_audio_mlines = 0;
6698 int num_video_mlines = 0;
6699 int num_audio_tracks = 0;
6700 int num_video_tracks = 0;
6701 for (const ContentInfo& content : remote_offer.description()->contents()) {
6702 cricket::MediaType media_type = content.media_description()->type();
6703 int num_tracks = std::max(
6704 1, static_cast<int>(content.media_description()->streams().size()));
6705 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6706 num_audio_mlines += 1;
6707 num_audio_tracks += num_tracks;
6708 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6709 num_video_mlines += 1;
6710 num_video_tracks += num_tracks;
6711 }
6712 }
6713 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6714 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6715 format = kSdpFormatReceivedComplexUnifiedPlan;
6716 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6717 format = kSdpFormatReceivedComplexPlanB;
6718 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6719 format = kSdpFormatReceivedSimple;
6720 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006721 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6722 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006723}
6724
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006725void PeerConnection::NoteUsageEvent(UsageEvent event) {
6726 RTC_DCHECK_RUN_ON(signaling_thread());
6727 usage_event_accumulator_ |= static_cast<int>(event);
6728}
6729
6730void PeerConnection::ReportUsagePattern() const {
6731 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006732 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6733 usage_event_accumulator_,
6734 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006735 const int bad_bits =
6736 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6737 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6738 const int good_bits =
6739 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6740 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6741 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6742 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6743 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006744 // If called after close(), we can't report, because observer may have
6745 // been deallocated, and therefore pointer is null. Write to log instead.
6746 if (observer_) {
6747 Observer()->OnInterestingUsage(usage_event_accumulator_);
6748 } else {
6749 RTC_LOG(LS_INFO) << "Interesting usage signature "
6750 << usage_event_accumulator_
6751 << " observed after observer shutdown";
6752 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006753 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006754}
6755
Steve Anton0ffaaa22018-02-23 10:31:30 -08006756void PeerConnection::ReportNegotiatedSdpSemantics(
6757 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006758 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006759 switch (answer.description()->msid_signaling()) {
6760 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006761 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006762 break;
6763 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006764 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006765 break;
6766 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006767 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006768 break;
6769 case cricket::kMsidSignalingMediaSection |
6770 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006771 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006772 break;
6773 default:
6774 RTC_NOTREACHED();
6775 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006776 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6777 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006778}
6779
Steve Anton75737c02017-11-06 10:37:17 -08006780// We need to check the local/remote description for the Transport instead of
6781// the session, because a new Transport added during renegotiation may have
6782// them unset while the session has them set from the previous negotiation.
6783// Not doing so may trigger the auto generation of transport description and
6784// mess up DTLS identity information, ICE credential, etc.
6785bool PeerConnection::ReadyToUseRemoteCandidate(
6786 const IceCandidateInterface* candidate,
6787 const SessionDescriptionInterface* remote_desc,
6788 bool* valid) {
6789 *valid = true;
6790
6791 const SessionDescriptionInterface* current_remote_desc =
6792 remote_desc ? remote_desc : remote_description();
6793
6794 if (!current_remote_desc) {
6795 return false;
6796 }
6797
6798 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6799 size_t remote_content_size =
6800 current_remote_desc->description()->contents().size();
6801 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006802 RTC_LOG(LS_ERROR)
6803 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6804 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006805
6806 *valid = false;
6807 return false;
6808 }
6809
6810 cricket::ContentInfo content =
6811 current_remote_desc->description()->contents()[mediacontent_index];
6812
6813 const std::string transport_name = GetTransportName(content.name);
6814 if (transport_name.empty()) {
6815 return false;
6816 }
Zhi Huange830e682018-03-30 10:48:35 -07006817 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006818}
6819
6820bool PeerConnection::SrtpRequired() const {
6821 return dtls_enabled_ ||
6822 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6823}
6824
6825void PeerConnection::OnTransportControllerGatheringState(
6826 cricket::IceGatheringState state) {
6827 RTC_DCHECK(signaling_thread()->IsCurrent());
6828 if (state == cricket::kIceGatheringGathering) {
6829 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6830 } else if (state == cricket::kIceGatheringComplete) {
6831 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6832 }
6833}
6834
6835void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006836 std::map<std::string, std::set<cricket::MediaType>>
6837 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006838 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006839 if (transceiver->internal()->channel()) {
6840 const std::string& transport_name =
6841 transceiver->internal()->channel()->transport_name();
6842 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006843 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006844 }
Steve Anton75737c02017-11-06 10:37:17 -08006845 }
6846 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006847 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6848 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006849 }
Zhi Huange830e682018-03-30 10:48:35 -07006850
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006851 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006852 if (transport_name) {
6853 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006854 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006855 }
Zhi Huange830e682018-03-30 10:48:35 -07006856
Steve Antonc7b964c2018-02-01 14:39:45 -08006857 for (const auto& entry : media_types_by_transport_name) {
6858 const std::string& transport_name = entry.first;
6859 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006860 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006861 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006862 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006863 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006864 }
6865 }
6866}
6867// Walk through the ConnectionInfos to gather best connection usage
6868// for IPv4 and IPv6.
6869void PeerConnection::ReportBestConnectionState(
6870 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006871 for (const cricket::TransportChannelStats& channel_stats :
6872 stats.channel_stats) {
6873 for (const cricket::ConnectionInfo& connection_info :
6874 channel_stats.connection_infos) {
6875 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006876 continue;
6877 }
6878
Steve Antonc7b964c2018-02-01 14:39:45 -08006879 const cricket::Candidate& local = connection_info.local_candidate;
6880 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006881
6882 // Increment the counter for IceCandidatePairType.
6883 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6884 (local.type() == RELAY_PORT_TYPE &&
6885 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006886 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6887 GetIceCandidatePairCounter(local, remote),
6888 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006889 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006890 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6891 GetIceCandidatePairCounter(local, remote),
6892 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006893 } else {
6894 RTC_CHECK(0);
6895 }
Steve Anton75737c02017-11-06 10:37:17 -08006896
6897 // Increment the counter for IP type.
6898 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006899 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6900 kBestConnections_IPv4,
6901 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006902 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006903 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6904 kBestConnections_IPv6,
6905 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006906 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006907 RTC_CHECK(!local.address().hostname().empty() &&
6908 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006909 }
6910
6911 return;
6912 }
6913 }
6914}
6915
6916void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006917 const cricket::TransportStats& stats,
6918 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006919 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6920 return;
6921 }
6922
6923 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6924 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6925 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6926 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6927 return;
6928 }
6929
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006930 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6931 for (cricket::MediaType media_type : media_types) {
6932 switch (media_type) {
6933 case cricket::MEDIA_TYPE_AUDIO:
6934 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6935 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6936 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6937 break;
6938 case cricket::MEDIA_TYPE_VIDEO:
6939 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6940 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6941 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6942 break;
6943 case cricket::MEDIA_TYPE_DATA:
6944 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6945 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6946 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6947 break;
6948 default:
6949 RTC_NOTREACHED();
6950 continue;
6951 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006952 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006953 }
6954
6955 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6956 for (cricket::MediaType media_type : media_types) {
6957 switch (media_type) {
6958 case cricket::MEDIA_TYPE_AUDIO:
6959 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6960 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6961 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6962 break;
6963 case cricket::MEDIA_TYPE_VIDEO:
6964 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6965 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6966 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6967 break;
6968 case cricket::MEDIA_TYPE_DATA:
6969 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6970 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6971 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6972 break;
6973 default:
6974 RTC_NOTREACHED();
6975 continue;
6976 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006977 }
Steve Anton75737c02017-11-06 10:37:17 -08006978 }
6979}
6980
6981void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01006982 RTC_DCHECK_RUN_ON(worker_thread());
Steve Anton75737c02017-11-06 10:37:17 -08006983 RTC_DCHECK(call_);
6984 call_->OnSentPacket(sent_packet);
6985}
6986
6987const std::string PeerConnection::GetTransportName(
6988 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006989 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006990 if (channel) {
6991 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006992 }
Steve Anton6fec8802017-12-04 10:37:29 -08006993 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006994 RTC_DCHECK(sctp_mid_);
6995 if (content_name == *sctp_mid_) {
6996 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006997 }
6998 }
6999 // Return an empty string if failed to retrieve the transport name.
7000 return "";
Steve Anton75737c02017-11-06 10:37:17 -08007001}
7002
Steve Anton6fec8802017-12-04 10:37:29 -08007003void PeerConnection::DestroyTransceiverChannel(
7004 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
7005 transceiver) {
7006 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08007007
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007008 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08007009 if (channel) {
7010 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007011 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08007012 }
7013}
7014
7015void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08007016 if (rtp_data_channel_) {
7017 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007018 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08007019 rtp_data_channel_ = nullptr;
7020 }
7021
7022 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
7023 // grab a reference to this PeerConnection. If this is called from the
7024 // PeerConnection destructor, the RefCountedObject vtable will have already
7025 // been destroyed (since it is a subclass of PeerConnection) and using
7026 // rtc::Bind will cause "Pure virtual function called" error to appear.
7027
7028 if (sctp_transport_) {
7029 OnDataChannelDestroyed();
7030 network_thread()->Invoke<void>(RTC_FROM_HERE,
7031 [this] { DestroySctpTransport_n(); });
7032 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08007033
7034 if (media_transport_) {
7035 OnDataChannelDestroyed();
7036 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
7037 RTC_DCHECK_RUN_ON(network_thread());
7038 TeardownMediaTransportForDataChannels_n();
7039 });
7040 }
Steve Anton6fec8802017-12-04 10:37:29 -08007041}
7042
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08007043void PeerConnection::DestroyChannelInterface(
7044 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08007045 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08007046 switch (channel->media_type()) {
7047 case cricket::MEDIA_TYPE_AUDIO:
7048 channel_manager()->DestroyVoiceChannel(
7049 static_cast<cricket::VoiceChannel*>(channel));
7050 break;
7051 case cricket::MEDIA_TYPE_VIDEO:
7052 channel_manager()->DestroyVideoChannel(
7053 static_cast<cricket::VideoChannel*>(channel));
7054 break;
7055 case cricket::MEDIA_TYPE_DATA:
7056 channel_manager()->DestroyRtpDataChannel(
7057 static_cast<cricket::RtpDataChannel*>(channel));
7058 break;
7059 default:
7060 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
7061 break;
7062 }
Zhi Huange830e682018-03-30 10:48:35 -07007063}
Steve Anton6fec8802017-12-04 10:37:29 -08007064
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007065bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07007066 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007067 RtpTransportInternal* rtp_transport,
Harald Alvestrandc85328f2019-02-28 07:51:00 +01007068 rtc::scoped_refptr<DtlsTransport> dtls_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007069 MediaTransportInterface* media_transport) {
Karl Wibergac025892019-03-26 13:08:37 +01007070 RTC_DCHECK_RUN_ON(network_thread());
Karl Wiberg5966c502019-02-21 23:55:09 +01007071 RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007072 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07007073 auto base_channel = GetChannel(mid);
7074 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007075 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07007076 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007077 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07007078 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08007079 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007080
Karl Wiberg5966c502019-02-21 23:55:09 +01007081 if (use_media_transport_) {
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007082 // Only pass media transport to call object if media transport is used
7083 // for media (and not data channel).
Karl Wibergac025892019-03-26 13:08:37 +01007084 call_ptr_->MediaTransportChange(media_transport);
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08007085 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08007086
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07007087 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08007088}
7089
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007090PeerConnectionObserver* PeerConnection::Observer() const {
7091 // In earlier production code, the pointer was not cleared on close,
7092 // which might have led to undefined behavior if the observer was not
7093 // deallocated, or strange crashes if it was.
7094 // We use CHECK in order to catch such behavior if it exists.
7095 // TODO(hta): Remove or replace with DCHECK if nothing is found.
7096 RTC_CHECK(observer_);
7097 return observer_;
7098}
7099
Benjamin Wright8c27cca2018-10-25 10:16:44 -07007100CryptoOptions PeerConnection::GetCryptoOptions() {
7101 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
7102 // after it has been removed.
7103 return configuration_.crypto_options.has_value()
7104 ? *configuration_.crypto_options
7105 : factory_->options().crypto_options;
7106}
7107
Harald Alvestrand89061872018-01-02 14:08:34 +01007108void PeerConnection::ClearStatsCache() {
Karl Wiberg6cab5c82019-03-26 09:57:01 +01007109 RTC_DCHECK_RUN_ON(signaling_thread());
Harald Alvestrand89061872018-01-02 14:08:34 +01007110 if (stats_collector_) {
7111 stats_collector_->ClearCachedStatsReport();
7112 }
7113}
7114
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007115void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00007116 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
7117 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02007118}
7119
henrike@webrtc.org28e20752013-07-10 00:45:36 +00007120} // namespace webrtc