blob: 10901496f0f3be4c9337946293f6bb297a6878ff [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"
33#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080034#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "pc/channel_manager.h"
36#include "pc/dtmf_sender.h"
37#include "pc/media_stream.h"
38#include "pc/media_stream_observer.h"
39#include "pc/remote_audio_source.h"
40#include "pc/rtp_media_utils.h"
41#include "pc/rtp_receiver.h"
42#include "pc/rtp_sender.h"
43#include "pc/sctp_utils.h"
44#include "pc/sdp_utils.h"
45#include "pc/stream_collection.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "pc/video_capturer_track_source.h"
47#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/bind.h"
49#include "rtc_base/checks.h"
50#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010051#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080052#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020053#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/trace_event.h"
55#include "system_wrappers/include/clock.h"
56#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070057#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
Steve Anton75737c02017-11-06 10:37:17 -080059using cricket::ContentInfo;
60using cricket::ContentInfos;
61using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080063using cricket::RidDescription;
64using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080065using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080066using cricket::SimulcastDescription;
67using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080068using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080070using cricket::TransportInfo;
71
72using cricket::LOCAL_PORT_TYPE;
73using cricket::STUN_PORT_TYPE;
74using cricket::RELAY_PORT_TYPE;
75using cricket::PRFLX_PORT_TYPE;
76
Steve Antonba818672017-11-06 10:21:57 -080077namespace webrtc {
78
Steve Anton75737c02017-11-06 10:37:17 -080079// Error messages
80const char kBundleWithoutRtcpMux[] =
81 "rtcp-mux must be enabled when BUNDLE "
82 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080083const char kInvalidCandidates[] = "Description contains invalid candidates.";
84const char kInvalidSdp[] = "Invalid session description.";
85const char kMlineMismatchInAnswer[] =
86 "The order of m-lines in answer doesn't match order in offer. Rejecting "
87 "answer.";
88const char kMlineMismatchInSubsequentOffer[] =
89 "The order of m-lines in subsequent offer doesn't match order from "
90 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080091const char kSdpWithoutDtlsFingerprint[] =
92 "Called with SDP without DTLS fingerprint.";
93const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
94const char kSdpWithoutIceUfragPwd[] =
95 "Called with SDP without ice-ufrag and ice-pwd.";
96const char kSessionError[] = "Session error code: ";
97const char kSessionErrorDesc[] = "Session error description: ";
98const char kDtlsSrtpSetupFailureRtp[] =
99 "Couldn't set up DTLS-SRTP on RTP channel.";
100const char kDtlsSrtpSetupFailureRtcp[] =
101 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102
Steve Anton75737c02017-11-06 10:37:17 -0800103namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104
Seth Hampson845e8782018-03-02 11:34:10 -0800105static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800106static const char kDefaultAudioSenderId[] = "defaulta0";
107static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700108
zhihuang8f65cdf2016-05-06 18:40:30 -0700109// The length of RTCP CNAMEs.
110static const int kRtcpCnameLength = 16;
111
Steve Antonad182762018-09-05 20:22:40 +0000112enum {
113 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
114 MSG_SET_SESSIONDESCRIPTION_FAILED,
115 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
116 MSG_GETSTATS,
117 MSG_FREE_DATACHANNELS,
118 MSG_REPORT_USAGE_PATTERN,
119};
120
Harald Alvestrand19793842018-06-25 12:03:50 +0200121static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
122
Steve Antonad182762018-09-05 20:22:40 +0000123struct SetSessionDescriptionMsg : public rtc::MessageData {
124 explicit SetSessionDescriptionMsg(
125 webrtc::SetSessionDescriptionObserver* observer)
126 : observer(observer) {}
127
128 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
129 RTCError error;
130};
131
132struct CreateSessionDescriptionMsg : public rtc::MessageData {
133 explicit CreateSessionDescriptionMsg(
134 webrtc::CreateSessionDescriptionObserver* observer)
135 : observer(observer) {}
136
137 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
138 RTCError error;
139};
140
141struct GetStatsMsg : public rtc::MessageData {
142 GetStatsMsg(webrtc::StatsObserver* observer,
143 webrtc::MediaStreamTrackInterface* track)
144 : observer(observer), track(track) {}
145 rtc::scoped_refptr<webrtc::StatsObserver> observer;
146 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
147};
148
deadbeefab9b2d12015-10-14 11:33:11 -0700149// Check if we can send |new_stream| on a PeerConnection.
150bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
151 webrtc::MediaStreamInterface* new_stream) {
152 if (!new_stream || !current_streams) {
153 return false;
154 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700155 if (current_streams->find(new_stream->id()) != nullptr) {
156 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100157 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700158 return false;
159 }
160 return true;
161}
162
deadbeef5e97fb52015-10-15 12:49:08 -0700163// If the direction is "recvonly" or "inactive", treat the description
164// as containing no streams.
165// See: https://code.google.com/p/webrtc/issues/detail?id=5054
166std::vector<cricket::StreamParams> GetActiveStreams(
167 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800168 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700169 ? desc->streams()
170 : std::vector<cricket::StreamParams>();
171}
172
deadbeefab9b2d12015-10-14 11:33:11 -0700173bool IsValidOfferToReceiveMedia(int value) {
174 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
175 return (value >= Options::kUndefined) &&
176 (value <= Options::kMaxOfferToReceiveMedia);
177}
178
zhihuang1c378ed2017-08-17 14:10:50 -0700179// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800180void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700181 const std::vector<rtc::scoped_refptr<
182 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700183 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200184 cricket::MediaDescriptionOptions* video_media_description_options,
185 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700186 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700187 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
188 if (audio_media_description_options) {
189 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700190 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 } else {
193 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
194 if (video_media_description_options) {
195 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800196 sender->id(), sender->internal()->stream_ids(), {},
197 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700198 }
199 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700200 }
zhihuang1c378ed2017-08-17 14:10:50 -0700201}
olka3c747662017-08-17 06:50:32 -0700202
zhihuang1c378ed2017-08-17 14:10:50 -0700203// Add options to |session_options| from |rtp_data_channels|.
204void AddRtpDataChannelOptions(
205 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
206 rtp_data_channels,
207 cricket::MediaDescriptionOptions* data_media_description_options) {
208 if (!data_media_description_options) {
209 return;
210 }
deadbeefab9b2d12015-10-14 11:33:11 -0700211 // Check for data channels.
212 for (const auto& kv : rtp_data_channels) {
213 const DataChannel* channel = kv.second;
214 if (channel->state() == DataChannel::kConnecting ||
215 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700216 // Legacy RTP data channels are signaled with the track/stream ID set to
217 // the data channel's label.
218 data_media_description_options->AddRtpDataChannel(channel->label(),
219 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700220 }
221 }
222}
223
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700224uint32_t ConvertIceTransportTypeToCandidateFilter(
225 PeerConnectionInterface::IceTransportsType type) {
226 switch (type) {
227 case PeerConnectionInterface::kNone:
228 return cricket::CF_NONE;
229 case PeerConnectionInterface::kRelay:
230 return cricket::CF_RELAY;
231 case PeerConnectionInterface::kNoHost:
232 return (cricket::CF_ALL & ~cricket::CF_HOST);
233 case PeerConnectionInterface::kAll:
234 return cricket::CF_ALL;
235 default:
nissec80e7412017-01-11 05:56:46 -0800236 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700237 }
238 return cricket::CF_NONE;
239}
240
deadbeef293e9262017-01-11 12:28:30 -0800241// Helper to set an error and return from a method.
242bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
243 if (error) {
244 error->set_type(type);
245 }
246 return type == webrtc::RTCErrorType::NONE;
247}
248
Steve Anton038834f2017-07-14 15:59:59 -0700249bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700250 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700251 if (error_out) {
252 *error_out = std::move(error);
253 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700254 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700255}
256
Steve Antonba818672017-11-06 10:21:57 -0800257std::string GetSignalingStateString(
258 PeerConnectionInterface::SignalingState state) {
259 switch (state) {
260 case PeerConnectionInterface::kStable:
261 return "kStable";
262 case PeerConnectionInterface::kHaveLocalOffer:
263 return "kHaveLocalOffer";
264 case PeerConnectionInterface::kHaveLocalPrAnswer:
265 return "kHavePrAnswer";
266 case PeerConnectionInterface::kHaveRemoteOffer:
267 return "kHaveRemoteOffer";
268 case PeerConnectionInterface::kHaveRemotePrAnswer:
269 return "kHaveRemotePrAnswer";
270 case PeerConnectionInterface::kClosed:
271 return "kClosed";
272 }
273 RTC_NOTREACHED();
274 return "";
275}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700276
Steve Anton75737c02017-11-06 10:37:17 -0800277IceCandidatePairType GetIceCandidatePairCounter(
278 const cricket::Candidate& local,
279 const cricket::Candidate& remote) {
280 const auto& l = local.type();
281 const auto& r = remote.type();
282 const auto& host = LOCAL_PORT_TYPE;
283 const auto& srflx = STUN_PORT_TYPE;
284 const auto& relay = RELAY_PORT_TYPE;
285 const auto& prflx = PRFLX_PORT_TYPE;
286 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800287 bool local_hostname =
288 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
289 bool remote_hostname = !remote.address().hostname().empty() &&
290 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800291 bool local_private = IPIsPrivate(local.address().ipaddr());
292 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800293 if (local_hostname) {
294 if (remote_hostname) {
295 return kIceCandidatePairHostNameHostName;
296 } else if (remote_private) {
297 return kIceCandidatePairHostNameHostPrivate;
298 } else {
299 return kIceCandidatePairHostNameHostPublic;
300 }
301 } else if (local_private) {
302 if (remote_hostname) {
303 return kIceCandidatePairHostPrivateHostName;
304 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800305 return kIceCandidatePairHostPrivateHostPrivate;
306 } else {
307 return kIceCandidatePairHostPrivateHostPublic;
308 }
309 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800310 if (remote_hostname) {
311 return kIceCandidatePairHostPublicHostName;
312 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800313 return kIceCandidatePairHostPublicHostPrivate;
314 } else {
315 return kIceCandidatePairHostPublicHostPublic;
316 }
317 }
318 }
319 if (l == host && r == srflx)
320 return kIceCandidatePairHostSrflx;
321 if (l == host && r == relay)
322 return kIceCandidatePairHostRelay;
323 if (l == host && r == prflx)
324 return kIceCandidatePairHostPrflx;
325 if (l == srflx && r == host)
326 return kIceCandidatePairSrflxHost;
327 if (l == srflx && r == srflx)
328 return kIceCandidatePairSrflxSrflx;
329 if (l == srflx && r == relay)
330 return kIceCandidatePairSrflxRelay;
331 if (l == srflx && r == prflx)
332 return kIceCandidatePairSrflxPrflx;
333 if (l == relay && r == host)
334 return kIceCandidatePairRelayHost;
335 if (l == relay && r == srflx)
336 return kIceCandidatePairRelaySrflx;
337 if (l == relay && r == relay)
338 return kIceCandidatePairRelayRelay;
339 if (l == relay && r == prflx)
340 return kIceCandidatePairRelayPrflx;
341 if (l == prflx && r == host)
342 return kIceCandidatePairPrflxHost;
343 if (l == prflx && r == srflx)
344 return kIceCandidatePairPrflxSrflx;
345 if (l == prflx && r == relay)
346 return kIceCandidatePairPrflxRelay;
347 return kIceCandidatePairMax;
348}
349
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800350// Logic to decide if an m= section can be recycled. This means that the new
351// m= section is not rejected, but the old local or remote m= section is
352// rejected. |old_content_one| and |old_content_two| refer to the m= section
353// of the old remote and old local descriptions in no particular order.
354// We need to check both the old local and remote because either
355// could be the most current from the latest negotation.
356bool IsMediaSectionBeingRecycled(SdpType type,
357 const ContentInfo& content,
358 const ContentInfo* old_content_one,
359 const ContentInfo* old_content_two) {
360 return type == SdpType::kOffer && !content.rejected &&
361 ((old_content_one && old_content_one->rejected) ||
362 (old_content_two && old_content_two->rejected));
363}
364
Steve Anton75737c02017-11-06 10:37:17 -0800365// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366// |current_desc|. The number of m= sections in |new_desc| should be no
367// less than |current_desc|. In the case of checking an answer's
368// |new_desc|, the |current_desc| is the last offer that was set as the
369// local or remote. In the case of checking an offer's |new_desc| we
370// check against the local and remote descriptions stored from the last
371// negotiation, because either of these could be the most up to date for
372// possible rejected m sections. These are the |current_desc| and
373// |secondary_current_desc|.
374bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
375 const SessionDescription* secondary_current_desc,
376 const SessionDescription& new_desc,
377 const SdpType type) {
378 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800379 return false;
380 }
381
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800382 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
383 const cricket::ContentInfo* secondary_content_info = nullptr;
384 if (secondary_current_desc &&
385 i < secondary_current_desc->contents().size()) {
386 secondary_content_info = &secondary_current_desc->contents()[i];
387 }
388 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
389 &current_desc.contents()[i],
390 secondary_content_info)) {
391 // For new offer descriptions, if the media section can be recycled, it's
392 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800393 continue;
394 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800395 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800396 return false;
397 }
398 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800399 new_desc.contents()[i].media_description();
400 const MediaContentDescription* current_desc_mdesc =
401 current_desc.contents()[i].media_description();
402 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800403 return false;
404 }
405 }
406 return true;
407}
408
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800409bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
410 const SessionDescription& desc2) {
411 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800412}
413
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700414void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
415 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200416 // Array of structs needed to map {KeyExchangeProtocolType,
417 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
418 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
419 static constexpr struct {
420 KeyExchangeProtocolType protocol_type;
421 cricket::MediaType media_type;
422 KeyExchangeProtocolMedia protocol_media;
423 } kEnumCounterKeyProtocolMediaMap[] = {
424 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
425 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
426 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
427 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
428 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
429 kEnumCounterKeyProtocolMediaTypeDtlsData},
430 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
431 kEnumCounterKeyProtocolMediaTypeSdesAudio},
432 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
433 kEnumCounterKeyProtocolMediaTypeSdesVideo},
434 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
435 kEnumCounterKeyProtocolMediaTypeSdesData},
436 };
437
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
439 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100440
Mirko Bonadeiab499822018-09-11 10:43:20 +0200441 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
442 if (i.protocol_type == protocol_type && i.media_type == media_type) {
443 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
444 i.protocol_media,
445 kEnumCounterKeyProtocolMediaTypeMax);
446 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100447 }
448}
449
Harald Alvestrand76829d72018-07-18 23:24:36 +0200450void NoteAddIceCandidateResult(int result) {
451 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
452 kAddIceCandidateMax);
453}
454
Steve Anton75737c02017-11-06 10:37:17 -0800455// Checks that each non-rejected content has SDES crypto keys or a DTLS
456// fingerprint, unless it's in a BUNDLE group, in which case only the
457// BUNDLE-tag section (first media section/description in the BUNDLE group)
458// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
459// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
460// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700461RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800462 const cricket::ContentGroup* bundle =
463 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800464 for (const cricket::ContentInfo& content_info : desc->contents()) {
465 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800466 continue;
467 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100468 // Note what media is used with each crypto protocol, for all sections.
469 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
470 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700471 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800472 const std::string& mid = content_info.name;
473 if (bundle && bundle->HasContentName(mid) &&
474 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800475 // This isn't the first media section in the BUNDLE group, so it's not
476 // required to have crypto attributes, since only the crypto attributes
477 // from the first section actually get used.
478 continue;
479 }
480
481 // If the content isn't rejected or bundled into another m= section, crypto
482 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800483 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800484 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800485 if (!media || !tinfo) {
486 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800487 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800488 }
489 if (dtls_enabled) {
490 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100491 RTC_LOG(LS_WARNING)
492 << "Session description must have DTLS fingerprint if "
493 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800494 return RTCError(RTCErrorType::INVALID_PARAMETER,
495 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800496 }
497 } else {
498 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100499 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800500 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800501 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 }
504 }
Steve Anton8a006912017-12-04 15:25:56 -0800505 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800506}
507
508// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
509// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
510// media section/description in the BUNDLE group) needs a ufrag and pwd.
511bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
512 const cricket::ContentGroup* bundle =
513 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800514 for (const cricket::ContentInfo& content_info : desc->contents()) {
515 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800516 continue;
517 }
Steve Anton8a006912017-12-04 15:25:56 -0800518 const std::string& mid = content_info.name;
519 if (bundle && bundle->HasContentName(mid) &&
520 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800521 // This isn't the first media section in the BUNDLE group, so it's not
522 // required to have ufrag/password, since only the ufrag/password from
523 // the first section actually get used.
524 continue;
525 }
526
527 // If the content isn't rejected or bundled into another m= section,
528 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800529 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (!tinfo) {
531 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100532 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800533 return false;
534 }
535 if (tinfo->description.ice_ufrag.empty() ||
536 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100537 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800538 return false;
539 }
540 }
541 return true;
542}
543
Steve Anton75737c02017-11-06 10:37:17 -0800544// Get the SCTP port out of a SessionDescription.
545// Return -1 if not found.
546int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800547 const cricket::DataContentDescription* data_desc =
548 GetFirstDataContentDescription(session_description);
549 RTC_DCHECK(data_desc);
550 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800551 return -1;
552 }
Steve Anton75737c02017-11-06 10:37:17 -0800553 std::string value;
554 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
555 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800556 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800557 if (!codec.Matches(match_pattern)) {
558 continue;
559 }
560 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
561 return rtc::FromString<int>(value);
562 }
563 }
564 return -1;
565}
566
Steve Anton75737c02017-11-06 10:37:17 -0800567// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
568bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
569 const SessionDescriptionInterface* new_desc,
570 const std::string& content_name) {
571 if (!old_desc) {
572 return false;
573 }
574 const SessionDescription* new_sd = new_desc->description();
575 const SessionDescription* old_sd = old_desc->description();
576 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
577 if (!cinfo || cinfo->rejected) {
578 return false;
579 }
580 // If the content isn't rejected, check if ufrag and password has changed.
581 const cricket::TransportDescription* new_transport_desc =
582 new_sd->GetTransportDescriptionByName(content_name);
583 const cricket::TransportDescription* old_transport_desc =
584 old_sd->GetTransportDescriptionByName(content_name);
585 if (!new_transport_desc || !old_transport_desc) {
586 // No transport description exists. This is not an ICE restart.
587 return false;
588 }
589 if (cricket::IceCredentialsChanged(
590 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
591 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100592 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
593 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800594 return true;
595 }
596 return false;
597}
598
Steve Anton80dd7b52018-02-16 17:08:42 -0800599// Generates a string error message for SetLocalDescription/SetRemoteDescription
600// from an RTCError.
601std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
602 SdpType type,
603 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200604 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800605 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
606 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200607 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800608}
609
Seth Hampson5b4f0752018-04-02 16:31:36 -0700610std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
611 std::string output = "streams=[";
612 const char* separator = "";
613 for (const auto& stream_id : stream_ids) {
614 output.append(separator).append(stream_id);
615 separator = ", ";
616 }
617 output.append("]");
618 return output;
619}
620
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200621absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700622 int rtc_configuration_parameter) {
623 if (rtc_configuration_parameter ==
624 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 }
627 return rtc_configuration_parameter;
628}
629
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800630cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
631 switch (type) {
632 case DataMessageType::kText:
633 return cricket::DMT_TEXT;
634 case DataMessageType::kBinary:
635 return cricket::DMT_BINARY;
636 case DataMessageType::kControl:
637 return cricket::DMT_CONTROL;
638 default:
639 return cricket::DMT_NONE;
640 }
641 return cricket::DMT_NONE;
642}
643
644DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
645 switch (type) {
646 case cricket::DMT_TEXT:
647 return DataMessageType::kText;
648 case cricket::DMT_BINARY:
649 return DataMessageType::kBinary;
650 case cricket::DMT_CONTROL:
651 return DataMessageType::kControl;
652 case cricket::DMT_NONE:
653 default:
654 RTC_NOTREACHED();
655 }
656 return DataMessageType::kControl;
657}
658
Steve Anton75737c02017-11-06 10:37:17 -0800659} // namespace
660
Henrik Boström31638672017-11-23 17:48:32 +0100661// Upon completion, posts a task to execute the callback of the
662// SetSessionDescriptionObserver asynchronously on the same thread. At this
663// point, the state of the peer connection might no longer reflect the effects
664// of the SetRemoteDescription operation, as the peer connection could have been
665// modified during the post.
666// TODO(hbos): Remove this class once we remove the version of
667// PeerConnectionInterface::SetRemoteDescription() that takes a
668// SetSessionDescriptionObserver as an argument.
669class PeerConnection::SetRemoteDescriptionObserverAdapter
670 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
671 public:
672 SetRemoteDescriptionObserverAdapter(
673 rtc::scoped_refptr<PeerConnection> pc,
674 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
675 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
676
677 // SetRemoteDescriptionObserverInterface implementation.
678 void OnSetRemoteDescriptionComplete(RTCError error) override {
679 if (error.ok())
680 pc_->PostSetSessionDescriptionSuccess(wrapper_);
681 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100682 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100683 }
684
685 private:
686 rtc::scoped_refptr<PeerConnection> pc_;
687 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
688};
689
deadbeef293e9262017-01-11 12:28:30 -0800690bool PeerConnectionInterface::RTCConfiguration::operator==(
691 const PeerConnectionInterface::RTCConfiguration& o) const {
692 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700693 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800694 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000695 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700696 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800697 BundlePolicy bundle_policy;
698 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700699 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
700 int ice_candidate_pool_size;
701 bool disable_ipv6;
702 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700703 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100704 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700705 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200706 absl::optional<int> screencast_min_bitrate;
707 absl::optional<bool> combined_audio_video_bwe;
708 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800709 TcpCandidatePolicy tcp_candidate_policy;
710 CandidateNetworkPolicy candidate_network_policy;
711 int audio_jitter_buffer_max_packets;
712 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100713 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100714 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800715 int ice_connection_receiving_timeout;
716 int ice_backup_candidate_pair_ping_interval;
717 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800718 bool prioritize_most_likely_ice_candidate_pairs;
719 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800720 bool prune_turn_ports;
721 bool presume_writable_when_fully_relayed;
722 bool enable_ice_renomination;
723 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200724 absl::optional<int> ice_check_interval_strong_connectivity;
725 absl::optional<int> ice_check_interval_weak_connectivity;
726 absl::optional<int> ice_check_min_interval;
727 absl::optional<int> ice_unwritable_timeout;
728 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800729 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200730 absl::optional<int> stun_candidate_keepalive_interval;
731 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200732 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800733 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200734 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700735 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700736 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700737 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700738 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100739 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800740 };
741 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
742 "Did you add something to RTCConfiguration and forget to "
743 "update operator==?");
744 return type == o.type && servers == o.servers &&
745 bundle_policy == o.bundle_policy &&
746 rtcp_mux_policy == o.rtcp_mux_policy &&
747 tcp_candidate_policy == o.tcp_candidate_policy &&
748 candidate_network_policy == o.candidate_network_policy &&
749 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
750 audio_jitter_buffer_fast_accelerate ==
751 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100752 audio_jitter_buffer_min_delay_ms ==
753 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100754 audio_jitter_buffer_enable_rtx_handling ==
755 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800756 ice_connection_receiving_timeout ==
757 o.ice_connection_receiving_timeout &&
758 ice_backup_candidate_pair_ping_interval ==
759 o.ice_backup_candidate_pair_ping_interval &&
760 continual_gathering_policy == o.continual_gathering_policy &&
761 certificates == o.certificates &&
762 prioritize_most_likely_ice_candidate_pairs ==
763 o.prioritize_most_likely_ice_candidate_pairs &&
764 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800765 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700766 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100767 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800768 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800769 screencast_min_bitrate == o.screencast_min_bitrate &&
770 combined_audio_video_bwe == o.combined_audio_video_bwe &&
771 enable_dtls_srtp == o.enable_dtls_srtp &&
772 ice_candidate_pool_size == o.ice_candidate_pool_size &&
773 prune_turn_ports == o.prune_turn_ports &&
774 presume_writable_when_fully_relayed ==
775 o.presume_writable_when_fully_relayed &&
776 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800777 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800778 ice_check_interval_strong_connectivity ==
779 o.ice_check_interval_strong_connectivity &&
780 ice_check_interval_weak_connectivity ==
781 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700782 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700783 ice_unwritable_timeout == o.ice_unwritable_timeout &&
784 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800785 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800786 stun_candidate_keepalive_interval ==
787 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200788 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800789 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800790 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700791 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700792 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700793 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700794 use_media_transport_for_data_channels ==
795 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100796 crypto_options == o.crypto_options &&
797 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800798}
799
800bool PeerConnectionInterface::RTCConfiguration::operator!=(
801 const PeerConnectionInterface::RTCConfiguration& o) const {
802 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800803}
804
zhihuang8f65cdf2016-05-06 18:40:30 -0700805// Generate a RTCP CNAME when a PeerConnection is created.
806std::string GenerateRtcpCname() {
807 std::string cname;
808 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100809 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800810 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700811 }
812 return cname;
813}
814
zhihuang1c378ed2017-08-17 14:10:50 -0700815bool ValidateOfferAnswerOptions(
816 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
817 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
818 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700819}
820
zhihuang1c378ed2017-08-17 14:10:50 -0700821// From |rtc_options|, fill parts of |session_options| shared by all generated
822// m= sections (in other words, nothing that involves a map/array).
823void ExtractSharedMediaSessionOptions(
824 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
825 cricket::MediaSessionOptions* session_options) {
826 session_options->vad_enabled = rtc_options.voice_activity_detection;
827 session_options->bundle_enabled = rtc_options.use_rtp_mux;
828}
zhihuanga77e6bb2017-08-14 18:17:48 -0700829
zhihuang38ede132017-06-15 12:52:32 -0700830PeerConnection::PeerConnection(PeerConnectionFactory* factory,
831 std::unique_ptr<RtcEventLog> event_log,
832 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700834 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700835 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700836 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700837 remote_streams_(StreamCollection::Create()),
838 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839
840PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100841 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800842 RTC_DCHECK_RUN_ON(signaling_thread());
843
Steve Anton8af21862017-12-15 11:20:13 -0800844 // Need to stop transceivers before destroying the stats collector because
845 // AudioRtpSender has a reference to the StatsCollector it will update when
846 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100847 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800848 transceiver->Stop();
849 }
Steve Anton4171afb2017-11-20 10:20:22 -0800850
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700851 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800852 if (stats_collector_) {
853 stats_collector_->WaitForPendingRequest();
854 stats_collector_ = nullptr;
855 }
Steve Anton75737c02017-11-06 10:37:17 -0800856
Steve Anton8af21862017-12-15 11:20:13 -0800857 // Don't destroy BaseChannels until after stats has been cleaned up so that
858 // the last stats request can still read from the channels.
859 DestroyAllChannels();
860
Mirko Bonadei675513b2017-11-09 11:09:25 +0100861 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800862
863 webrtc_session_desc_factory_.reset();
864 sctp_invoker_.reset();
865 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800866 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800867 transport_controller_.reset();
868
deadbeef91dd5672016-05-18 16:55:30 -0700869 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700870 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700871 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700872 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700873 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700874 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800875 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700876 event_log_.reset();
877 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000878}
879
Steve Anton8af21862017-12-15 11:20:13 -0800880void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800881 // Destroy video channels first since they may have a pointer to a voice
882 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100883 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800884 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800885 DestroyTransceiverChannel(transceiver);
886 }
887 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100888 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800889 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800890 DestroyTransceiverChannel(transceiver);
891 }
892 }
893 DestroyDataChannel();
894}
895
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000897 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700898 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100899 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700900
901 RTCError config_error = ValidateConfiguration(configuration);
902 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100903 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700904 return false;
905 }
906
Benjamin Wrightcab58882018-05-02 15:12:47 -0700907 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100908 RTC_LOG(LS_ERROR)
909 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100910 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800911 return false;
912 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200913
Benjamin Wrightcab58882018-05-02 15:12:47 -0700914 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800915 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100916 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100917 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800918 return false;
919 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700920
Benjamin Wrightcab58882018-05-02 15:12:47 -0700921 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700922 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700923 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700924 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800925
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200926 cricket::ServerAddresses stun_servers;
927 std::vector<cricket::RelayServerConfig> turn_servers;
928
929 RTCErrorType parse_error =
930 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
931 if (parse_error != RTCErrorType::NONE) {
932 return false;
933 }
934
deadbeef91dd5672016-05-18 16:55:30 -0700935 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700936 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700937 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200938 RTC_FROM_HERE,
939 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
940 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941 return false;
942 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200943 // If initialization was successful, note if STUN or TURN servers
944 // were supplied.
945 if (!stun_servers.empty()) {
946 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
947 }
948 if (!turn_servers.empty()) {
949 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
950 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700952 // Send information about IPv4/IPv6 status.
953 PeerConnectionAddressFamilyCounter address_family;
954 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
955 address_family = kPeerConnection_IPv6;
956 } else {
957 address_family = kPeerConnection_IPv4;
958 }
959 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
960 kPeerConnectionAddressFamilyCounter_Max);
961
Zhi Huange830e682018-03-30 10:48:35 -0700962 const PeerConnectionFactoryInterface::Options& options = factory_->options();
963
Steve Anton75737c02017-11-06 10:37:17 -0800964 // RFC 3264: The numeric value of the session id and version in the
965 // o line MUST be representable with a "64 bit signed integer".
966 // Due to this constraint session id |session_id_| is max limited to
967 // LLONG_MAX.
968 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700969 JsepTransportController::Config config;
970 config.redetermine_role_on_ice_restart =
971 configuration.redetermine_role_on_ice_restart;
972 config.ssl_max_version = factory_->options().ssl_max_version;
973 config.disable_encryption = options.disable_encryption;
974 config.bundle_policy = configuration.bundle_policy;
975 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700976 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
977 // stub.
978 config.crypto_options = configuration.crypto_options.has_value()
979 ? *configuration.crypto_options
980 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700981 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700982 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700983#if defined(ENABLE_EXTERNAL_AUTH)
984 config.enable_external_auth = true;
985#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700986 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700987
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700988 if (configuration.use_media_transport ||
989 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700990 if (!factory_->media_transport_factory()) {
991 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700992 << "PeerConnecton is initialized with use_media_transport = true or "
993 << "use_media_transport_for_data_channels = true "
994 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700995 return false;
996 }
997
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -0800998 config.use_media_transport_for_media = configuration.use_media_transport;
999 config.use_media_transport_for_data_channels =
1000 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001001 config.media_transport_factory = factory_->media_transport_factory();
1002 }
1003
Zhi Huange830e682018-03-30 10:48:35 -07001004 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001005 signaling_thread(), network_thread(), port_allocator_.get(),
1006 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001007 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001008 this, &PeerConnection::OnTransportControllerConnectionState);
1009 transport_controller_->SignalStandardizedIceConnectionState.connect(
1010 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001011 transport_controller_->SignalConnectionState.connect(
1012 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001013 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001014 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001015 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001016 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001017 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001018 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1019 transport_controller_->SignalDtlsHandshakeError.connect(
1020 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1021
1022 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001023
deadbeefab9b2d12015-10-14 11:33:11 -07001024 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001025 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026
Steve Antonba818672017-11-06 10:21:57 -08001027 configuration_ = configuration;
1028
Steve Anton75737c02017-11-06 10:37:17 -08001029 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1030 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1031 if (!configuration.certificates.empty()) {
1032 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1033 // just picking the first one. The decision should be made based on the DTLS
1034 // handshake. The DTLS negotiations need to know about all certificates.
1035 certificate = configuration.certificates[0];
1036 }
1037
Steve Antond25da372017-11-06 14:50:29 -08001038 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001039
1040 if (options.disable_encryption) {
1041 dtls_enabled_ = false;
1042 } else {
1043 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001044 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001045 // |configuration| can override the default |dtls_enabled_| value.
1046 if (configuration.enable_dtls_srtp) {
1047 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1048 }
1049 }
1050
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001051 if (configuration.use_media_transport_for_data_channels) {
1052 if (configuration.enable_rtp_data_channel) {
1053 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1054 "use_media_transport_for_data_channels are "
1055 "incompatible and cannot both be set to true";
1056 return false;
1057 }
1058 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1059 } else if (configuration.enable_rtp_data_channel) {
1060 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1061 // set. It takes precendence over the disable_sctp_data_channels
1062 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001063 data_channel_type_ = cricket::DCT_RTP;
1064 } else {
1065 // DTLS has to be enabled to use SCTP.
1066 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1067 data_channel_type_ = cricket::DCT_SCTP;
1068 }
1069 }
1070
1071 video_options_.screencast_min_bitrate_kbps =
1072 configuration.screencast_min_bitrate;
1073 audio_options_.combined_audio_video_bwe =
1074 configuration.combined_audio_video_bwe;
1075
1076 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001077 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001078
1079 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001080 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001081
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001082 audio_options_.audio_jitter_buffer_min_delay_ms =
1083 configuration.audio_jitter_buffer_min_delay_ms;
1084
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001085 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1086 configuration.audio_jitter_buffer_enable_rtx_handling;
1087
Steve Anton75737c02017-11-06 10:37:17 -08001088 // Whether the certificate generator/certificate is null or not determines
1089 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1090 // the right instructions by clearing the variables if needed.
1091 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001092 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001093 certificate = nullptr;
1094 } else if (certificate) {
1095 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001096 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001097 }
1098
1099 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1100 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001101 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001102 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1103 this, &PeerConnection::OnCertificateReady);
1104
1105 if (options.disable_encryption) {
1106 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1107 }
1108
1109 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001110 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001111 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112
Steve Anton4171afb2017-11-20 10:20:22 -08001113 // Add default audio/video transceivers for Plan B SDP.
1114 if (!IsUnifiedPlan()) {
1115 transceivers_.push_back(
1116 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1117 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1118 transceivers_.push_back(
1119 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1120 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1121 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001122 int delay_ms =
1123 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001124 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1125 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126 return true;
1127}
1128
Steve Anton038834f2017-07-14 15:59:59 -07001129RTCError PeerConnection::ValidateConfiguration(
1130 const RTCConfiguration& config) const {
1131 if (config.ice_regather_interval_range &&
1132 config.continual_gathering_policy == GATHER_ONCE) {
1133 return RTCError(RTCErrorType::INVALID_PARAMETER,
1134 "ice_regather_interval_range specified but continual "
1135 "gathering policy is GATHER_ONCE");
1136 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001137 auto result =
1138 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1139 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001140}
1141
Yves Gerey665174f2018-06-19 15:03:05 +02001142rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001143 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1144 "Plan SdpSemantics. Please use GetSenders "
1145 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001146 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147}
1148
Yves Gerey665174f2018-06-19 15:03:05 +02001149rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001150 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1151 "Plan SdpSemantics. Please use GetReceivers "
1152 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001153 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154}
1155
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001156bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001157 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1158 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001159 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001160 if (IsClosed()) {
1161 return false;
1162 }
deadbeefab9b2d12015-10-14 11:33:11 -07001163 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001164 return false;
1165 }
deadbeefab9b2d12015-10-14 11:33:11 -07001166
1167 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001168 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1169 observer->SignalAudioTrackAdded.connect(this,
1170 &PeerConnection::OnAudioTrackAdded);
1171 observer->SignalAudioTrackRemoved.connect(
1172 this, &PeerConnection::OnAudioTrackRemoved);
1173 observer->SignalVideoTrackAdded.connect(this,
1174 &PeerConnection::OnVideoTrackAdded);
1175 observer->SignalVideoTrackRemoved.connect(
1176 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001177 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001178
deadbeefab9b2d12015-10-14 11:33:11 -07001179 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001180 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001181 }
1182 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001183 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001184 }
1185
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001186 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001187 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 return true;
1189}
1190
1191void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001192 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1193 "Plan SdpSemantics. Please use RemoveTrack "
1194 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001195 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001196 if (!IsClosed()) {
1197 for (const auto& track : local_stream->GetAudioTracks()) {
1198 RemoveAudioTrack(track.get(), local_stream);
1199 }
1200 for (const auto& track : local_stream->GetVideoTracks()) {
1201 RemoveVideoTrack(track.get(), local_stream);
1202 }
deadbeefab9b2d12015-10-14 11:33:11 -07001203 }
deadbeefab9b2d12015-10-14 11:33:11 -07001204 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001205 stream_observers_.erase(
1206 std::remove_if(
1207 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001208 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001209 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001210 }),
1211 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001212
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001213 if (IsClosed()) {
1214 return;
1215 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001216 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217}
1218
Steve Anton2d6c76a2018-01-05 17:10:52 -08001219RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001220 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001221 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001222 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001223 if (!track) {
1224 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1225 }
1226 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1227 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1228 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1229 "Track has invalid kind: " + track->kind());
1230 }
Steve Antonf9381f02017-12-14 10:23:57 -08001231 if (IsClosed()) {
1232 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1233 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001234 }
Steve Anton4171afb2017-11-20 10:20:22 -08001235 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001236 LOG_AND_RETURN_ERROR(
1237 RTCErrorType::INVALID_PARAMETER,
1238 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001239 }
Steve Antonf9381f02017-12-14 10:23:57 -08001240 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001241 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1242 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001243 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001244 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001245 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001246 }
1247 return sender_or_error;
1248}
deadbeefe1f9d832016-01-14 15:35:42 -08001249
Steve Antonf9381f02017-12-14 10:23:57 -08001250RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1251PeerConnection::AddTrackPlanB(
1252 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001253 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001254 if (stream_ids.size() > 1u) {
1255 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1256 "AddTrack with more than one stream is not "
1257 "supported with Plan B semantics.");
1258 }
1259 std::vector<std::string> adjusted_stream_ids = stream_ids;
1260 if (adjusted_stream_ids.empty()) {
1261 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1262 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001263 cricket::MediaType media_type =
1264 (track->kind() == MediaStreamTrackInterface::kAudioKind
1265 ? cricket::MEDIA_TYPE_AUDIO
1266 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001267 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001268 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001269 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001270 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001271 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001272 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001273 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001274 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001275 if (sender_info) {
1276 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001277 }
Steve Antonf9381f02017-12-14 10:23:57 -08001278 } else {
1279 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001280 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001281 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001282 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001283 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001284 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001285 if (sender_info) {
1286 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001287 }
deadbeefe1f9d832016-01-14 15:35:42 -08001288 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001289 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001290}
deadbeefe1f9d832016-01-14 15:35:42 -08001291
Steve Antonf9381f02017-12-14 10:23:57 -08001292RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1293PeerConnection::AddTrackUnifiedPlan(
1294 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001295 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001296 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1297 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001298 RTC_LOG(LS_INFO) << "Reusing an existing "
1299 << cricket::MediaTypeToString(transceiver->media_type())
1300 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001301 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001302 transceiver->internal()->set_direction(
1303 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001304 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001305 transceiver->internal()->set_direction(
1306 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001307 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001308 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001309 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001310 } else {
1311 cricket::MediaType media_type =
1312 (track->kind() == MediaStreamTrackInterface::kAudioKind
1313 ? cricket::MEDIA_TYPE_AUDIO
1314 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001315 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1316 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001317 std::string sender_id = track->id();
1318 // Avoid creating a sender with an existing ID by generating a random ID.
1319 // This can happen if this is the second time AddTrack has created a sender
1320 // for this track.
1321 if (FindSenderById(sender_id)) {
1322 sender_id = rtc::CreateRandomUuid();
1323 }
Florent Castelli892acf02018-10-01 22:47:20 +02001324 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001325 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1326 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001327 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001328 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001329 }
Steve Antonf9381f02017-12-14 10:23:57 -08001330 return transceiver->sender();
1331}
1332
1333rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1334PeerConnection::FindFirstTransceiverForAddedTrack(
1335 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1336 RTC_DCHECK(track);
1337 for (auto transceiver : transceivers_) {
1338 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001339 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001340 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001341 !transceiver->internal()->has_ever_been_used_to_send() &&
1342 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001343 return transceiver;
1344 }
1345 }
1346 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001347}
1348
1349bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1350 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001351 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001352}
1353
Steve Anton24db5732018-07-23 10:27:33 -07001354RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001355 rtc::scoped_refptr<RtpSenderInterface> sender) {
1356 if (!sender) {
1357 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1358 }
deadbeefe1f9d832016-01-14 15:35:42 -08001359 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001360 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1361 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001362 }
Steve Antonf9381f02017-12-14 10:23:57 -08001363 if (IsUnifiedPlan()) {
1364 auto transceiver = FindTransceiverBySender(sender);
1365 if (!transceiver || !sender->track()) {
1366 return RTCError::OK();
1367 }
1368 sender->SetTrack(nullptr);
1369 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001370 transceiver->internal()->set_direction(
1371 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001372 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001373 transceiver->internal()->set_direction(
1374 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001375 }
Steve Anton4171afb2017-11-20 10:20:22 -08001376 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001377 bool removed;
1378 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1379 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1380 } else {
1381 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1382 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1383 }
1384 if (!removed) {
1385 LOG_AND_RETURN_ERROR(
1386 RTCErrorType::INVALID_PARAMETER,
1387 "Couldn't find sender " + sender->id() + " to remove.");
1388 }
Steve Anton4171afb2017-11-20 10:20:22 -08001389 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001390 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001391 return RTCError::OK();
1392}
1393
1394rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1395PeerConnection::FindTransceiverBySender(
1396 rtc::scoped_refptr<RtpSenderInterface> sender) {
1397 for (auto transceiver : transceivers_) {
1398 if (transceiver->sender() == sender) {
1399 return transceiver;
1400 }
1401 }
1402 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001403}
1404
Steve Anton9158ef62017-11-27 13:01:52 -08001405RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1406PeerConnection::AddTransceiver(
1407 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1408 return AddTransceiver(track, RtpTransceiverInit());
1409}
1410
1411RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1412PeerConnection::AddTransceiver(
1413 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1414 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001415 RTC_CHECK(IsUnifiedPlan())
1416 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001417 if (!track) {
1418 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1419 }
1420 cricket::MediaType media_type;
1421 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1422 media_type = cricket::MEDIA_TYPE_AUDIO;
1423 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1424 media_type = cricket::MEDIA_TYPE_VIDEO;
1425 } else {
1426 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1427 "Track kind is not audio or video");
1428 }
1429 return AddTransceiver(media_type, track, init);
1430}
1431
1432RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1433PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1434 return AddTransceiver(media_type, RtpTransceiverInit());
1435}
1436
1437RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1438PeerConnection::AddTransceiver(cricket::MediaType media_type,
1439 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001440 RTC_CHECK(IsUnifiedPlan())
1441 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001442 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1443 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1444 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1445 "media type is not audio or video");
1446 }
1447 return AddTransceiver(media_type, nullptr, init);
1448}
1449
1450RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1451PeerConnection::AddTransceiver(
1452 cricket::MediaType media_type,
1453 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001454 const RtpTransceiverInit& init,
1455 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001456 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1457 media_type == cricket::MEDIA_TYPE_VIDEO));
1458 if (track) {
1459 RTC_DCHECK_EQ(media_type,
1460 (track->kind() == MediaStreamTrackInterface::kAudioKind
1461 ? cricket::MEDIA_TYPE_AUDIO
1462 : cricket::MEDIA_TYPE_VIDEO));
1463 }
1464
1465 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001466 if (init.send_encodings.size() > 1) {
1467 LOG_AND_RETURN_ERROR(
1468 RTCErrorType::UNSUPPORTED_PARAMETER,
1469 "Attempted to create an encoder with more than 1 encoding parameter.");
1470 }
1471
1472 for (const auto& encoding : init.send_encodings) {
1473 if (encoding.ssrc.has_value()) {
1474 LOG_AND_RETURN_ERROR(
1475 RTCErrorType::UNSUPPORTED_PARAMETER,
1476 "Attempted to set an unimplemented parameter of RtpParameters.");
1477 }
1478 }
1479
1480 RtpParameters parameters;
1481 parameters.encodings = init.send_encodings;
1482 if (UnimplementedRtpParameterHasValue(parameters)) {
1483 LOG_AND_RETURN_ERROR(
1484 RTCErrorType::UNSUPPORTED_PARAMETER,
1485 "Attempted to set an unimplemented parameter of RtpParameters.");
1486 }
Steve Anton9158ef62017-11-27 13:01:52 -08001487
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001488 auto result = cricket::CheckRtpParametersValues(parameters);
1489 if (!result.ok()) {
1490 LOG_AND_RETURN_ERROR(result.type(), result.message());
1491 }
1492
Steve Anton3d954a62018-04-02 11:27:23 -07001493 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1494 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001495 // Set the sender ID equal to the track ID if the track is specified unless
1496 // that sender ID is already in use.
1497 std::string sender_id =
1498 (track && !FindSenderById(track->id()) ? track->id()
1499 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001500 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1501 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001502 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1503 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1504 transceiver->internal()->set_direction(init.direction);
1505
Steve Anton22da89f2018-01-25 13:58:07 -08001506 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001507 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001508 }
Steve Antonf9381f02017-12-14 10:23:57 -08001509
1510 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1511}
1512
Steve Anton02ee47c2018-01-10 16:26:06 -08001513rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1514PeerConnection::CreateSender(
1515 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001516 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001517 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001518 const std::vector<std::string>& stream_ids,
1519 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001520 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001521 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1522 RTC_DCHECK(!track ||
1523 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1524 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1525 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001526 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001527 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001528 } else {
1529 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1530 RTC_DCHECK(!track ||
1531 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1532 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001533 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001534 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001535 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001536 bool set_track_succeeded = sender->SetTrack(track);
1537 RTC_DCHECK(set_track_succeeded);
1538 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001539 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001540 return sender;
1541}
1542
1543rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1544PeerConnection::CreateReceiver(cricket::MediaType media_type,
1545 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001546 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1547 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001548 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001549 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001550 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1551 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001552 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001553 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001554 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001555 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001556 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1557 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001558 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001559 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001560 return receiver;
1561}
1562
1563rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1564PeerConnection::CreateAndAddTransceiver(
1565 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1566 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1567 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001568 // Ensure that the new sender does not have an ID that is already in use by
1569 // another sender.
1570 // Allow receiver IDs to conflict since those come from remote SDP (which
1571 // could be invalid, but should not cause a crash).
1572 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001573 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1574 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001575 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001576 transceiver->internal()->SignalNegotiationNeeded.connect(
1577 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001578 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001579}
1580
Steve Anton52d86772018-02-20 15:48:12 -08001581void PeerConnection::OnNegotiationNeeded() {
1582 RTC_DCHECK_RUN_ON(signaling_thread());
1583 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001584 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001585}
1586
deadbeeffac06552015-11-25 11:26:01 -08001587rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001588 const std::string& kind,
1589 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001590 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1591 "Plan SdpSemantics. Please use AddTransceiver "
1592 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001593 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001594 if (IsClosed()) {
1595 return nullptr;
1596 }
Steve Anton4171afb2017-11-20 10:20:22 -08001597
Seth Hampson5b4f0752018-04-02 16:31:36 -07001598 // Internally we need to have one stream with Plan B semantics, so we
1599 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001600 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001601 if (stream_id.empty()) {
1602 stream_ids.push_back(rtc::CreateRandomUuid());
1603 RTC_LOG(LS_INFO)
1604 << "No stream_id specified for sender. Generated stream ID: "
1605 << stream_ids[0];
1606 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001607 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001608 }
1609
Steve Anton4171afb2017-11-20 10:20:22 -08001610 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001611 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001612 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001613 auto* audio_sender = new AudioRtpSender(
1614 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001615 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001616 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001617 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001618 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001619 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001620 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001621 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001622 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001623 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001624 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001625 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001626 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001627 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001628 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001629 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001630 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001631
deadbeefe1f9d832016-01-14 15:35:42 -08001632 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001633}
1634
deadbeef70ab1a12015-09-28 16:53:55 -07001635std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1636 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001637 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001638 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001639 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001640 }
1641 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001642}
1643
Steve Anton4171afb2017-11-20 10:20:22 -08001644std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1645PeerConnection::GetSendersInternal() const {
1646 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1647 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001648 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001649 auto senders = transceiver->internal()->senders();
1650 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1651 }
1652 return all_senders;
1653}
1654
deadbeef70ab1a12015-09-28 16:53:55 -07001655std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1656PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001657 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001658 for (const auto& receiver : GetReceiversInternal()) {
1659 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001660 }
1661 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001662}
1663
Steve Anton4171afb2017-11-20 10:20:22 -08001664std::vector<
1665 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1666PeerConnection::GetReceiversInternal() const {
1667 std::vector<
1668 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1669 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001670 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001671 auto receivers = transceiver->internal()->receivers();
1672 all_receivers.insert(all_receivers.end(), receivers.begin(),
1673 receivers.end());
1674 }
1675 return all_receivers;
1676}
1677
Steve Anton9158ef62017-11-27 13:01:52 -08001678std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1679PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001680 RTC_CHECK(IsUnifiedPlan())
1681 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001682 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001683 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001684 all_transceivers.push_back(transceiver);
1685 }
1686 return all_transceivers;
1687}
1688
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001689bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001690 MediaStreamTrackInterface* track,
1691 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001692 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001693 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001694 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001695 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001696 return false;
1697 }
1698
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001699 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001700 // The StatsCollector is used to tell if a track is valid because it may
1701 // remember tracks that the PeerConnection previously removed.
1702 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001703 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1704 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001705 return false;
1706 }
Steve Antonad182762018-09-05 20:22:40 +00001707 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1708 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709 return true;
1710}
1711
hbos74e1a4f2016-09-15 23:33:01 -07001712void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001713 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001714 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001715 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001716 stats_collector_->GetStatsReport(callback);
1717}
1718
Henrik Boström1df1bf82018-03-20 13:24:20 +01001719void PeerConnection::GetStats(
1720 rtc::scoped_refptr<RtpSenderInterface> selector,
1721 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1722 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1723 RTC_DCHECK(callback);
1724 RTC_DCHECK(stats_collector_);
1725 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1726 if (selector) {
1727 for (const auto& proxy_transceiver : transceivers_) {
1728 for (const auto& proxy_sender :
1729 proxy_transceiver->internal()->senders()) {
1730 if (proxy_sender == selector) {
1731 internal_sender = proxy_sender->internal();
1732 break;
1733 }
1734 }
1735 if (internal_sender)
1736 break;
1737 }
1738 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001739 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001740 // belong to the PeerConnection (in Plan B, senders can be removed from the
1741 // PeerConnection). This means that "all the stats objects representing the
1742 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1743 // produces an empty stats report.
1744 stats_collector_->GetStatsReport(internal_sender, callback);
1745}
1746
1747void PeerConnection::GetStats(
1748 rtc::scoped_refptr<RtpReceiverInterface> selector,
1749 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1750 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1751 RTC_DCHECK(callback);
1752 RTC_DCHECK(stats_collector_);
1753 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1754 if (selector) {
1755 for (const auto& proxy_transceiver : transceivers_) {
1756 for (const auto& proxy_receiver :
1757 proxy_transceiver->internal()->receivers()) {
1758 if (proxy_receiver == selector) {
1759 internal_receiver = proxy_receiver->internal();
1760 break;
1761 }
1762 }
1763 if (internal_receiver)
1764 break;
1765 }
1766 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001767 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001768 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1769 // the PeerConnection). This means that "all the stats objects representing
1770 // the selector" is an empty set. Invoking GetStatsReport() with a null
1771 // selector produces an empty stats report.
1772 stats_collector_->GetStatsReport(internal_receiver, callback);
1773}
1774
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1776 return signaling_state_;
1777}
1778
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001779PeerConnectionInterface::IceConnectionState
1780PeerConnection::ice_connection_state() {
1781 return ice_connection_state_;
1782}
1783
Alex Loiko9289eda2018-11-23 16:18:59 +00001784PeerConnectionInterface::IceConnectionState
1785PeerConnection::standardized_ice_connection_state() {
1786 return standardized_ice_connection_state_;
1787}
1788
Jonas Olsson635474e2018-10-18 15:58:17 +02001789PeerConnectionInterface::PeerConnectionState
1790PeerConnection::peer_connection_state() {
1791 return connection_state_;
1792}
1793
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001794PeerConnectionInterface::IceGatheringState
1795PeerConnection::ice_gathering_state() {
1796 return ice_gathering_state_;
1797}
1798
Yves Gerey665174f2018-06-19 15:03:05 +02001799rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 const std::string& label,
1801 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001802 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001803
deadbeefab9b2d12015-10-14 11:33:11 -07001804 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001805
kwibergd1fe2812016-04-27 06:47:29 -07001806 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001807 if (config) {
1808 internal_config.reset(new InternalDataChannelInit(*config));
1809 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001810 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001811 InternalCreateDataChannel(label, internal_config.get()));
1812 if (!channel.get()) {
1813 return nullptr;
1814 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001815
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001816 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1817 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001818 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001819 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001820 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001821 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822 return DataChannelProxy::Create(signaling_thread(), channel.get());
1823}
1824
1825void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001826 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001827 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001828
nisse7ce109a2017-01-31 00:57:56 -08001829 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001830 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001831 return;
1832 }
deadbeefab9b2d12015-10-14 11:33:11 -07001833
Steve Anton8d3444d2017-10-20 15:30:51 -07001834 if (IsClosed()) {
1835 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001836 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001837 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001838 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001839 return;
1840 }
1841
zhihuang1c378ed2017-08-17 14:10:50 -07001842 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001843 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001844 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001845 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001846 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001847 return;
1848 }
1849
Steve Anton22da89f2018-01-25 13:58:07 -08001850 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1851 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1852 if (IsUnifiedPlan()) {
1853 RTCError error = HandleLegacyOfferOptions(options);
1854 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001855 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001856 return;
1857 }
1858 }
1859
zhihuang1c378ed2017-08-17 14:10:50 -07001860 cricket::MediaSessionOptions session_options;
1861 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001862 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001863}
1864
Steve Anton22da89f2018-01-25 13:58:07 -08001865RTCError PeerConnection::HandleLegacyOfferOptions(
1866 const RTCOfferAnswerOptions& options) {
1867 RTC_DCHECK(IsUnifiedPlan());
1868
1869 if (options.offer_to_receive_audio == 0) {
1870 RemoveRecvDirectionFromReceivingTransceiversOfType(
1871 cricket::MEDIA_TYPE_AUDIO);
1872 } else if (options.offer_to_receive_audio == 1) {
1873 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1874 } else if (options.offer_to_receive_audio > 1) {
1875 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1876 "offer_to_receive_audio > 1 is not supported.");
1877 }
1878
1879 if (options.offer_to_receive_video == 0) {
1880 RemoveRecvDirectionFromReceivingTransceiversOfType(
1881 cricket::MEDIA_TYPE_VIDEO);
1882 } else if (options.offer_to_receive_video == 1) {
1883 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1884 } else if (options.offer_to_receive_video > 1) {
1885 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1886 "offer_to_receive_video > 1 is not supported.");
1887 }
1888
1889 return RTCError::OK();
1890}
1891
1892void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1893 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001894 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001895 RtpTransceiverDirection new_direction =
1896 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1897 if (new_direction != transceiver->direction()) {
1898 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1899 << " transceiver (MID="
1900 << transceiver->mid().value_or("<not set>") << ") from "
1901 << RtpTransceiverDirectionToString(
1902 transceiver->direction())
1903 << " to "
1904 << RtpTransceiverDirectionToString(new_direction)
1905 << " since CreateOffer specified offer_to_receive=0";
1906 transceiver->internal()->set_direction(new_direction);
1907 }
Steve Anton22da89f2018-01-25 13:58:07 -08001908 }
1909}
1910
1911void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1912 cricket::MediaType media_type) {
1913 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001914 RTC_LOG(LS_INFO)
1915 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1916 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001917 RtpTransceiverInit init;
1918 init.direction = RtpTransceiverDirection::kRecvOnly;
1919 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1920 }
1921}
1922
1923std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1924PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1925 std::vector<
1926 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1927 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001928 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001929 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001930 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1931 receiving_transceivers.push_back(transceiver);
1932 }
1933 }
1934 return receiving_transceivers;
1935}
1936
htaa2a49d92016-03-04 02:51:39 -08001937void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1938 const RTCOfferAnswerOptions& options) {
1939 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001940 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001941 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001942 return;
1943 }
1944
Steve Antondffead82018-02-06 10:31:29 -08001945 if (!(signaling_state_ == kHaveRemoteOffer ||
1946 signaling_state_ == kHaveLocalPrAnswer)) {
1947 std::string error =
1948 "PeerConnection cannot create an answer in a state other than "
1949 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001950 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001951 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001952 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001953 return;
1954 }
1955
Steve Antondffead82018-02-06 10:31:29 -08001956 // The remote description should be set if we're in the right state.
1957 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001958
Steve Anton22da89f2018-01-25 13:58:07 -08001959 if (IsUnifiedPlan()) {
1960 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1961 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1962 "supported with Unified Plan semantics. Use the "
1963 "RtpTransceiver API instead.";
1964 }
1965 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1966 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1967 "supported with Unified Plan semantics. Use the "
1968 "RtpTransceiver API instead.";
1969 }
1970 }
1971
htaa2a49d92016-03-04 02:51:39 -08001972 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001973 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001974
Steve Antond25da372017-11-06 14:50:29 -08001975 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976}
1977
1978void PeerConnection::SetLocalDescription(
1979 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001980 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001981 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001982
Steve Anton80dd7b52018-02-16 17:08:42 -08001983 // The SetLocalDescription contract is that we take ownership of the session
1984 // description regardless of the outcome, so wrap it in a unique_ptr right
1985 // away. Ideally, SetLocalDescription's signature will be changed to take the
1986 // description as a unique_ptr argument to formalize this agreement.
1987 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1988
nisse7ce109a2017-01-31 00:57:56 -08001989 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001990 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 return;
1992 }
Steve Anton8a006912017-12-04 15:25:56 -08001993
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001994 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001995 PostSetSessionDescriptionFailure(
1996 observer,
1997 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998 return;
1999 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002000
Steve Anton80dd7b52018-02-16 17:08:42 -08002001 // If a session error has occurred the PeerConnection is in a possibly
2002 // inconsistent state so fail right away.
2003 if (session_error() != SessionError::kNone) {
2004 std::string error_message = GetSessionErrorMsg();
2005 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002006 PostSetSessionDescriptionFailure(
2007 observer,
2008 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002009 return;
2010 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002011
Steve Anton80dd7b52018-02-16 17:08:42 -08002012 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2013 if (!error.ok()) {
2014 std::string error_message = GetSetDescriptionErrorMessage(
2015 cricket::CS_LOCAL, desc->GetType(), error);
2016 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002017 PostSetSessionDescriptionFailure(
2018 observer,
2019 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002020 return;
2021 }
2022
2023 // Grab the description type before moving ownership to ApplyLocalDescription,
2024 // which may destroy it before returning.
2025 const SdpType type = desc->GetType();
2026
2027 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002028 // |desc| may be destroyed at this point.
2029
2030 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002031 // If ApplyLocalDescription fails, the PeerConnection could be in an
2032 // inconsistent state, so act conservatively here and set the session error
2033 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2034 SetSessionError(SessionError::kContent, error.message());
2035 std::string error_message =
2036 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2037 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002038 PostSetSessionDescriptionFailure(
2039 observer,
2040 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002041 return;
2042 }
Steve Anton8a006912017-12-04 15:25:56 -08002043 RTC_DCHECK(local_description());
2044
2045 PostSetSessionDescriptionSuccess(observer);
2046
Steve Antonad182762018-09-05 20:22:40 +00002047 // MaybeStartGathering needs to be called after posting
2048 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2049 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002050 transport_controller_->MaybeStartGathering();
2051
Steve Antona3a92c22017-12-07 10:27:41 -08002052 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002053 // TODO(deadbeef): We already had to hop to the network thread for
2054 // MaybeStartGathering...
2055 network_thread()->Invoke<void>(
2056 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2057 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002058 // Make UMA notes about what was agreed to.
2059 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002060 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002061 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002062}
2063
2064RTCError PeerConnection::ApplyLocalDescription(
2065 std::unique_ptr<SessionDescriptionInterface> desc) {
2066 RTC_DCHECK_RUN_ON(signaling_thread());
2067 RTC_DCHECK(desc);
2068
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002069 // Update stats here so that we have the most recent stats for tracks and
2070 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002071 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002072
Steve Antondcc3c022017-12-22 16:02:54 -08002073 // Take a reference to the old local description since it's used below to
2074 // compare against the new local description. When setting the new local
2075 // description, grab ownership of the replaced session description in case it
2076 // is the same as |old_local_description|, to keep it alive for the duration
2077 // of the method.
2078 const SessionDescriptionInterface* old_local_description =
2079 local_description();
2080 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002081 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002082 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002083 replaced_local_description = pending_local_description_
2084 ? std::move(pending_local_description_)
2085 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002086 current_local_description_ = std::move(desc);
2087 pending_local_description_ = nullptr;
2088 current_remote_description_ = std::move(pending_remote_description_);
2089 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002090 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002091 pending_local_description_ = std::move(desc);
2092 }
2093 // The session description to apply now must be accessed by
2094 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002095 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002096
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002097 if (!is_caller_) {
2098 if (remote_description()) {
2099 // Remote description was applied first, so this PC is the callee.
2100 is_caller_ = false;
2101 } else {
2102 // Local description is applied first, so this PC is the caller.
2103 is_caller_ = true;
2104 }
2105 }
2106
Zhi Huange830e682018-03-30 10:48:35 -07002107 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2108 if (!error.ok()) {
2109 return error;
2110 }
2111
Steve Antondcc3c022017-12-22 16:02:54 -08002112 if (IsUnifiedPlan()) {
2113 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002114 cricket::CS_LOCAL, *local_description(), old_local_description,
2115 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002116 if (!error.ok()) {
2117 return error;
2118 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002119 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2120 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002121 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002122 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2123 // Note that code paths that don't set MID won't be able to use
2124 // information about DTLS transports.
2125 if (transceiver->mid()) {
2126 auto dtls_transport =
2127 LookupDtlsTransportByMidInternal(*transceiver->mid());
2128 transceiver->internal()->sender_internal()->set_transport(
2129 dtls_transport);
2130 transceiver->internal()->receiver_internal()->set_transport(
2131 dtls_transport);
2132 }
2133
Steve Antondcc3c022017-12-22 16:02:54 -08002134 const ContentInfo* content =
2135 FindMediaSectionForTransceiver(transceiver, local_description());
2136 if (!content) {
2137 continue;
2138 }
2139 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002140 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2141 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002142 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002143 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2144 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2145 // "recvonly", process the removal of a remote track for the media
2146 // description, given transceiver, removeList, and muteTracks.
2147 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2148 (transceiver->internal()->fired_direction() &&
2149 RtpTransceiverDirectionHasRecv(
2150 *transceiver->internal()->fired_direction()))) {
2151 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2152 &removed_streams);
2153 }
2154 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2155 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002156 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002157 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002158 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002159 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002160 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002161 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002162 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002163 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002164 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002165 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002166 }
2167 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002168 // Media channels will be created only when offer is set. These may use new
2169 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002170 if (type == SdpType::kOffer) {
2171 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2172 // description is applied. Restore back to old description.
2173 RTCError error = CreateChannels(*local_description()->description());
2174 if (!error.ok()) {
2175 return error;
2176 }
2177 }
Steve Antondcc3c022017-12-22 16:02:54 -08002178 // Remove unused channels if MediaContentDescription is rejected.
2179 RemoveUnusedChannels(local_description()->description());
2180 }
Steve Anton8a006912017-12-04 15:25:56 -08002181
Zhi Huange830e682018-03-30 10:48:35 -07002182 error = UpdateSessionState(type, cricket::CS_LOCAL,
2183 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002184 if (!error.ok()) {
2185 return error;
2186 }
Steve Antondcc3c022017-12-22 16:02:54 -08002187
Steve Anton8a006912017-12-04 15:25:56 -08002188 if (remote_description()) {
2189 // Now that we have a local description, we can push down remote candidates.
2190 UseCandidatesInSessionDescription(remote_description());
2191 }
2192
2193 pending_ice_restarts_.clear();
2194 if (session_error() != SessionError::kNone) {
2195 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2196 }
2197
deadbeefab9b2d12015-10-14 11:33:11 -07002198 // If setting the description decided our SSL role, allocate any necessary
2199 // SCTP sids.
2200 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002201 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002202 AllocateSctpSids(role);
2203 }
2204
Steve Antond3679212018-01-17 17:41:02 -08002205 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002206 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002207 const ContentInfo* content =
2208 FindMediaSectionForTransceiver(transceiver, local_description());
2209 if (!content) {
2210 continue;
2211 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002212 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2213 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002214 // 0 is a special value meaning "this sender has no associated send
2215 // stream". Need to call this so the sender won't attempt to configure
2216 // a no longer existing stream and run into DCHECKs in the lower
2217 // layers.
2218 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002219 } else {
2220 // Get the StreamParams from the channel which could generate SSRCs.
2221 const std::vector<StreamParams>& streams = channel->local_streams();
2222 transceiver->internal()->sender_internal()->set_stream_ids(
2223 streams[0].stream_ids());
2224 transceiver->internal()->sender_internal()->SetSsrc(
2225 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002226 }
2227 }
2228 } else {
2229 // Plan B semantics.
2230
Steve Antondcc3c022017-12-22 16:02:54 -08002231 // Update state and SSRC of local MediaStreams and DataChannels based on the
2232 // local session description.
2233 const cricket::ContentInfo* audio_content =
2234 GetFirstAudioContent(local_description()->description());
2235 if (audio_content) {
2236 if (audio_content->rejected) {
2237 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2238 } else {
2239 const cricket::AudioContentDescription* audio_desc =
2240 audio_content->media_description()->as_audio();
2241 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2242 }
deadbeeffaac4972015-11-12 15:33:07 -08002243 }
deadbeefab9b2d12015-10-14 11:33:11 -07002244
Steve Antondcc3c022017-12-22 16:02:54 -08002245 const cricket::ContentInfo* video_content =
2246 GetFirstVideoContent(local_description()->description());
2247 if (video_content) {
2248 if (video_content->rejected) {
2249 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2250 } else {
2251 const cricket::VideoContentDescription* video_desc =
2252 video_content->media_description()->as_video();
2253 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2254 }
deadbeeffaac4972015-11-12 15:33:07 -08002255 }
deadbeefab9b2d12015-10-14 11:33:11 -07002256 }
2257
2258 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002259 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002260 if (data_content) {
2261 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002262 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002263 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002264 cricket::kMediaProtocolRtpPrefix)) {
2265 UpdateLocalRtpDataChannels(data_desc->streams());
2266 }
2267 }
2268
Steve Anton8a006912017-12-04 15:25:56 -08002269 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270}
2271
Steve Anton06817cd2018-12-18 15:55:30 -08002272// The SDP parser used to populate these values by default for the 'content
2273// name' if an a=mid line was absent.
2274static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2275 switch (media_type) {
2276 case cricket::MEDIA_TYPE_AUDIO:
2277 return cricket::CN_AUDIO;
2278 case cricket::MEDIA_TYPE_VIDEO:
2279 return cricket::CN_VIDEO;
2280 case cricket::MEDIA_TYPE_DATA:
2281 return cricket::CN_DATA;
2282 }
2283 RTC_NOTREACHED();
2284 return "";
2285}
2286
2287void PeerConnection::FillInMissingRemoteMids(
2288 cricket::SessionDescription* remote_description) {
2289 RTC_DCHECK(remote_description);
2290 const cricket::ContentInfos& local_contents =
2291 (local_description() ? local_description()->description()->contents()
2292 : cricket::ContentInfos());
Steve Anton06817cd2018-12-18 15:55:30 -08002293 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2294 cricket::ContentInfo& content = remote_description->contents()[i];
2295 if (!content.name.empty()) {
2296 continue;
2297 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002298 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002299 absl::string_view source_explanation;
2300 if (IsUnifiedPlan()) {
2301 if (i < local_contents.size()) {
2302 new_mid = local_contents[i].name;
2303 source_explanation = "from the matching local media section";
2304 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002305 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002306 source_explanation = "generated just now";
2307 }
2308 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002309 new_mid = std::string(
2310 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002311 source_explanation = "to match pre-existing behavior";
2312 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002313 content.name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002314 remote_description->transport_infos()[i].content_name =
2315 std::string(new_mid);
2316 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2317 << " is missing an a=mid line. Filling in the value '"
2318 << new_mid << "' " << source_explanation << ".";
2319 }
2320}
2321
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002323 SetSessionDescriptionObserver* observer,
2324 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002325 SetRemoteDescription(
2326 std::unique_ptr<SessionDescriptionInterface>(desc),
2327 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2328 new SetRemoteDescriptionObserverAdapter(this, observer)));
2329}
2330
2331void PeerConnection::SetRemoteDescription(
2332 std::unique_ptr<SessionDescriptionInterface> desc,
2333 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002334 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002335
nisse7ce109a2017-01-31 00:57:56 -08002336 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002337 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002338 return;
2339 }
Steve Anton8a006912017-12-04 15:25:56 -08002340
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002342 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002343 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344 return;
2345 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002346
Steve Anton80dd7b52018-02-16 17:08:42 -08002347 // If a session error has occurred the PeerConnection is in a possibly
2348 // inconsistent state so fail right away.
2349 if (session_error() != SessionError::kNone) {
2350 std::string error_message = GetSessionErrorMsg();
2351 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2352 observer->OnSetRemoteDescriptionComplete(
2353 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2354 return;
2355 }
Steve Anton71439a62018-02-15 11:53:06 -08002356
Steve Antonba42e992018-04-09 14:10:01 -07002357 if (desc->GetType() == SdpType::kOffer) {
2358 // Report to UMA the format of the received offer.
2359 ReportSdpFormatReceived(*desc);
2360 }
2361
Steve Anton06817cd2018-12-18 15:55:30 -08002362 // Handle remote descriptions missing a=mid lines for interop with legacy end
2363 // points.
2364 FillInMissingRemoteMids(desc->description());
2365
Steve Anton80dd7b52018-02-16 17:08:42 -08002366 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002367 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002368 std::string error_message = GetSetDescriptionErrorMessage(
2369 cricket::CS_REMOTE, desc->GetType(), error);
2370 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002371 observer->OnSetRemoteDescriptionComplete(
2372 RTCError(error.type(), std::move(error_message)));
2373 return;
2374 }
Steve Anton71439a62018-02-15 11:53:06 -08002375
Steve Anton80dd7b52018-02-16 17:08:42 -08002376 // Grab the description type before moving ownership to
2377 // ApplyRemoteDescription, which may destroy it before returning.
2378 const SdpType type = desc->GetType();
2379
2380 error = ApplyRemoteDescription(std::move(desc));
2381 // |desc| may be destroyed at this point.
2382
2383 if (!error.ok()) {
2384 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2385 // inconsistent state, so act conservatively here and set the session error
2386 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2387 SetSessionError(SessionError::kContent, error.message());
2388 std::string error_message =
2389 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2390 RTC_LOG(LS_ERROR) << error_message;
2391 observer->OnSetRemoteDescriptionComplete(
2392 RTCError(error.type(), std::move(error_message)));
2393 return;
2394 }
2395 RTC_DCHECK(remote_description());
2396
2397 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002398 // TODO(deadbeef): We already had to hop to the network thread for
2399 // MaybeStartGathering...
2400 network_thread()->Invoke<void>(
2401 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2402 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002403 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002404 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002405 }
2406
2407 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002408 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002409}
2410
2411RTCError PeerConnection::ApplyRemoteDescription(
2412 std::unique_ptr<SessionDescriptionInterface> desc) {
2413 RTC_DCHECK_RUN_ON(signaling_thread());
2414 RTC_DCHECK(desc);
2415
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416 // Update stats here so that we have the most recent stats for tracks and
2417 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002418 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002419
Steve Antondcc3c022017-12-22 16:02:54 -08002420 // Take a reference to the old remote description since it's used below to
2421 // compare against the new remote description. When setting the new remote
2422 // description, grab ownership of the replaced session description in case it
2423 // is the same as |old_remote_description|, to keep it alive for the duration
2424 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002425 const SessionDescriptionInterface* old_remote_description =
2426 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002427 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002428 SdpType type = desc->GetType();
2429 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002430 replaced_remote_description = pending_remote_description_
2431 ? std::move(pending_remote_description_)
2432 : std::move(current_remote_description_);
2433 current_remote_description_ = std::move(desc);
2434 pending_remote_description_ = nullptr;
2435 current_local_description_ = std::move(pending_local_description_);
2436 } else {
2437 replaced_remote_description = std::move(pending_remote_description_);
2438 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439 }
Steve Anton8a006912017-12-04 15:25:56 -08002440 // The session description to apply now must be accessed by
2441 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002442 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002443
Zhi Huange830e682018-03-30 10:48:35 -07002444 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2445 if (!error.ok()) {
2446 return error;
2447 }
Steve Anton8a006912017-12-04 15:25:56 -08002448 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002449 if (IsUnifiedPlan()) {
2450 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002451 cricket::CS_REMOTE, *remote_description(), local_description(),
2452 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002453 if (!error.ok()) {
2454 return error;
2455 }
Steve Antondcc3c022017-12-22 16:02:54 -08002456 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002457 // Media channels will be created only when offer is set. These may use new
2458 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002459 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002460 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002461 // description is applied. Restore back to old description.
2462 RTCError error = CreateChannels(*remote_description()->description());
2463 if (!error.ok()) {
2464 return error;
2465 }
2466 }
Steve Antondcc3c022017-12-22 16:02:54 -08002467 // Remove unused channels if MediaContentDescription is rejected.
2468 RemoveUnusedChannels(remote_description()->description());
2469 }
Steve Anton8a006912017-12-04 15:25:56 -08002470
Zhi Huange830e682018-03-30 10:48:35 -07002471 // NOTE: Candidates allocation will be initiated only when
2472 // SetLocalDescription is called.
2473 error = UpdateSessionState(type, cricket::CS_REMOTE,
2474 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002475 if (!error.ok()) {
2476 return error;
2477 }
2478
2479 if (local_description() &&
2480 !UseCandidatesInSessionDescription(remote_description())) {
2481 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2482 }
2483
2484 if (old_remote_description) {
2485 for (const cricket::ContentInfo& content :
2486 old_remote_description->description()->contents()) {
2487 // Check if this new SessionDescription contains new ICE ufrag and
2488 // password that indicates the remote peer requests an ICE restart.
2489 // TODO(deadbeef): When we start storing both the current and pending
2490 // remote description, this should reset pending_ice_restarts and compare
2491 // against the current description.
2492 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2493 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002494 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002495 pending_ice_restarts_.insert(content.name);
2496 }
2497 } else {
2498 // We retain all received candidates only if ICE is not restarted.
2499 // When ICE is restarted, all previous candidates belong to an old
2500 // generation and should not be kept.
2501 // TODO(deadbeef): This goes against the W3C spec which says the remote
2502 // description should only contain candidates from the last set remote
2503 // description plus any candidates added since then. We should remove
2504 // this once we're sure it won't break anything.
2505 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2506 old_remote_description, content.name, mutable_remote_description());
2507 }
2508 }
2509 }
2510
2511 if (session_error() != SessionError::kNone) {
2512 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2513 }
2514
2515 // Set the the ICE connection state to connecting since the connection may
2516 // become writable with peer reflexive candidates before any remote candidate
2517 // is signaled.
2518 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2519 // is to have a new signal the indicates a change in checking state from the
2520 // transport and expose a new checking() member from transport that can be
2521 // read to determine the current checking state. The existing SignalConnecting
2522 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002523 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002524 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002525 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2526 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2527 }
2528
deadbeefab9b2d12015-10-14 11:33:11 -07002529 // If setting the description decided our SSL role, allocate any necessary
2530 // SCTP sids.
2531 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002532 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002533 AllocateSctpSids(role);
2534 }
2535
Steve Antondcc3c022017-12-22 16:02:54 -08002536 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002537 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002538 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002539 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002540 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002541 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002542 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002543 const ContentInfo* content =
2544 FindMediaSectionForTransceiver(transceiver, remote_description());
2545 if (!content) {
2546 continue;
2547 }
2548 const MediaContentDescription* media_desc = content->media_description();
2549 RtpTransceiverDirection local_direction =
2550 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002551 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2552 // RTCSessionDescription: Set the associated remote streams given
2553 // transceiver.[[Receiver]], msids, addList, and removeList".
2554 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2555 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2556 std::vector<std::string> stream_ids;
2557 if (!media_desc->streams().empty()) {
2558 // The remote description has signaled the stream IDs.
2559 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002560 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002561 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2562 << " (" << GetStreamIdsString(stream_ids) << ").";
2563 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2564 stream_ids, &added_streams,
2565 &removed_streams);
2566 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2567 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2568 // and transceiver's current direction is neither sendrecv nor recvonly,
2569 // process the addition of a remote track for the media description.
2570 if (!transceiver->fired_direction() ||
2571 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2572 RTC_LOG(LS_INFO)
2573 << "Processing the addition of a remote track for MID="
2574 << content->name << ".";
2575 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002576 }
Steve Antondcc3c022017-12-22 16:02:54 -08002577 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002578 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002579 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2580 // removal of a remote track for the media description, given transceiver,
2581 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002582 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002583 (transceiver->fired_direction() &&
2584 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2585 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2586 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002587 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002588 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002589 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002590 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002591 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002592 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002593 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002594 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002595 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002596 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2597 if (transceiver->mid()) {
2598 auto dtls_transport =
2599 LookupDtlsTransportByMidInternal(*transceiver->mid());
2600 transceiver->internal()->sender_internal()->set_transport(
2601 dtls_transport);
2602 transceiver->internal()->receiver_internal()->set_transport(
2603 dtls_transport);
2604 }
Steve Antondcc3c022017-12-22 16:02:54 -08002605 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002606 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002607 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002608 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002609 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2610 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002611 transceiver->Stop();
2612 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002613 if (!content->rejected &&
2614 RtpTransceiverDirectionHasRecv(local_direction)) {
2615 // Set ssrc to 0 in the case of an unsignalled ssrc.
2616 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002617 if (!media_desc->streams().empty() &&
2618 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002619 ssrc = media_desc->streams()[0].first_ssrc();
2620 }
2621 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002622 }
Steve Antondcc3c022017-12-22 16:02:54 -08002623 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002624 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002625 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002626 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002627 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002628 observer->OnTrack(transceiver);
2629 observer->OnAddTrack(transceiver->receiver(),
2630 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002631 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002632 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002633 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002634 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002635 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002636 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002637 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002638 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002639 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002640 }
Steve Antondcc3c022017-12-22 16:02:54 -08002641 }
2642
Henrik Boströmfdb92012017-11-09 19:55:44 +01002643 const cricket::ContentInfo* audio_content =
2644 GetFirstAudioContent(remote_description()->description());
2645 const cricket::ContentInfo* video_content =
2646 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002647 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002648 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002649 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002650 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002651 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002652 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002653
2654 // Check if the descriptions include streams, just in case the peer supports
2655 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002656 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002657 (audio_desc && !audio_desc->streams().empty()) ||
2658 (video_desc && !video_desc->streams().empty())) {
2659 remote_peer_supports_msid_ = true;
2660 }
deadbeefab9b2d12015-10-14 11:33:11 -07002661
2662 // We wait to signal new streams until we finish processing the description,
2663 // since only at that point will new streams have all their tracks.
2664 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2665
Steve Antondcc3c022017-12-22 16:02:54 -08002666 if (!IsUnifiedPlan()) {
2667 // TODO(steveanton): When removing RTP senders/receivers in response to a
2668 // rejected media section, there is some cleanup logic that expects the
2669 // voice/ video channel to still be set. But in this method the voice/video
2670 // channel would have been destroyed by the SetRemoteDescription caller
2671 // above so the cleanup that relies on them fails to run. The RemoveSenders
2672 // calls should be moved to right before the DestroyChannel calls to fix
2673 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002674
Steve Antondcc3c022017-12-22 16:02:54 -08002675 // Find all audio rtp streams and create corresponding remote AudioTracks
2676 // and MediaStreams.
2677 if (audio_content) {
2678 if (audio_content->rejected) {
2679 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2680 } else {
2681 bool default_audio_track_needed =
2682 !remote_peer_supports_msid_ &&
2683 RtpTransceiverDirectionHasSend(audio_desc->direction());
2684 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2685 default_audio_track_needed, audio_desc->type(),
2686 new_streams);
2687 }
deadbeeffaac4972015-11-12 15:33:07 -08002688 }
deadbeefab9b2d12015-10-14 11:33:11 -07002689
Steve Antondcc3c022017-12-22 16:02:54 -08002690 // Find all video rtp streams and create corresponding remote VideoTracks
2691 // and MediaStreams.
2692 if (video_content) {
2693 if (video_content->rejected) {
2694 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2695 } else {
2696 bool default_video_track_needed =
2697 !remote_peer_supports_msid_ &&
2698 RtpTransceiverDirectionHasSend(video_desc->direction());
2699 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2700 default_video_track_needed, video_desc->type(),
2701 new_streams);
2702 }
deadbeeffaac4972015-11-12 15:33:07 -08002703 }
deadbeefab9b2d12015-10-14 11:33:11 -07002704
Steve Antondcc3c022017-12-22 16:02:54 -08002705 // Update the DataChannels with the information from the remote peer.
2706 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002707 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002708 cricket::kMediaProtocolRtpPrefix)) {
2709 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2710 }
deadbeefab9b2d12015-10-14 11:33:11 -07002711 }
deadbeefab9b2d12015-10-14 11:33:11 -07002712
Steve Antondcc3c022017-12-22 16:02:54 -08002713 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002714 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002715 for (size_t i = 0; i < new_streams->count(); ++i) {
2716 MediaStreamInterface* new_stream = new_streams->at(i);
2717 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002718 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002719 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2720 }
deadbeefab9b2d12015-10-14 11:33:11 -07002721
Steve Antondcc3c022017-12-22 16:02:54 -08002722 UpdateEndedRemoteMediaStreams();
2723 }
deadbeefab9b2d12015-10-14 11:33:11 -07002724
Steve Anton8a006912017-12-04 15:25:56 -08002725 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002726}
2727
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002728void PeerConnection::SetAssociatedRemoteStreams(
2729 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2730 const std::vector<std::string>& stream_ids,
2731 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2732 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2733 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2734 for (const std::string& stream_id : stream_ids) {
2735 rtc::scoped_refptr<MediaStreamInterface> stream =
2736 remote_streams_->find(stream_id);
2737 if (!stream) {
2738 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2739 MediaStream::Create(stream_id));
2740 remote_streams_->AddStream(stream);
2741 added_streams->push_back(stream);
2742 }
2743 media_streams.push_back(stream);
2744 }
2745 // Special case: "a=msid" missing, use random stream ID.
2746 if (media_streams.empty() &&
2747 !(remote_description()->description()->msid_signaling() &
2748 cricket::kMsidSignalingMediaSection)) {
2749 if (!missing_msid_default_stream_) {
2750 missing_msid_default_stream_ = MediaStreamProxy::Create(
2751 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2752 added_streams->push_back(missing_msid_default_stream_);
2753 }
2754 media_streams.push_back(missing_msid_default_stream_);
2755 }
2756 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2757 receiver->streams();
2758 // SetStreams() will add/remove the receiver's track to/from the streams. This
2759 // differs from the spec - the spec uses an "addList" and "removeList" to
2760 // update the stream-track relationships in a later step. We do this earlier,
2761 // changing the order of things, but the end-result is the same.
2762 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2763 // instead. https://crbug.com/webrtc/9480
2764 receiver->SetStreams(media_streams);
2765 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2766}
2767
Steve Anton0f5400a2018-07-17 14:25:36 -07002768void PeerConnection::ProcessRemovalOfRemoteTrack(
2769 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2770 transceiver,
2771 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2772 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2773 RTC_DCHECK(transceiver->mid());
2774 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2775 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002776 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002777 transceiver->internal()->receiver_internal()->streams();
2778 // This will remove the remote track from the streams.
2779 transceiver->internal()->receiver_internal()->set_stream_ids({});
2780 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002781 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2782}
2783
2784void PeerConnection::RemoveRemoteStreamsIfEmpty(
2785 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2786 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2787 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2788 // streams, see if the stream was removed by checking if this was the last
2789 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002790 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002791 if (remote_stream->GetAudioTracks().empty() &&
2792 remote_stream->GetVideoTracks().empty()) {
2793 remote_streams_->RemoveStream(remote_stream);
2794 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002795 }
2796 }
2797}
2798
Steve Antondcc3c022017-12-22 16:02:54 -08002799RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2800 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002801 const SessionDescriptionInterface& new_session,
2802 const SessionDescriptionInterface* old_local_description,
2803 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002804 RTC_DCHECK(IsUnifiedPlan());
2805
Steve Anton7464fca2018-01-19 11:10:37 -08002806 const cricket::ContentGroup* bundle_group = nullptr;
2807 if (new_session.GetType() == SdpType::kOffer) {
2808 auto bundle_group_or_error =
2809 GetEarlyBundleGroup(*new_session.description());
2810 if (!bundle_group_or_error.ok()) {
2811 return bundle_group_or_error.MoveError();
2812 }
2813 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002814 }
Steve Antondcc3c022017-12-22 16:02:54 -08002815
Steve Antondcc3c022017-12-22 16:02:54 -08002816 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002817 for (size_t i = 0; i < new_contents.size(); ++i) {
2818 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002819 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002820 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002821 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2822 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002823 const cricket::ContentInfo* old_local_content = nullptr;
2824 if (old_local_description &&
2825 i < old_local_description->description()->contents().size()) {
2826 old_local_content =
2827 &old_local_description->description()->contents()[i];
2828 }
2829 const cricket::ContentInfo* old_remote_content = nullptr;
2830 if (old_remote_description &&
2831 i < old_remote_description->description()->contents().size()) {
2832 old_remote_content =
2833 &old_remote_description->description()->contents()[i];
2834 }
Steve Antondcc3c022017-12-22 16:02:54 -08002835 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002836 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2837 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002838 if (!transceiver_or_error.ok()) {
2839 return transceiver_or_error.MoveError();
2840 }
2841 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002842 RTCError error =
2843 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2844 if (!error.ok()) {
2845 return error;
2846 }
2847 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002848 if (GetDataMid() && new_content.name != *GetDataMid()) {
2849 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002850 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2851 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002852 continue;
2853 }
2854 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2855 if (!error.ok()) {
2856 return error;
2857 }
Steve Antondcc3c022017-12-22 16:02:54 -08002858 } else {
2859 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2860 "Unknown section type.");
2861 }
2862 }
2863
2864 return RTCError::OK();
2865}
2866
2867RTCError PeerConnection::UpdateTransceiverChannel(
2868 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2869 transceiver,
2870 const cricket::ContentInfo& content,
2871 const cricket::ContentGroup* bundle_group) {
2872 RTC_DCHECK(IsUnifiedPlan());
2873 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002874 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002875 if (content.rejected) {
2876 if (channel) {
2877 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002878 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002879 }
2880 } else {
2881 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002882 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002883 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002884 } else {
Steve Anton69470252018-02-09 11:43:08 -08002885 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002886 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002887 }
2888 if (!channel) {
2889 LOG_AND_RETURN_ERROR(
2890 RTCErrorType::INTERNAL_ERROR,
2891 "Failed to create channel for mid=" + content.name);
2892 }
2893 transceiver->internal()->SetChannel(channel);
2894 }
2895 }
2896 return RTCError::OK();
2897}
2898
Steve Antonfa2260d2017-12-28 16:38:23 -08002899RTCError PeerConnection::UpdateDataChannel(
2900 cricket::ContentSource source,
2901 const cricket::ContentInfo& content,
2902 const cricket::ContentGroup* bundle_group) {
2903 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002904 // If data channels are disabled, ignore this media section. CreateAnswer
2905 // will take care of rejecting it.
2906 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002907 }
2908 if (content.rejected) {
2909 DestroyDataChannel();
2910 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002911 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002912 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002913 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2914 "Failed to create data channel.");
2915 }
2916 }
2917 if (source == cricket::CS_REMOTE) {
2918 const MediaContentDescription* data_desc = content.media_description();
2919 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2920 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2921 }
2922 }
2923 }
2924 return RTCError::OK();
2925}
2926
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002927// This method will extract any send encodings that were sent by the remote
2928// connection. This is currently only relevant for Simulcast scenario (where
2929// the number of layers may be communicated by the server).
2930static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2931 const MediaContentDescription& desc) {
2932 if (!desc.HasSimulcast()) {
2933 return {};
2934 }
2935 std::vector<RtpEncodingParameters> result;
2936 const SimulcastDescription& simulcast = desc.simulcast_description();
2937
2938 // This is a remote description, the parameters we are after should appear
2939 // as receive streams.
2940 for (const auto& alternatives : simulcast.receive_layers()) {
2941 RTC_DCHECK(!alternatives.empty());
2942 // There is currently no way to specify or choose from alternatives.
2943 // We will always use the first alternative, which is the most preferred.
2944 const SimulcastLayer& layer = alternatives[0];
2945 RtpEncodingParameters parameters;
2946 parameters.rid = layer.rid;
2947 parameters.active = !layer.is_paused;
2948 result.push_back(parameters);
2949 }
2950
2951 return result;
2952}
2953
2954static RTCError UpdateSimulcastLayerStatusInSender(
2955 const std::vector<SimulcastLayer>& layers,
2956 RtpSenderInterface* sender) {
2957 RTC_DCHECK(sender);
2958 RtpParameters parameters = sender->GetParameters();
2959
2960 // The simulcast envelope cannot be changed, only the status of the streams.
2961 // So we will iterate over the send encodings rather than the layers.
2962 for (RtpEncodingParameters& encoding : parameters.encodings) {
2963 auto iter = std::find_if(layers.begin(), layers.end(),
2964 [&encoding](const SimulcastLayer& layer) {
2965 return layer.rid == encoding.rid;
2966 });
2967 // A layer that cannot be found may have been removed by the remote party.
2968 encoding.active = iter != layers.end() && !iter->is_paused;
2969 }
2970
2971 return sender->SetParameters(parameters);
2972}
2973
2974static RTCError DisableSimulcastInSender(RtpSenderInterface* sender) {
2975 RTC_DCHECK(sender);
2976 RtpParameters parameters = sender->GetParameters();
2977 if (parameters.encodings.empty()) {
2978 return RTCError::OK();
2979 }
2980
2981 bool first_layer_status = parameters.encodings[0].active;
2982 for (RtpEncodingParameters& encoding : parameters.encodings) {
2983 // TODO(bugs.webrtc.org/10251): Active does not really disable the layer.
2984 // The user might enable it at a later point in time even though it was
2985 // rejected.
2986 encoding.active = false;
2987 }
2988 parameters.encodings[0].active = first_layer_status;
2989
2990 return sender->SetParameters(parameters);
2991}
2992
Steve Antondcc3c022017-12-22 16:02:54 -08002993RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2994PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002995 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002996 size_t mline_index,
2997 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002998 const ContentInfo* old_local_content,
2999 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003000 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003001 // If this is an offer then the m= section might be recycled. If the m=
3002 // section is being recycled (defined as: rejected in the current local or
3003 // remote description and not rejected in new description), dissociate the
3004 // currently associated RtpTransceiver by setting its mid property to null,
3005 // and discard the mapping between the transceiver and its m= section index.
3006 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3007 old_remote_content)) {
3008 // We want to dissociate the transceiver that has the rejected mid.
3009 const std::string& old_mid =
3010 (old_local_content && old_local_content->rejected)
3011 ? old_local_content->name
3012 : old_remote_content->name;
3013 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003014 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003015 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3016 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003017 old_transceiver->internal()->set_mid(absl::nullopt);
3018 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003019 }
3020 }
3021 const MediaContentDescription* media_desc = content.media_description();
3022 auto transceiver = GetAssociatedTransceiver(content.name);
3023 if (source == cricket::CS_LOCAL) {
3024 // Find the RtpTransceiver that corresponds to this m= section, using the
3025 // mapping between transceivers and m= section indices established when
3026 // creating the offer.
3027 if (!transceiver) {
3028 transceiver = GetTransceiverByMLineIndex(mline_index);
3029 }
3030 if (!transceiver) {
3031 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3032 "Unknown transceiver");
3033 }
3034 } else {
3035 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3036 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3037 // of the same type...
3038 if (!transceiver &&
3039 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
3040 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3041 }
3042 // If no RtpTransceiver was found in the previous step, create one with a
3043 // recvonly direction.
3044 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003045 RTC_LOG(LS_INFO) << "Adding "
3046 << cricket::MediaTypeToString(media_desc->type())
3047 << " transceiver for MID=" << content.name
3048 << " at i=" << mline_index
3049 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003050 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003051 std::vector<RtpEncodingParameters> send_encodings =
3052 GetSendEncodingsFromRemoteDescription(*media_desc);
3053 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3054 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003055 std::string receiver_id;
3056 if (!media_desc->streams().empty()) {
3057 receiver_id = media_desc->streams()[0].id;
3058 } else {
3059 receiver_id = rtc::CreateRandomUuid();
3060 }
3061 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003062 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003063 transceiver->internal()->set_direction(
3064 RtpTransceiverDirection::kRecvOnly);
3065 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003066
3067 // Check if the offer indicated simulcast but the answer rejected it.
3068 // This can happen when simulcast is not supported on the remote party.
3069 // This check can be simplified to comparing the number of send encodings,
3070 // but that might break legacy implementation in which simulcast is not
3071 // signaled in the remote description.
3072 if (old_local_content && old_local_content->media_description() &&
3073 old_local_content->media_description()->HasSimulcast() &&
3074 !media_desc->HasSimulcast()) {
3075 RTCError error =
3076 DisableSimulcastInSender(transceiver->internal()->sender());
3077 if (!error.ok()) {
3078 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3079 return std::move(error);
3080 }
3081 }
Steve Antondcc3c022017-12-22 16:02:54 -08003082 }
3083 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003084 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003085 LOG_AND_RETURN_ERROR(
3086 RTCErrorType::INVALID_PARAMETER,
3087 "Transceiver type does not match media description type.");
3088 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003089 if (media_desc->HasSimulcast()) {
3090 std::vector<SimulcastLayer> layers =
3091 source == cricket::CS_LOCAL
3092 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3093 : media_desc->simulcast_description()
3094 .receive_layers()
3095 .GetAllLayers();
3096 RTCError error = UpdateSimulcastLayerStatusInSender(
3097 layers, transceiver->internal()->sender());
3098 if (!error.ok()) {
3099 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3100 return std::move(error);
3101 }
3102 }
Steve Antondcc3c022017-12-22 16:02:54 -08003103 // Associate the found or created RtpTransceiver with the m= section by
3104 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3105 // section, and establish a mapping between the transceiver and the index of
3106 // the m= section.
3107 transceiver->internal()->set_mid(content.name);
3108 transceiver->internal()->set_mline_index(mline_index);
3109 return std::move(transceiver);
3110}
3111
3112rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3113PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3114 RTC_DCHECK(IsUnifiedPlan());
3115 for (auto transceiver : transceivers_) {
3116 if (transceiver->mid() == mid) {
3117 return transceiver;
3118 }
3119 }
3120 return nullptr;
3121}
3122
3123rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3124PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3125 RTC_DCHECK(IsUnifiedPlan());
3126 for (auto transceiver : transceivers_) {
3127 if (transceiver->internal()->mline_index() == mline_index) {
3128 return transceiver;
3129 }
3130 }
3131 return nullptr;
3132}
3133
3134rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3135PeerConnection::FindAvailableTransceiverToReceive(
3136 cricket::MediaType media_type) const {
3137 RTC_DCHECK(IsUnifiedPlan());
3138 // From JSEP section 5.10 (Applying a Remote Description):
3139 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3140 // the same type that were added to the PeerConnection by addTrack and are not
3141 // associated with any m= section and are not stopped, find the first such
3142 // RtpTransceiver.
3143 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003144 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003145 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3146 !transceiver->stopped()) {
3147 return transceiver;
3148 }
3149 }
3150 return nullptr;
3151}
3152
Steve Antoned10bd92017-12-05 10:52:59 -08003153const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3154 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3155 transceiver,
3156 const SessionDescriptionInterface* sdesc) const {
3157 RTC_DCHECK(transceiver);
3158 RTC_DCHECK(sdesc);
3159 if (IsUnifiedPlan()) {
3160 if (!transceiver->internal()->mid()) {
3161 // This transceiver is not associated with a media section yet.
3162 return nullptr;
3163 }
3164 return sdesc->description()->GetContentByName(
3165 *transceiver->internal()->mid());
3166 } else {
3167 // Plan B only allows at most one audio and one video section, so use the
3168 // first media section of that type.
3169 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003170 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003171 }
3172}
3173
deadbeef46c73892016-11-16 19:42:04 -08003174PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3175 return configuration_;
3176}
3177
deadbeef293e9262017-01-11 12:28:30 -08003178bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3179 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003180 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003181 if (IsClosed()) {
3182 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3183 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3184 }
3185
Qingsi Wanga2d60672018-04-11 16:57:45 -07003186 // According to JSEP, after setLocalDescription, changing the candidate pool
3187 // size is not allowed, and changing the set of ICE servers will not result
3188 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003189 if (local_description() && configuration.ice_candidate_pool_size !=
3190 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003191 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3192 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003193 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003194 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003195
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003196 if (local_description() &&
3197 configuration.use_media_transport != configuration_.use_media_transport) {
3198 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3199 "SetLocalDescription.";
3200 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3201 }
3202
3203 if (remote_description() &&
3204 configuration.use_media_transport != configuration_.use_media_transport) {
3205 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3206 "SetRemoteDescription.";
3207 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3208 }
3209
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003210 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003211 configuration.use_media_transport_for_data_channels !=
3212 configuration_.use_media_transport_for_data_channels) {
3213 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3214 "after calling SetLocalDescription.";
3215 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3216 }
3217
3218 if (remote_description() &&
3219 configuration.use_media_transport_for_data_channels !=
3220 configuration_.use_media_transport_for_data_channels) {
3221 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3222 "after calling SetRemoteDescription.";
3223 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3224 }
3225
3226 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003227 configuration.crypto_options != configuration_.crypto_options) {
3228 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3229 "SetLocalDescription.";
3230 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3231 }
3232
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003233 if (configuration.use_media_transport_for_data_channels ||
3234 configuration.use_media_transport) {
3235 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3236 << "Media transport requires MaxBundle policy.";
3237 }
3238
deadbeef293e9262017-01-11 12:28:30 -08003239 // The simplest (and most future-compatible) way to tell if the config was
3240 // modified in an invalid way is to copy each property we do support
3241 // modifying, then use operator==. There are far more properties we don't
3242 // support modifying than those we do, and more could be added.
3243 RTCConfiguration modified_config = configuration_;
3244 modified_config.servers = configuration.servers;
3245 modified_config.type = configuration.type;
3246 modified_config.ice_candidate_pool_size =
3247 configuration.ice_candidate_pool_size;
3248 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003249 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003250 modified_config.ice_check_interval_strong_connectivity =
3251 configuration.ice_check_interval_strong_connectivity;
3252 modified_config.ice_check_interval_weak_connectivity =
3253 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003254 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3255 modified_config.ice_unwritable_min_checks =
3256 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003257 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003258 modified_config.stun_candidate_keepalive_interval =
3259 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003260 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003261 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003262 modified_config.active_reset_srtp_params =
3263 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003264 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003265 modified_config.use_media_transport_for_data_channels =
3266 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003267 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003268 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003269 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3270 }
3271
Steve Anton038834f2017-07-14 15:59:59 -07003272 // Validate the modified configuration.
3273 RTCError validate_error = ValidateConfiguration(modified_config);
3274 if (!validate_error.ok()) {
3275 return SafeSetError(std::move(validate_error), error);
3276 }
3277
deadbeef293e9262017-01-11 12:28:30 -08003278 // Note that this isn't possible through chromium, since it's an unsigned
3279 // short in WebIDL.
3280 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003281 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003282 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3283 }
3284
3285 // Parse ICE servers before hopping to network thread.
3286 cricket::ServerAddresses stun_servers;
3287 std::vector<cricket::RelayServerConfig> turn_servers;
3288 RTCErrorType parse_error =
3289 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3290 if (parse_error != RTCErrorType::NONE) {
3291 return SafeSetError(parse_error, error);
3292 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003293 // Note if STUN or TURN servers were supplied.
3294 if (!stun_servers.empty()) {
3295 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3296 }
3297 if (!turn_servers.empty()) {
3298 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3299 }
deadbeef293e9262017-01-11 12:28:30 -08003300
3301 // In theory this shouldn't fail.
3302 if (!network_thread()->Invoke<bool>(
3303 RTC_FROM_HERE,
3304 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3305 stun_servers, turn_servers, modified_config.type,
3306 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003307 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003308 modified_config.turn_customizer,
3309 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003310 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003311 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3312 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003313
deadbeefd1a38b52016-12-10 13:15:33 -08003314 // As described in JSEP, calling setConfiguration with new ICE servers or
3315 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3316 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003317 if (modified_config.servers != configuration_.servers ||
3318 modified_config.type != configuration_.type ||
3319 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003320 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003321 }
skvladd1f5fda2017-02-03 16:54:05 -08003322
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003323 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003324 transport_controller_->SetMediaTransportSettings(
3325 modified_config.use_media_transport,
3326 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003327
Zhi Huangb57e1692018-06-12 11:41:11 -07003328 if (configuration_.active_reset_srtp_params !=
3329 modified_config.active_reset_srtp_params) {
3330 transport_controller_->SetActiveResetSrtpParams(
3331 modified_config.active_reset_srtp_params);
3332 }
3333
deadbeef293e9262017-01-11 12:28:30 -08003334 configuration_ = modified_config;
3335 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003336}
3337
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003338bool PeerConnection::AddIceCandidate(
3339 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003340 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003341 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003342 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003343 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003344 return false;
3345 }
Steve Antond25da372017-11-06 14:50:29 -08003346
3347 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003348 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003349 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003350 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003351 return false;
3352 }
3353
3354 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003355 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003356 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003357 return false;
3358 }
3359
3360 bool valid = false;
3361 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3362 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003363 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003364 return false;
3365 }
3366
3367 // Add this candidate to the remote session description.
3368 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003369 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003370 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003371 return false;
3372 }
3373
3374 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003375 bool result = UseCandidate(ice_candidate);
3376 if (result) {
3377 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3378 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3379 } else {
3380 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3381 }
3382 return result;
Steve Antond25da372017-11-06 14:50:29 -08003383 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003384 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003385 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003386 return true;
3387 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003388}
3389
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003390bool PeerConnection::RemoveIceCandidates(
3391 const std::vector<cricket::Candidate>& candidates) {
3392 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003393 if (IsClosed()) {
3394 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3395 return false;
3396 }
3397
Steve Antond25da372017-11-06 14:50:29 -08003398 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003399 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3400 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003401 return false;
3402 }
3403
3404 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003405 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003406 return false;
3407 }
3408
3409 size_t number_removed =
3410 mutable_remote_description()->RemoveCandidates(candidates);
3411 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003412 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003413 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003414 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003415 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003416 }
3417
3418 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003419 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3420 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003421 RTC_LOG(LS_ERROR)
3422 << "RemoveIceCandidates: Error when removing remote candidates: "
3423 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003424 }
3425 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003426}
3427
Niels Möller0c4f7be2018-05-07 14:01:37 +02003428RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003429 if (!worker_thread()->IsCurrent()) {
3430 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003431 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003432 }
3433
Niels Möller0c4f7be2018-05-07 14:01:37 +02003434 const bool has_min = bitrate.min_bitrate_bps.has_value();
3435 const bool has_start = bitrate.start_bitrate_bps.has_value();
3436 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003437 if (has_min && *bitrate.min_bitrate_bps < 0) {
3438 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3439 "min_bitrate_bps <= 0");
3440 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003441 if (has_start) {
3442 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003443 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003444 "start_bitrate_bps < min_bitrate_bps");
3445 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003446 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3447 "curent_bitrate_bps < 0");
3448 }
3449 }
3450 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003451 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003452 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003453 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003454 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3455 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3456 "max_bitrate_bps < min_bitrate_bps");
3457 } else if (*bitrate.max_bitrate_bps < 0) {
3458 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3459 "max_bitrate_bps < 0");
3460 }
3461 }
3462
zstein4b979802017-06-02 14:37:37 -07003463 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003464 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003465
3466 return RTCError::OK();
3467}
3468
Alex Narest78609d52017-10-20 10:37:47 +02003469void PeerConnection::SetBitrateAllocationStrategy(
3470 std::unique_ptr<rtc::BitrateAllocationStrategy>
3471 bitrate_allocation_strategy) {
3472 rtc::Thread* worker_thread = factory_->worker_thread();
3473 if (!worker_thread->IsCurrent()) {
3474 rtc::BitrateAllocationStrategy* strategy_raw =
3475 bitrate_allocation_strategy.release();
3476 auto functor = [this, strategy_raw]() {
3477 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003478 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003479 };
3480 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3481 return;
3482 }
3483 RTC_DCHECK(call_.get());
3484 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3485}
3486
henrika5f6bf242017-11-01 11:06:56 +01003487void PeerConnection::SetAudioPlayout(bool playout) {
3488 if (!worker_thread()->IsCurrent()) {
3489 worker_thread()->Invoke<void>(
3490 RTC_FROM_HERE,
3491 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3492 return;
3493 }
3494 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003495 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003496 audio_state->SetPlayout(playout);
3497}
3498
3499void PeerConnection::SetAudioRecording(bool recording) {
3500 if (!worker_thread()->IsCurrent()) {
3501 worker_thread()->Invoke<void>(
3502 RTC_FROM_HERE,
3503 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3504 return;
3505 }
3506 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003507 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003508 audio_state->SetRecording(recording);
3509}
3510
Steve Anton8c0f7a72017-10-03 10:03:10 -07003511std::unique_ptr<rtc::SSLCertificate>
3512PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003513 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3514 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003515 return nullptr;
3516 }
Steve Antonf25303e2018-10-16 15:23:31 -07003517 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003518}
3519
Zhi Huang70b820f2018-01-27 14:16:15 -08003520std::unique_ptr<rtc::SSLCertChain>
3521PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003522 auto audio_transceiver = GetFirstAudioTransceiver();
3523 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003524 return nullptr;
3525 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003526 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003527 audio_transceiver->internal()->channel()->transport_name());
3528}
3529
3530rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3531PeerConnection::GetFirstAudioTransceiver() const {
3532 for (auto transceiver : transceivers_) {
3533 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3534 return transceiver;
3535 }
3536 }
3537 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003538}
3539
ivoc14d5dbe2016-07-04 07:06:55 -07003540bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3541 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003542 // TODO(eladalon): It would be better to not allow negative values into PC.
3543 const size_t max_size = (max_size_bytes < 0)
3544 ? RtcEventLog::kUnlimitedOutput
3545 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003546 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3547 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3548 output_period_ms = 5000;
3549 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003550 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003551 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003552 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003553}
3554
Bjorn Tereliusde939432017-11-20 17:38:14 +01003555bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3556 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003557 // TODO(eladalon): In C++14, this can be done with a lambda.
3558 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003559 bool operator()() {
3560 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3561 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003562 PeerConnection* const pc;
3563 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003564 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003565 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003566 return worker_thread()->Invoke<bool>(
3567 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003568}
3569
3570void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003571 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003572 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3573}
3574
Harald Alvestrandad88c882018-11-28 16:47:46 +01003575rtc::scoped_refptr<DtlsTransportInterface>
3576PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3577 return transport_controller_->LookupDtlsTransportByMid(mid);
3578}
3579
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003580rtc::scoped_refptr<DtlsTransport>
3581PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3582 return transport_controller_->LookupDtlsTransportByMid(mid);
3583}
3584
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003585const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003586 return pending_local_description_ ? pending_local_description_.get()
3587 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003588}
3589
3590const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003591 return pending_remote_description_ ? pending_remote_description_.get()
3592 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003593}
3594
deadbeeffe4a8a42016-12-20 17:56:17 -08003595const SessionDescriptionInterface* PeerConnection::current_local_description()
3596 const {
Steve Anton75737c02017-11-06 10:37:17 -08003597 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003598}
3599
3600const SessionDescriptionInterface* PeerConnection::current_remote_description()
3601 const {
Steve Anton75737c02017-11-06 10:37:17 -08003602 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003603}
3604
3605const SessionDescriptionInterface* PeerConnection::pending_local_description()
3606 const {
Steve Anton75737c02017-11-06 10:37:17 -08003607 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003608}
3609
3610const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3611 const {
Steve Anton75737c02017-11-06 10:37:17 -08003612 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003613}
3614
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003615void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003616 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003617 // Update stats here so that we have the most recent stats for tracks and
3618 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003619 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003620
Steve Anton75737c02017-11-06 10:37:17 -08003621 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003622 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003623
Mirko Bonadei739baf02019-01-27 17:29:42 +01003624 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003625 transceiver->Stop();
3626 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003627
3628 // Ensure that all asynchronous stats requests are completed before destroying
3629 // the transport controller below.
3630 if (stats_collector_) {
3631 stats_collector_->WaitForPendingRequest();
3632 }
3633
3634 // Don't destroy BaseChannels until after stats has been cleaned up so that
3635 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003636 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003637
Qingsi Wang93a84392018-01-30 17:13:09 -08003638 // The event log is used in the transport controller, which must be outlived
3639 // by the former. CreateOffer by the peer connection is implemented
3640 // asynchronously and if the peer connection is closed without resetting the
3641 // WebRTC session description factory, the session description factory would
3642 // call the transport controller.
3643 webrtc_session_desc_factory_.reset();
3644 transport_controller_.reset();
3645
deadbeef42a42632017-03-10 15:18:00 -08003646 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003647 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3648 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003649
Steve Anton978b8762017-09-29 12:15:02 -07003650 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003651 call_.reset();
3652 // The event log must outlive call (and any other object that uses it).
3653 event_log_.reset();
3654 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003655 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003656 // The .h file says that observer can be discarded after close() returns.
3657 // Make sure this is true.
3658 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003659}
3660
Steve Antonad182762018-09-05 20:22:40 +00003661void PeerConnection::OnMessage(rtc::Message* msg) {
3662 switch (msg->message_id) {
3663 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3664 SetSessionDescriptionMsg* param =
3665 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3666 param->observer->OnSuccess();
3667 delete param;
3668 break;
3669 }
3670 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3671 SetSessionDescriptionMsg* param =
3672 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3673 param->observer->OnFailure(std::move(param->error));
3674 delete param;
3675 break;
3676 }
3677 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3678 CreateSessionDescriptionMsg* param =
3679 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3680 param->observer->OnFailure(std::move(param->error));
3681 delete param;
3682 break;
3683 }
3684 case MSG_GETSTATS: {
3685 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3686 StatsReports reports;
3687 stats_->GetStats(param->track, &reports);
3688 param->observer->OnComplete(reports);
3689 delete param;
3690 break;
3691 }
3692 case MSG_FREE_DATACHANNELS: {
3693 sctp_data_channels_to_free_.clear();
3694 break;
3695 }
3696 case MSG_REPORT_USAGE_PATTERN: {
3697 ReportUsagePattern();
3698 break;
3699 }
3700 default:
3701 RTC_NOTREACHED() << "Not implemented";
3702 break;
3703 }
3704}
3705
Steve Antonafb0bb72018-02-20 11:35:37 -08003706cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3707 RTC_DCHECK(!IsUnifiedPlan());
3708 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3709 GetAudioTransceiver()->internal()->channel());
3710 if (voice_channel) {
3711 return voice_channel->media_channel();
3712 } else {
3713 return nullptr;
3714 }
3715}
3716
3717cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3718 RTC_DCHECK(!IsUnifiedPlan());
3719 auto* video_channel = static_cast<cricket::VideoChannel*>(
3720 GetVideoTransceiver()->internal()->channel());
3721 if (video_channel) {
3722 return video_channel->media_channel();
3723 } else {
3724 return nullptr;
3725 }
3726}
3727
Steve Anton4171afb2017-11-20 10:20:22 -08003728void PeerConnection::CreateAudioReceiver(
3729 MediaStreamInterface* stream,
3730 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003731 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3732 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003733 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3734 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003735 auto* audio_receiver = new AudioRtpReceiver(
3736 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003737 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003738 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3739 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3740 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003741 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003742 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003743 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003744}
3745
Steve Anton4171afb2017-11-20 10:20:22 -08003746void PeerConnection::CreateVideoReceiver(
3747 MediaStreamInterface* stream,
3748 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003749 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3750 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003751 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3752 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003753 auto* video_receiver = new VideoRtpReceiver(
3754 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003755 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003756 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3757 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3758 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003759 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003760 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003761 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003762}
3763
deadbeef70ab1a12015-09-28 16:53:55 -07003764// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3765// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003766rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003767 const RtpSenderInfo& remote_sender_info) {
3768 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3769 if (!receiver) {
3770 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3771 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003772 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003773 }
Steve Anton4171afb2017-11-20 10:20:22 -08003774 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3775 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3776 } else {
3777 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3778 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003779 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003780}
3781
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003782void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3783 MediaStreamInterface* stream) {
3784 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003785 RTC_DCHECK(track);
3786 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003787 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003788 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003789 // We already have a sender for this track, so just change the stream_id
3790 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003791 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003792 return;
3793 }
3794
3795 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003796 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003797 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003798 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003799 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003800 // If the sender has already been configured in SDP, we call SetSsrc,
3801 // which will connect the sender to the underlying transport. This can
3802 // occur if a local session description that contains the ID of the sender
3803 // is set before AddStream is called. It can also occur if the local
3804 // session description is not changed and RemoveStream is called, and
3805 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003806 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003807 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003808 if (sender_info) {
3809 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003810 }
3811}
3812
3813// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3814// indefinitely, when we have unified plan SDP.
3815void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3816 MediaStreamInterface* stream) {
3817 RTC_DCHECK(!IsClosed());
3818 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003819 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003820 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3821 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003822 return;
3823 }
Steve Anton4171afb2017-11-20 10:20:22 -08003824 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003825}
3826
3827void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3828 MediaStreamInterface* stream) {
3829 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003830 RTC_DCHECK(track);
3831 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003832 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003833 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003834 // We already have a sender for this track, so just change the stream_id
3835 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003836 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003837 return;
3838 }
3839
3840 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003841 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003842 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003843 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003844 GetVideoTransceiver()->internal()->AddSender(new_sender);
3845 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003846 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003847 if (sender_info) {
3848 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003849 }
3850}
3851
3852void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3853 MediaStreamInterface* stream) {
3854 RTC_DCHECK(!IsClosed());
3855 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003856 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003857 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3858 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003859 return;
3860 }
Steve Anton4171afb2017-11-20 10:20:22 -08003861 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003862}
3863
Steve Antonba818672017-11-06 10:21:57 -08003864void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003865 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003866 if (ice_connection_state_ == new_state) {
3867 return;
3868 }
3869
deadbeefcbecd352015-09-23 11:50:27 -07003870 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003871 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003872 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003873 return;
3874 }
Steve Antonba818672017-11-06 10:21:57 -08003875
Mirko Bonadei675513b2017-11-09 11:09:25 +01003876 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3877 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003878 RTC_DCHECK(ice_connection_state_ !=
3879 PeerConnectionInterface::kIceConnectionClosed);
3880
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003881 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003882 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003883}
3884
Alex Loiko9289eda2018-11-23 16:18:59 +00003885void PeerConnection::SetStandardizedIceConnectionState(
3886 PeerConnectionInterface::IceConnectionState new_state) {
3887 RTC_DCHECK(signaling_thread()->IsCurrent());
3888 if (standardized_ice_connection_state_ == new_state)
3889 return;
3890 if (IsClosed())
3891 return;
3892 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003893 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003894}
3895
Jonas Olsson635474e2018-10-18 15:58:17 +02003896void PeerConnection::SetConnectionState(
3897 PeerConnectionInterface::PeerConnectionState new_state) {
3898 RTC_DCHECK(signaling_thread()->IsCurrent());
3899 if (connection_state_ == new_state)
3900 return;
3901 if (IsClosed())
3902 return;
3903 connection_state_ = new_state;
3904 Observer()->OnConnectionChange(new_state);
3905}
3906
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003907void PeerConnection::OnIceGatheringChange(
3908 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003909 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003910 if (IsClosed()) {
3911 return;
3912 }
3913 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003914 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003915}
3916
jbauch81bf7b02017-03-25 08:31:12 -07003917void PeerConnection::OnIceCandidate(
3918 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003919 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003920 if (IsClosed()) {
3921 return;
3922 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003923 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003924 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3925 candidate->candidate().address().IsPrivateIP()) {
3926 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3927 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003928 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003929}
3930
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003931void PeerConnection::OnIceCandidatesRemoved(
3932 const std::vector<cricket::Candidate>& candidates) {
3933 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003934 if (IsClosed()) {
3935 return;
3936 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003937 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003938}
3939
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003940void PeerConnection::ChangeSignalingState(
3941 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003942 RTC_DCHECK(signaling_thread()->IsCurrent());
3943 if (signaling_state_ == signaling_state) {
3944 return;
3945 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003946 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3947 << GetSignalingStateString(signaling_state_)
3948 << " New state: "
3949 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003950 signaling_state_ = signaling_state;
3951 if (signaling_state == kClosed) {
3952 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003953 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003954 standardized_ice_connection_state_ =
3955 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003956 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3957 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003958 if (ice_gathering_state_ != kIceGatheringComplete) {
3959 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003960 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003961 }
3962 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003963 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003964}
3965
deadbeefeb459812015-12-15 19:24:43 -08003966void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3967 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003968 if (IsClosed()) {
3969 return;
3970 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003971 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003972 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003973}
3974
deadbeefeb459812015-12-15 19:24:43 -08003975void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3976 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003977 if (IsClosed()) {
3978 return;
3979 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003980 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003981 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003982}
3983
3984void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3985 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003986 if (IsClosed()) {
3987 return;
3988 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003989 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003990 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003991}
3992
3993void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3994 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003995 if (IsClosed()) {
3996 return;
3997 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003998 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003999 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004000}
4001
Henrik Boström31638672017-11-23 17:48:32 +01004002void PeerConnection::PostSetSessionDescriptionSuccess(
4003 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004004 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4005 signaling_thread()->Post(RTC_FROM_HERE, this,
4006 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004007}
4008
deadbeefab9b2d12015-10-14 11:33:11 -07004009void PeerConnection::PostSetSessionDescriptionFailure(
4010 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004011 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004012 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004013 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4014 msg->error = std::move(error);
4015 signaling_thread()->Post(RTC_FROM_HERE, this,
4016 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004017}
4018
4019void PeerConnection::PostCreateSessionDescriptionFailure(
4020 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004021 RTCError error) {
4022 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004023 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4024 msg->error = std::move(error);
4025 signaling_thread()->Post(RTC_FROM_HERE, this,
4026 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004027}
4028
zhihuang1c378ed2017-08-17 14:10:50 -07004029void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004030 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004031 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004032 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004033
Steve Antondcc3c022017-12-22 16:02:54 -08004034 if (IsUnifiedPlan()) {
4035 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4036 } else {
4037 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4038 }
4039
Steve Antonfa2260d2017-12-28 16:38:23 -08004040 // Intentionally unset the data channel type for RTP data channel with the
4041 // second condition. Otherwise the RTP data channels would be successfully
4042 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4043 // when building with chromium. We want to leave RTP data channels broken, so
4044 // people won't try to use them.
4045 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4046 session_options->data_channel_type = data_channel_type();
4047 }
4048
Steve Antondcc3c022017-12-22 16:02:54 -08004049 // Apply ICE restart flag and renomination flag.
4050 for (auto& options : session_options->media_description_options) {
4051 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4052 options.transport_options.enable_ice_renomination =
4053 configuration_.enable_ice_renomination;
4054 }
4055
4056 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004057 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004058 session_options->pooled_ice_credentials =
4059 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4060 RTC_FROM_HERE,
4061 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4062 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004063 session_options->offer_extmap_allow_mixed =
4064 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004065}
4066
4067void PeerConnection::GetOptionsForPlanBOffer(
4068 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4069 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004070 // Figure out transceiver directional preferences.
4071 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4072 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4073
4074 // By default, generate sendrecv/recvonly m= sections.
4075 bool recv_audio = true;
4076 bool recv_video = true;
4077
4078 // By default, only offer a new m= section if we have media to send with it.
4079 bool offer_new_audio_description = send_audio;
4080 bool offer_new_video_description = send_video;
4081 bool offer_new_data_description = HasDataChannels();
4082
4083 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004084 if (offer_answer_options.offer_to_receive_audio !=
4085 RTCOfferAnswerOptions::kUndefined) {
4086 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004087 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004088 offer_new_audio_description ||
4089 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004090 }
Steve Antondcc3c022017-12-22 16:02:54 -08004091 if (offer_answer_options.offer_to_receive_video !=
4092 RTCOfferAnswerOptions::kUndefined) {
4093 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004094 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004095 offer_new_video_description ||
4096 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004097 }
4098
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004099 absl::optional<size_t> audio_index;
4100 absl::optional<size_t> video_index;
4101 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004102 // If a current description exists, generate m= sections in the same order,
4103 // using the first audio/video/data section that appears and rejecting
4104 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004105 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004106 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004107 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004108 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4109 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4110 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004111 }
4112
zhihuang1c378ed2017-08-17 14:10:50 -07004113 // Add audio/video/data m= sections to the end if needed.
4114 if (!audio_index && offer_new_audio_description) {
4115 session_options->media_description_options.push_back(
4116 cricket::MediaDescriptionOptions(
4117 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004118 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4119 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004120 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004121 }
zhihuang1c378ed2017-08-17 14:10:50 -07004122 if (!video_index && offer_new_video_description) {
4123 session_options->media_description_options.push_back(
4124 cricket::MediaDescriptionOptions(
4125 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004126 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4127 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004128 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004129 }
zhihuang1c378ed2017-08-17 14:10:50 -07004130 if (!data_index && offer_new_data_description) {
4131 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004132 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004133 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004134 }
4135
4136 cricket::MediaDescriptionOptions* audio_media_description_options =
4137 !audio_index ? nullptr
4138 : &session_options->media_description_options[*audio_index];
4139 cricket::MediaDescriptionOptions* video_media_description_options =
4140 !video_index ? nullptr
4141 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004142
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004143 AddPlanBRtpSenderOptions(GetSendersInternal(),
4144 audio_media_description_options,
4145 video_media_description_options,
4146 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004147}
4148
Steve Antondcc3c022017-12-22 16:02:54 -08004149static cricket::MediaDescriptionOptions
4150GetMediaDescriptionOptionsForTransceiver(
4151 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4152 transceiver,
4153 const std::string& mid) {
4154 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004155 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004156 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004157 // This behavior is specified in JSEP. The gist is that:
4158 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4159 // sendrecv.
4160 // 2. If the MSID is included, then it must be included in any subsequent
4161 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004162 if (transceiver->stopped() ||
4163 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4164 !transceiver->internal()->has_ever_been_used_to_send())) {
4165 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004166 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004167
4168 cricket::SenderOptions sender_options;
4169 sender_options.track_id = transceiver->sender()->id();
4170 sender_options.stream_ids = transceiver->sender()->stream_ids();
4171
4172 // The following sets up RIDs and Simulcast.
4173 // RIDs are included if Simulcast is requested or if any RID was specified.
4174 RtpParameters send_parameters = transceiver->sender()->GetParameters();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004175 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4176 send_parameters.encodings.end(),
4177 [](const RtpEncodingParameters& encoding) {
4178 return !encoding.rid.empty();
4179 });
4180
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004181 std::vector<RidDescription> send_rids;
4182 SimulcastLayerList send_layers;
4183 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4184 if (encoding.rid.empty()) {
4185 continue;
4186 }
4187 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4188 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4189 }
4190
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004191 if (has_rids) {
4192 sender_options.rids = send_rids;
4193 }
4194
4195 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004196 // When RIDs are configured, we must set num_sim_layers to 0 to.
4197 // Otherwise, num_sim_layers must be 1 because either there is no
4198 // simulcast, or simulcast is acheived by munging the SDP.
4199 sender_options.num_sim_layers = has_rids ? 0 : 1;
4200 media_description_options.sender_options.push_back(sender_options);
4201
Steve Antondcc3c022017-12-22 16:02:54 -08004202 return media_description_options;
4203}
4204
Steve Anton5c72e712018-12-10 14:25:30 -08004205// Returns the ContentInfo at mline index |i|, or null if none exists.
4206static const ContentInfo* GetContentByIndex(
4207 const SessionDescriptionInterface* sdesc,
4208 size_t i) {
4209 if (!sdesc) {
4210 return nullptr;
4211 }
4212 const ContentInfos& contents = sdesc->description()->contents();
4213 return (i < contents.size() ? &contents[i] : nullptr);
4214}
4215
Steve Antondcc3c022017-12-22 16:02:54 -08004216void PeerConnection::GetOptionsForUnifiedPlanOffer(
4217 const RTCOfferAnswerOptions& offer_answer_options,
4218 cricket::MediaSessionOptions* session_options) {
4219 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4220 // Offers) and 5.2.2 (Subsequent Offers).
4221 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4222 const ContentInfos& local_contents =
4223 (local_description() ? local_description()->description()->contents()
4224 : ContentInfos());
4225 const ContentInfos& remote_contents =
4226 (remote_description() ? remote_description()->description()->contents()
4227 : ContentInfos());
4228 // The mline indices that can be recycled. New transceivers should reuse these
4229 // slots first.
4230 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004231 // First, go through each media section that exists in either the local or
4232 // remote description and generate a media section in this offer for the
4233 // associated transceiver. If a media section can be recycled, generate a
4234 // default, rejected media section here that can be later overwritten.
4235 for (size_t i = 0;
4236 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4237 // Either |local_content| or |remote_content| is non-null.
4238 const ContentInfo* local_content =
4239 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004240 const ContentInfo* current_local_content =
4241 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004242 const ContentInfo* remote_content =
4243 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004244 const ContentInfo* current_remote_content =
4245 GetContentByIndex(current_remote_description(), i);
4246 bool had_been_rejected =
4247 (current_local_content && current_local_content->rejected) ||
4248 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004249 const std::string& mid =
4250 (local_content ? local_content->name : remote_content->name);
4251 cricket::MediaType media_type =
4252 (local_content ? local_content->media_description()->type()
4253 : remote_content->media_description()->type());
4254 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4255 media_type == cricket::MEDIA_TYPE_VIDEO) {
4256 auto transceiver = GetAssociatedTransceiver(mid);
4257 RTC_CHECK(transceiver);
4258 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004259 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004260 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004261 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004262 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4263 RtpTransceiverDirection::kInactive,
4264 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004265 recycleable_mline_indices.push(i);
4266 } else {
4267 session_options->media_description_options.push_back(
4268 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4269 // CreateOffer shouldn't really cause any state changes in
4270 // PeerConnection, but we need a way to match new transceivers to new
4271 // media sections in SetLocalDescription and JSEP specifies this is done
4272 // by recording the index of the media section generated for the
4273 // transceiver in the offer.
4274 transceiver->internal()->set_mline_index(i);
4275 }
4276 } else {
4277 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004278 RTC_CHECK(GetDataMid());
4279 if (had_been_rejected || mid != *GetDataMid()) {
4280 session_options->media_description_options.push_back(
4281 GetMediaDescriptionOptionsForRejectedData(mid));
4282 } else {
4283 session_options->media_description_options.push_back(
4284 GetMediaDescriptionOptionsForActiveData(mid));
4285 }
Steve Antondcc3c022017-12-22 16:02:54 -08004286 }
4287 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004288
Steve Antondcc3c022017-12-22 16:02:54 -08004289 // Next, look for transceivers that are newly added (that is, are not stopped
4290 // and not associated). Reuse media sections marked as recyclable first,
4291 // otherwise append to the end of the offer. New media sections should be
4292 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004293 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004294 if (transceiver->mid() || transceiver->stopped()) {
4295 continue;
4296 }
4297 size_t mline_index;
4298 if (!recycleable_mline_indices.empty()) {
4299 mline_index = recycleable_mline_indices.front();
4300 recycleable_mline_indices.pop();
4301 session_options->media_description_options[mline_index] =
4302 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004303 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004304 } else {
4305 mline_index = session_options->media_description_options.size();
4306 session_options->media_description_options.push_back(
4307 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004308 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004309 }
4310 // See comment above for why CreateOffer changes the transceiver's state.
4311 transceiver->internal()->set_mline_index(mline_index);
4312 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004313 // Lastly, add a m-section if we have local data channels and an m section
4314 // does not already exist.
4315 if (!GetDataMid() && HasDataChannels()) {
4316 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004317 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004318 }
Steve Antondcc3c022017-12-22 16:02:54 -08004319}
4320
4321void PeerConnection::GetOptionsForAnswer(
4322 const RTCOfferAnswerOptions& offer_answer_options,
4323 cricket::MediaSessionOptions* session_options) {
4324 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4325
4326 if (IsUnifiedPlan()) {
4327 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4328 } else {
4329 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4330 }
4331
Steve Antonfa2260d2017-12-28 16:38:23 -08004332 // Intentionally unset the data channel type for RTP data channel. Otherwise
4333 // the RTP data channels would be successfully negotiated by default and the
4334 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4335 // We want to leave RTP data channels broken, so people won't try to use them.
4336 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4337 session_options->data_channel_type = data_channel_type();
4338 }
4339
Steve Antondcc3c022017-12-22 16:02:54 -08004340 // Apply ICE renomination flag.
4341 for (auto& options : session_options->media_description_options) {
4342 options.transport_options.enable_ice_renomination =
4343 configuration_.enable_ice_renomination;
4344 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004345
4346 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004347 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004348 session_options->pooled_ice_credentials =
4349 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4350 RTC_FROM_HERE,
4351 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4352 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004353}
4354
Steve Antondcc3c022017-12-22 16:02:54 -08004355void PeerConnection::GetOptionsForPlanBAnswer(
4356 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004357 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004358 // Figure out transceiver directional preferences.
4359 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4360 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4361
4362 // By default, generate sendrecv/recvonly m= sections. The direction is also
4363 // restricted by the direction in the offer.
4364 bool recv_audio = true;
4365 bool recv_video = true;
4366
4367 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004368 if (offer_answer_options.offer_to_receive_audio !=
4369 RTCOfferAnswerOptions::kUndefined) {
4370 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004371 }
Steve Antondcc3c022017-12-22 16:02:54 -08004372 if (offer_answer_options.offer_to_receive_video !=
4373 RTCOfferAnswerOptions::kUndefined) {
4374 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004375 }
4376
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004377 absl::optional<size_t> audio_index;
4378 absl::optional<size_t> video_index;
4379 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004380
4381 // Generate m= sections that match those in the offer.
4382 // Note that mediasession.cc will handle intersection our preferred
4383 // direction with the offered direction.
4384 GenerateMediaDescriptionOptions(
4385 remote_description(),
4386 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4387 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4388 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004389
4390 cricket::MediaDescriptionOptions* audio_media_description_options =
4391 !audio_index ? nullptr
4392 : &session_options->media_description_options[*audio_index];
4393 cricket::MediaDescriptionOptions* video_media_description_options =
4394 !video_index ? nullptr
4395 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004396
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004397 AddPlanBRtpSenderOptions(GetSendersInternal(),
4398 audio_media_description_options,
4399 video_media_description_options,
4400 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004401}
zhihuangaf388472016-11-02 16:49:48 -07004402
Steve Antondcc3c022017-12-22 16:02:54 -08004403void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4404 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4405 cricket::MediaSessionOptions* session_options) {
4406 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4407 // Answers) and 5.3.2 (Subsequent Answers).
4408 RTC_DCHECK(remote_description());
4409 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4410 for (const ContentInfo& content :
4411 remote_description()->description()->contents()) {
4412 cricket::MediaType media_type = content.media_description()->type();
4413 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4414 media_type == cricket::MEDIA_TYPE_VIDEO) {
4415 auto transceiver = GetAssociatedTransceiver(content.name);
4416 RTC_CHECK(transceiver);
4417 session_options->media_description_options.push_back(
4418 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4419 } else {
4420 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004421 // Reject all data sections if data channels are disabled.
4422 // Reject a data section if it has already been rejected.
4423 // Reject all data sections except for the first one.
4424 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4425 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004426 session_options->media_description_options.push_back(
4427 GetMediaDescriptionOptionsForRejectedData(content.name));
4428 } else {
4429 session_options->media_description_options.push_back(
4430 GetMediaDescriptionOptionsForActiveData(content.name));
4431 }
Steve Antondcc3c022017-12-22 16:02:54 -08004432 }
4433 }
htaa2a49d92016-03-04 02:51:39 -08004434}
4435
zhihuang1c378ed2017-08-17 14:10:50 -07004436void PeerConnection::GenerateMediaDescriptionOptions(
4437 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004438 RtpTransceiverDirection audio_direction,
4439 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004440 absl::optional<size_t>* audio_index,
4441 absl::optional<size_t>* video_index,
4442 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004443 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004444 for (const cricket::ContentInfo& content :
4445 session_desc->description()->contents()) {
4446 if (IsAudioContent(&content)) {
4447 // If we already have an audio m= section, reject this extra one.
4448 if (*audio_index) {
4449 session_options->media_description_options.push_back(
4450 cricket::MediaDescriptionOptions(
4451 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004452 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004453 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004454 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004455 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004456 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4457 content.name, audio_direction,
4458 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004459 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004460 }
4461 } else if (IsVideoContent(&content)) {
4462 // If we already have an video m= section, reject this extra one.
4463 if (*video_index) {
4464 session_options->media_description_options.push_back(
4465 cricket::MediaDescriptionOptions(
4466 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004467 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004468 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004469 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004470 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004471 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4472 content.name, video_direction,
4473 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004474 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004475 }
4476 } else {
4477 RTC_DCHECK(IsDataContent(&content));
4478 // If we already have an data m= section, reject this extra one.
4479 if (*data_index) {
4480 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004481 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004482 } else {
4483 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004484 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004485 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004486 }
4487 }
htaa2a49d92016-03-04 02:51:39 -08004488 }
deadbeefab9b2d12015-10-14 11:33:11 -07004489}
4490
Steve Antonfa2260d2017-12-28 16:38:23 -08004491cricket::MediaDescriptionOptions
4492PeerConnection::GetMediaDescriptionOptionsForActiveData(
4493 const std::string& mid) const {
4494 // Direction for data sections is meaningless, but legacy endpoints might
4495 // expect sendrecv.
4496 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4497 RtpTransceiverDirection::kSendRecv,
4498 /*stopped=*/false);
4499 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4500 return options;
4501}
4502
4503cricket::MediaDescriptionOptions
4504PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4505 const std::string& mid) const {
4506 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4507 RtpTransceiverDirection::kInactive,
4508 /*stopped=*/true);
4509 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4510 return options;
4511}
4512
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004513absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004514 switch (data_channel_type_) {
4515 case cricket::DCT_RTP:
4516 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004517 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004518 }
4519 return rtp_data_channel_->content_name();
4520 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004521 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004522 case cricket::DCT_MEDIA_TRANSPORT:
4523 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004524 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004525 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004526 }
4527}
4528
Steve Anton4171afb2017-11-20 10:20:22 -08004529void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4530 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4531 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004532 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004533}
4534
Steve Anton4171afb2017-11-20 10:20:22 -08004535void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004536 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004537 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004538 cricket::MediaType media_type,
4539 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004540 RTC_DCHECK(!IsUnifiedPlan());
4541
Steve Anton4171afb2017-11-20 10:20:22 -08004542 std::vector<RtpSenderInfo>* current_senders =
4543 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004544
Steve Anton4171afb2017-11-20 10:20:22 -08004545 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004546 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004547 for (auto sender_it = current_senders->begin();
4548 sender_it != current_senders->end();
4549 /* incremented manually */) {
4550 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004551 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004552 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004553 std::string params_stream_id;
4554 if (params) {
4555 params_stream_id =
4556 (!params->first_stream_id().empty() ? params->first_stream_id()
4557 : kDefaultStreamId);
4558 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004559 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004560 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004561 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004562 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004563 sender_exists) {
4564 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004565 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004566 OnRemoteSenderRemoved(info, media_type);
4567 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004568 }
4569 }
4570
Steve Anton4171afb2017-11-20 10:20:22 -08004571 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004572 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004573 if (!params.has_ssrcs()) {
4574 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4575 // sender, this means it is coming from a Unified Plan endpoint,so we just
4576 // create a default.
4577 default_sender_needed = true;
4578 break;
4579 }
4580
Seth Hampson845e8782018-03-02 11:34:10 -08004581 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004582 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004583 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4584 // not supported in Plan B, we just take the first here and create the
4585 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004586 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004587 (!params.first_stream_id().empty() ? params.first_stream_id()
4588 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004589 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004590 uint32_t ssrc = params.first_ssrc();
4591
4592 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004593 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004594 if (!stream) {
4595 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004596 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004597 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004598 remote_streams_->AddStream(stream);
4599 new_streams->AddStream(stream);
4600 }
4601
Steve Anton4171afb2017-11-20 10:20:22 -08004602 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004603 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004604 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004605 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004606 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004607 }
4608 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004609
Steve Anton4171afb2017-11-20 10:20:22 -08004610 // Add default sender if necessary.
4611 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004612 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004613 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004614 if (!default_stream) {
4615 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004616 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004617 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004618 remote_streams_->AddStream(default_stream);
4619 new_streams->AddStream(default_stream);
4620 }
Steve Anton4171afb2017-11-20 10:20:22 -08004621 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4622 ? kDefaultAudioSenderId
4623 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004624 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004625 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004626 if (!default_sender_info) {
4627 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004628 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004629 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004630 }
4631 }
deadbeefab9b2d12015-10-14 11:33:11 -07004632}
4633
Steve Anton4171afb2017-11-20 10:20:22 -08004634void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4635 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004636 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4637 << " receiver for track_id=" << sender_info.sender_id
4638 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004639
Steve Anton3d954a62018-04-02 11:27:23 -07004640 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004641 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004642 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004643 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004644 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004645 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004646 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004647 }
4648}
4649
Steve Anton4171afb2017-11-20 10:20:22 -08004650void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4651 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004652 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4653 << " receiver for track_id=" << sender_info.sender_id
4654 << " and stream_id=" << sender_info.stream_id;
4655
Seth Hampson845e8782018-03-02 11:34:10 -08004656 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004657
Henrik Boström933d8b02017-10-10 10:05:16 -07004658 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004659 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004660 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4661 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004662 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004663 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004664 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004665 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004666 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004667 }
4668 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004669 // Stopping or destroying a VideoRtpReceiver will end the
4670 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004671 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004672 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004673 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004674 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004675 // There's no guarantee the track is still available, e.g. the track may
4676 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004677 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004678 }
4679 } else {
nisseede5da42017-01-12 05:15:36 -08004680 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004681 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004682 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004683 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004684 }
deadbeefab9b2d12015-10-14 11:33:11 -07004685}
4686
4687void PeerConnection::UpdateEndedRemoteMediaStreams() {
4688 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4689 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4690 MediaStreamInterface* stream = remote_streams_->at(i);
4691 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4692 streams_to_remove.push_back(stream);
4693 }
4694 }
4695
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004696 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004697 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004698 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004699 }
4700}
4701
Steve Anton4171afb2017-11-20 10:20:22 -08004702void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004703 const std::vector<cricket::StreamParams>& streams,
4704 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004705 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004706
Seth Hampson845e8782018-03-02 11:34:10 -08004707 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004708 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004709 for (auto sender_it = current_senders->begin();
4710 sender_it != current_senders->end();
4711 /* incremented manually */) {
4712 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004713 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004714 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4715 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004716 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004717 OnLocalSenderRemoved(info, media_type);
4718 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004719 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004720 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004721 }
4722 }
4723
Steve Anton4171afb2017-11-20 10:20:22 -08004724 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004725 for (const cricket::StreamParams& params : streams) {
4726 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004727 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004728 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004729 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004730 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004731 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004732 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004733 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004734 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004735 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004736 }
4737 }
4738}
4739
Steve Anton4171afb2017-11-20 10:20:22 -08004740void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4741 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004742 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004743 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004744 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004745 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4746 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004747 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004748 return;
4749 }
4750
deadbeeffac06552015-11-25 11:26:01 -08004751 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004752 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004753 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004754 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004755 }
deadbeeffac06552015-11-25 11:26:01 -08004756
Seth Hampson5b4f0752018-04-02 16:31:36 -07004757 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004758 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004759}
4760
Steve Anton4171afb2017-11-20 10:20:22 -08004761void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4762 cricket::MediaType media_type) {
4763 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004764 if (!sender) {
4765 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004766 // SessionDescriptions has been renegotiated.
4767 return;
4768 }
deadbeeffac06552015-11-25 11:26:01 -08004769
4770 // A sender has been removed from the SessionDescription but it's still
4771 // associated with the PeerConnection. This only occurs if the SDP doesn't
4772 // match with the calls to CreateSender, AddStream and RemoveStream.
4773 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004774 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004775 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004776 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004777 }
deadbeeffac06552015-11-25 11:26:01 -08004778
Steve Anton4171afb2017-11-20 10:20:22 -08004779 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004780}
4781
4782void PeerConnection::UpdateLocalRtpDataChannels(
4783 const cricket::StreamParamsVec& streams) {
4784 std::vector<std::string> existing_channels;
4785
4786 // Find new and active data channels.
4787 for (const cricket::StreamParams& params : streams) {
4788 // |it->sync_label| is actually the data channel label. The reason is that
4789 // we use the same naming of data channels as we do for
4790 // MediaStreams and Tracks.
4791 // For MediaStreams, the sync_label is the MediaStream label and the
4792 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004793 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004794 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004795 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004796 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004797 continue;
4798 }
4799 // Set the SSRC the data channel should use for sending.
4800 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4801 existing_channels.push_back(data_channel_it->first);
4802 }
4803
4804 UpdateClosingRtpDataChannels(existing_channels, true);
4805}
4806
4807void PeerConnection::UpdateRemoteRtpDataChannels(
4808 const cricket::StreamParamsVec& streams) {
4809 std::vector<std::string> existing_channels;
4810
4811 // Find new and active data channels.
4812 for (const cricket::StreamParams& params : streams) {
4813 // The data channel label is either the mslabel or the SSRC if the mslabel
4814 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004815 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004816 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004817 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004818 auto data_channel_it = rtp_data_channels_.find(label);
4819 if (data_channel_it == rtp_data_channels_.end()) {
4820 // This is a new data channel.
4821 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4822 } else {
4823 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4824 }
4825 existing_channels.push_back(label);
4826 }
4827
4828 UpdateClosingRtpDataChannels(existing_channels, false);
4829}
4830
4831void PeerConnection::UpdateClosingRtpDataChannels(
4832 const std::vector<std::string>& active_channels,
4833 bool is_local_update) {
4834 auto it = rtp_data_channels_.begin();
4835 while (it != rtp_data_channels_.end()) {
4836 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004837 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004838 ++it;
4839 continue;
4840 }
4841
4842 if (is_local_update) {
4843 data_channel->SetSendSsrc(0);
4844 } else {
4845 data_channel->RemotePeerRequestClose();
4846 }
4847
4848 if (data_channel->state() == DataChannel::kClosed) {
4849 rtp_data_channels_.erase(it);
4850 it = rtp_data_channels_.begin();
4851 } else {
4852 ++it;
4853 }
4854 }
4855}
4856
4857void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4858 uint32_t remote_ssrc) {
4859 rtc::scoped_refptr<DataChannel> channel(
4860 InternalCreateDataChannel(label, nullptr));
4861 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004862 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004863 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004864 return;
4865 }
4866 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004867 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4868 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004869 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004870}
4871
4872rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4873 const std::string& label,
4874 const InternalDataChannelInit* config) {
4875 if (IsClosed()) {
4876 return nullptr;
4877 }
Steve Anton75737c02017-11-06 10:37:17 -08004878 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004879 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004880 << "InternalCreateDataChannel: Data is not supported in this call.";
4881 return nullptr;
4882 }
4883 InternalDataChannelInit new_config =
4884 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004885 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004886 if (new_config.id < 0) {
4887 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004888 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004889 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004890 RTC_LOG(LS_ERROR)
4891 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004892 return nullptr;
4893 }
4894 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004895 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004896 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004897 return nullptr;
4898 }
4899 }
4900
Steve Anton75737c02017-11-06 10:37:17 -08004901 rtc::scoped_refptr<DataChannel> channel(
4902 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004903 if (!channel) {
4904 sid_allocator_.ReleaseSid(new_config.id);
4905 return nullptr;
4906 }
4907
4908 if (channel->data_channel_type() == cricket::DCT_RTP) {
4909 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004910 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4911 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004912 return nullptr;
4913 }
4914 rtp_data_channels_[channel->label()] = channel;
4915 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004916 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004917 sctp_data_channels_.push_back(channel);
4918 channel->SignalClosed.connect(this,
4919 &PeerConnection::OnSctpDataChannelClosed);
4920 }
4921
Steve Anton2d8609c2018-01-23 16:38:46 -08004922 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004923 return channel;
4924}
4925
4926bool PeerConnection::HasDataChannels() const {
4927 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4928}
4929
4930void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4931 for (const auto& channel : sctp_data_channels_) {
4932 if (channel->id() < 0) {
4933 int sid;
4934 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004935 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004936 continue;
4937 }
4938 channel->SetSctpSid(sid);
4939 }
4940 }
4941}
4942
4943void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004944 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004945 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4946 ++it) {
4947 if (it->get() == channel) {
4948 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004949 // After the closing procedure is done, it's safe to use this ID for
4950 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004951 sid_allocator_.ReleaseSid(channel->id());
4952 }
deadbeefbd292462015-12-14 18:15:29 -08004953 // Since this method is triggered by a signal from the DataChannel,
4954 // we can't free it directly here; we need to free it asynchronously.
4955 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004956 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004957 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4958 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004959 return;
4960 }
4961 }
4962}
4963
deadbeefab9b2d12015-10-14 11:33:11 -07004964void PeerConnection::OnDataChannelDestroyed() {
4965 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4966 // DataChannel may callback to us and try to modify the list.
4967 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4968 temp_rtp_dcs.swap(rtp_data_channels_);
4969 for (const auto& kv : temp_rtp_dcs) {
4970 kv.second->OnTransportChannelDestroyed();
4971 }
4972
4973 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4974 temp_sctp_dcs.swap(sctp_data_channels_);
4975 for (const auto& channel : temp_sctp_dcs) {
4976 channel->OnTransportChannelDestroyed();
4977 }
4978}
4979
4980void PeerConnection::OnDataChannelOpenMessage(
4981 const std::string& label,
4982 const InternalDataChannelInit& config) {
4983 rtc::scoped_refptr<DataChannel> channel(
4984 InternalCreateDataChannel(label, &config));
4985 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004986 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004987 return;
4988 }
4989
deadbeefa601f5c2016-06-06 14:27:39 -07004990 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4991 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004992 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004993 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004994}
4995
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004996bool PeerConnection::HandleOpenMessage_s(
4997 const cricket::ReceiveDataParams& params,
4998 const rtc::CopyOnWriteBuffer& buffer) {
4999 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5000 // Received OPEN message; parse and signal that a new data channel should
5001 // be created.
5002 std::string label;
5003 InternalDataChannelInit config;
5004 config.id = params.ssrc;
5005 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5006 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5007 << params.ssrc;
5008 return true;
5009 }
5010 config.open_handshake_role = InternalDataChannelInit::kAcker;
5011 OnDataChannelOpenMessage(label, config);
5012 return true;
5013 }
5014 return false;
5015}
5016
Steve Anton4171afb2017-11-20 10:20:22 -08005017rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5018PeerConnection::GetAudioTransceiver() const {
5019 // This method only works with Plan B SDP, where there is a single
5020 // audio/video transceiver.
5021 RTC_DCHECK(!IsUnifiedPlan());
5022 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005023 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005024 return transceiver;
5025 }
5026 }
5027 RTC_NOTREACHED();
5028 return nullptr;
5029}
5030
5031rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5032PeerConnection::GetVideoTransceiver() const {
5033 // This method only works with Plan B SDP, where there is a single
5034 // audio/video transceiver.
5035 RTC_DCHECK(!IsUnifiedPlan());
5036 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005037 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005038 return transceiver;
5039 }
5040 }
5041 RTC_NOTREACHED();
5042 return nullptr;
5043}
5044
5045// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5046// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005047bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005048 switch (type) {
5049 case cricket::MEDIA_TYPE_AUDIO:
5050 return !GetAudioTransceiver()->internal()->senders().empty();
5051 case cricket::MEDIA_TYPE_VIDEO:
5052 return !GetVideoTransceiver()->internal()->senders().empty();
5053 case cricket::MEDIA_TYPE_DATA:
5054 return false;
5055 }
5056 RTC_NOTREACHED();
5057 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005058}
5059
Steve Anton4171afb2017-11-20 10:20:22 -08005060rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5061PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005062 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005063 for (auto sender : transceiver->internal()->senders()) {
5064 if (sender->track() == track) {
5065 return sender;
5066 }
5067 }
5068 }
5069 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005070}
5071
Steve Anton4171afb2017-11-20 10:20:22 -08005072rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5073PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005074 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005075 for (auto sender : transceiver->internal()->senders()) {
5076 if (sender->id() == sender_id) {
5077 return sender;
5078 }
5079 }
5080 }
5081 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005082}
5083
Steve Anton4171afb2017-11-20 10:20:22 -08005084rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5085PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005086 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005087 for (auto receiver : transceiver->internal()->receivers()) {
5088 if (receiver->id() == receiver_id) {
5089 return receiver;
5090 }
5091 }
5092 }
5093 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005094}
5095
Steve Anton4171afb2017-11-20 10:20:22 -08005096std::vector<PeerConnection::RtpSenderInfo>*
5097PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5098 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5099 media_type == cricket::MEDIA_TYPE_VIDEO);
5100 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5101 ? &remote_audio_sender_infos_
5102 : &remote_video_sender_infos_;
5103}
5104
5105std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005106 cricket::MediaType media_type) {
5107 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5108 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005109 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5110 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005111}
5112
Steve Anton4171afb2017-11-20 10:20:22 -08005113const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5114 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005115 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005116 const std::string sender_id) const {
5117 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005118 if (sender_info.stream_id == stream_id &&
5119 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005120 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005121 }
5122 }
5123 return nullptr;
5124}
5125
5126DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5127 for (const auto& channel : sctp_data_channels_) {
5128 if (channel->id() == sid) {
5129 return channel;
5130 }
5131 }
5132 return nullptr;
5133}
5134
deadbeef91dd5672016-05-18 16:55:30 -07005135bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005136 const cricket::ServerAddresses& stun_servers,
5137 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005138 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005139 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005140 // To handle both internal and externally created port allocator, we will
5141 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005142 port_allocator_flags_ = port_allocator_->flags();
5143 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5144 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5145 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005146 // If the disable-IPv6 flag was specified, we'll not override it
5147 // by experiment.
5148 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005149 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005150 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5151 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005152 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005153 }
5154
zhihuangb09b3f92017-03-07 14:40:51 -08005155 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005156 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005157 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005158 }
5159
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005160 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005161 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005162 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005163 }
5164
honghaiz60347052016-05-31 18:29:12 -07005165 if (configuration.candidate_network_policy ==
5166 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005167 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005168 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005169 }
5170
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005171 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005172 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005173 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5174 }
5175
Qingsi Wanga2d60672018-04-11 16:57:45 -07005176 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005177 // No step delay is used while allocating ports.
5178 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5179 port_allocator_->set_candidate_filter(
5180 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005181 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005182
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005183 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005184 for (auto& turn_server : turn_servers_copy) {
5185 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005186 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005187 // Call this last since it may create pooled allocator sessions using the
5188 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005189 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005190 stun_servers, std::move(turn_servers_copy),
5191 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5192 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005193 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005194 return true;
5195}
5196
deadbeef91dd5672016-05-18 16:55:30 -07005197bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005198 const cricket::ServerAddresses& stun_servers,
5199 const std::vector<cricket::RelayServerConfig>& turn_servers,
5200 IceTransportsType type,
5201 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005202 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005203 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005204 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005205 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005206 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005207 // According to JSEP, after setLocalDescription, changing the candidate pool
5208 // size is not allowed, and changing the set of ICE servers will not result
5209 // in new candidates being gathered.
5210 if (local_description()) {
5211 port_allocator_->FreezeCandidatePool();
5212 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005213 // Add the custom tls turn servers if they exist.
5214 auto turn_servers_copy = turn_servers;
5215 for (auto& turn_server : turn_servers_copy) {
5216 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5217 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005218 // Call this last since it may create pooled allocator sessions using the
5219 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005220 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005221 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5222 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005223}
5224
Steve Antonba818672017-11-06 10:21:57 -08005225cricket::ChannelManager* PeerConnection::channel_manager() const {
5226 return factory_->channel_manager();
5227}
5228
Elad Alon99c3fe52017-10-13 16:29:40 +02005229bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005230 std::unique_ptr<RtcEventLogOutput> output,
5231 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005232 if (!event_log_) {
5233 return false;
5234 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005235 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005236}
5237
5238void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005239 if (event_log_) {
5240 event_log_->StopLogging();
5241 }
ivoc14d5dbe2016-07-04 07:06:55 -07005242}
nisseeaabdf62017-05-05 02:23:02 -07005243
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005244cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005245 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005246 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005247 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005248 if (channel && channel->content_name() == content_name) {
5249 return channel;
5250 }
Steve Anton75737c02017-11-06 10:37:17 -08005251 }
5252 if (rtp_data_channel() &&
5253 rtp_data_channel()->content_name() == content_name) {
5254 return rtp_data_channel();
5255 }
5256 return nullptr;
5257}
5258
5259bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005260 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005261 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005262 RTC_LOG(LS_INFO)
5263 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005264 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005265 return false;
5266 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005267 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005268 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005269 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005270 return false;
5271 }
5272
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005273 absl::optional<rtc::SSLRole> dtls_role;
5274 if (sctp_mid_) {
5275 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5276 } else if (is_caller_) {
5277 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5278 }
Zhi Huange830e682018-03-30 10:48:35 -07005279 if (dtls_role) {
5280 *role = *dtls_role;
5281 return true;
5282 }
5283 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005284}
5285
5286bool PeerConnection::GetSslRole(const std::string& content_name,
5287 rtc::SSLRole* role) {
5288 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005289 RTC_LOG(LS_INFO)
5290 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005291 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005292 return false;
5293 }
5294
Zhi Huange830e682018-03-30 10:48:35 -07005295 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5296 if (dtls_role) {
5297 *role = *dtls_role;
5298 return true;
5299 }
5300 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005301}
5302
Steve Antonf8470812017-12-04 10:46:21 -08005303void PeerConnection::SetSessionError(SessionError error,
5304 const std::string& error_desc) {
5305 RTC_DCHECK_RUN_ON(signaling_thread());
5306 if (error != session_error_) {
5307 session_error_ = error;
5308 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005309 }
5310}
5311
Zhi Huange830e682018-03-30 10:48:35 -07005312RTCError PeerConnection::UpdateSessionState(
5313 SdpType type,
5314 cricket::ContentSource source,
5315 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005316 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005317
5318 // If there's already a pending error then no state transition should happen.
5319 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005320 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005321
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005322 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005323 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005324 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005325 }
5326
5327 // Update the signaling state according to the specified state machine (see
5328 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005329 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005330 ChangeSignalingState(source == cricket::CS_LOCAL
5331 ? PeerConnectionInterface::kHaveLocalOffer
5332 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005333 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005334 ChangeSignalingState(source == cricket::CS_LOCAL
5335 ? PeerConnectionInterface::kHaveLocalPrAnswer
5336 : PeerConnectionInterface::kHaveRemotePrAnswer);
5337 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005338 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005339 ChangeSignalingState(PeerConnectionInterface::kStable);
5340 }
5341
5342 // Update internal objects according to the session description's media
5343 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005344 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005345 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005346 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005347 }
5348
Steve Anton8a006912017-12-04 15:25:56 -08005349 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005350}
5351
Steve Anton8a006912017-12-04 15:25:56 -08005352RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005353 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005354 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005355 const SessionDescriptionInterface* sdesc =
5356 (source == cricket::CS_LOCAL ? local_description()
5357 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005358 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005359
5360 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005361 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005362 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005363 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005364 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005365 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005366 continue;
5367 }
5368 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005369 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005370 if (!content_desc) {
5371 continue;
5372 }
5373 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005374 bool success = (source == cricket::CS_LOCAL)
5375 ? channel->SetLocalContent(content_desc, type, &error)
5376 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005377 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005378 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005379 }
5380 }
5381
5382 // If using the RtpDataChannel, push down the new SDP section for it too.
5383 if (rtp_data_channel_) {
5384 const ContentInfo* data_content =
5385 cricket::GetFirstDataContent(sdesc->description());
5386 if (data_content && !data_content->rejected) {
5387 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005388 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005389 if (data_desc) {
5390 std::string error;
5391 bool success =
5392 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005393 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005394 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005395 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005396 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005397 }
Steve Anton75737c02017-11-06 10:37:17 -08005398 }
5399 }
5400 }
Steve Antoned10bd92017-12-05 10:52:59 -08005401
Steve Anton75737c02017-11-06 10:37:17 -08005402 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5403 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5404 if (sctp_transport_ && local_description() && remote_description() &&
5405 cricket::GetFirstDataContent(local_description()->description()) &&
5406 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005407 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005408 RTC_FROM_HERE,
5409 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005410 if (!success) {
5411 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5412 "Failed to push down SCTP parameters.");
5413 }
Steve Anton75737c02017-11-06 10:37:17 -08005414 }
Steve Antoned10bd92017-12-05 10:52:59 -08005415
Steve Anton8a006912017-12-04 15:25:56 -08005416 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005417}
5418
5419bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5420 RTC_DCHECK(network_thread()->IsCurrent());
5421 RTC_DCHECK(local_description());
5422 RTC_DCHECK(remote_description());
5423 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5424 // When we support "max-message-size", that would also be pushed down here.
5425 return sctp_transport_->Start(
5426 GetSctpPort(local_description()->description()),
5427 GetSctpPort(remote_description()->description()));
5428}
5429
Steve Anton8a006912017-12-04 15:25:56 -08005430RTCError PeerConnection::PushdownTransportDescription(
5431 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005432 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005433 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005434
Zhi Huange830e682018-03-30 10:48:35 -07005435 if (source == cricket::CS_LOCAL) {
5436 const SessionDescriptionInterface* sdesc = local_description();
5437 RTC_DCHECK(sdesc);
5438 return transport_controller_->SetLocalDescription(type,
5439 sdesc->description());
5440 } else {
5441 const SessionDescriptionInterface* sdesc = remote_description();
5442 RTC_DCHECK(sdesc);
5443 return transport_controller_->SetRemoteDescription(type,
5444 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005445 }
Steve Anton75737c02017-11-06 10:37:17 -08005446}
5447
5448bool PeerConnection::GetTransportDescription(
5449 const SessionDescription* description,
5450 const std::string& content_name,
5451 cricket::TransportDescription* tdesc) {
5452 if (!description || !tdesc) {
5453 return false;
5454 }
5455 const TransportInfo* transport_info =
5456 description->GetTransportInfoByName(content_name);
5457 if (!transport_info) {
5458 return false;
5459 }
5460 *tdesc = transport_info->description;
5461 return true;
5462}
5463
Steve Anton75737c02017-11-06 10:37:17 -08005464cricket::IceConfig PeerConnection::ParseIceConfig(
5465 const PeerConnectionInterface::RTCConfiguration& config) const {
5466 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005467 switch (config.continual_gathering_policy) {
5468 case PeerConnectionInterface::GATHER_ONCE:
5469 gathering_policy = cricket::GATHER_ONCE;
5470 break;
5471 case PeerConnectionInterface::GATHER_CONTINUALLY:
5472 gathering_policy = cricket::GATHER_CONTINUALLY;
5473 break;
5474 default:
5475 RTC_NOTREACHED();
5476 gathering_policy = cricket::GATHER_ONCE;
5477 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005478
Steve Anton75737c02017-11-06 10:37:17 -08005479 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005480 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5481 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005482 ice_config.prioritize_most_likely_candidate_pairs =
5483 config.prioritize_most_likely_ice_candidate_pairs;
5484 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005485 RTCConfigurationToIceConfigOptionalInt(
5486 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005487 ice_config.continual_gathering_policy = gathering_policy;
5488 ice_config.presume_writable_when_fully_relayed =
5489 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005490 ice_config.ice_check_interval_strong_connectivity =
5491 config.ice_check_interval_strong_connectivity;
5492 ice_config.ice_check_interval_weak_connectivity =
5493 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005494 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005495 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5496 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005497 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005498 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005499 ice_config.regather_all_networks_interval_range =
5500 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005501 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005502 return ice_config;
5503}
5504
Steve Antona41959e2018-11-28 11:15:33 -08005505static absl::string_view GetTrackIdBySsrc(
5506 const SessionDescriptionInterface* session_description,
5507 uint32_t ssrc) {
5508 if (!session_description) {
5509 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005510 }
Steve Antona41959e2018-11-28 11:15:33 -08005511 for (const cricket::ContentInfo& content :
5512 session_description->description()->contents()) {
5513 const cricket::MediaContentDescription& media =
5514 *content.media_description();
5515 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5516 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5517 const cricket::StreamParams* stream_params =
5518 cricket::GetStreamBySsrc(media.streams(), ssrc);
5519 if (stream_params) {
5520 return stream_params->id;
5521 }
5522 }
5523 }
5524 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005525}
5526
Steve Antona41959e2018-11-28 11:15:33 -08005527absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5528 return GetTrackIdBySsrc(local_description(), ssrc);
5529}
5530
5531absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5532 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005533}
5534
5535bool PeerConnection::SendData(const cricket::SendDataParams& params,
5536 const rtc::CopyOnWriteBuffer& payload,
5537 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005538 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5539 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5540 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005541 return false;
5542 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005543 if (media_transport_) {
5544 SendDataParams send_params;
5545 send_params.type = ToWebrtcDataMessageType(params.type);
5546 send_params.ordered = params.ordered;
5547 if (params.max_rtx_count >= 0) {
5548 send_params.max_rtx_count = params.max_rtx_count;
5549 } else if (params.max_rtx_ms >= 0) {
5550 send_params.max_rtx_ms = params.max_rtx_ms;
5551 }
5552 return media_transport_->SendData(params.sid, send_params, payload).ok();
5553 }
Steve Anton75737c02017-11-06 10:37:17 -08005554 return rtp_data_channel_
5555 ? rtp_data_channel_->SendData(params, payload, result)
5556 : network_thread()->Invoke<bool>(
5557 RTC_FROM_HERE,
5558 Bind(&cricket::SctpTransportInternal::SendData,
5559 sctp_transport_.get(), params, payload, result));
5560}
5561
5562bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005563 RTC_DCHECK_RUN_ON(signaling_thread());
5564 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005565 // Don't log an error here, because DataChannels are expected to call
5566 // ConnectDataChannel in this state. It's the only way to initially tell
5567 // whether or not the underlying transport is ready.
5568 return false;
5569 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005570 if (media_transport_) {
5571 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5572 &DataChannel::OnChannelReady);
5573 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5574 &DataChannel::OnDataReceived);
5575 SignalMediaTransportChannelClosing_s.connect(
5576 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5577 SignalMediaTransportChannelClosed_s.connect(
5578 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5579 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005580 rtp_data_channel_->SignalReadyToSendData.connect(
5581 webrtc_data_channel, &DataChannel::OnChannelReady);
5582 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5583 &DataChannel::OnDataReceived);
5584 } else {
5585 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5586 &DataChannel::OnChannelReady);
5587 SignalSctpDataReceived.connect(webrtc_data_channel,
5588 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005589 SignalSctpClosingProcedureStartedRemotely.connect(
5590 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5591 SignalSctpClosingProcedureComplete.connect(
5592 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005593 }
5594 return true;
5595}
5596
5597void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005598 RTC_DCHECK_RUN_ON(signaling_thread());
5599 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005600 RTC_LOG(LS_ERROR)
5601 << "DisconnectDataChannel called when rtp_data_channel_ and "
5602 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005603 return;
5604 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005605 if (media_transport_) {
5606 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5607 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5608 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5609 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5610 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005611 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5612 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5613 } else {
5614 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5615 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005616 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5617 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005618 }
5619}
5620
5621void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005622 if (media_transport_) {
5623 // No-op. Media transport does not need to add streams.
5624 return;
5625 }
Steve Anton75737c02017-11-06 10:37:17 -08005626 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005627 RTC_LOG(LS_ERROR)
5628 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005629 return;
5630 }
5631 network_thread()->Invoke<void>(
5632 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5633 sctp_transport_.get(), sid));
5634}
5635
5636void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005637 if (media_transport_) {
5638 media_transport_->CloseChannel(sid);
5639 return;
5640 }
Steve Anton75737c02017-11-06 10:37:17 -08005641 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005642 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005643 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005644 return;
5645 }
5646 network_thread()->Invoke<void>(
5647 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5648 sctp_transport_.get(), sid));
5649}
5650
5651bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005652 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005653 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005654 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005655 sctp_ready_to_send_data_;
5656}
5657
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005658void PeerConnection::OnDataReceived(int channel_id,
5659 DataMessageType type,
5660 const rtc::CopyOnWriteBuffer& buffer) {
5661 cricket::ReceiveDataParams params;
5662 params.sid = channel_id;
5663 params.type = ToCricketDataMessageType(type);
5664 media_transport_invoker_->AsyncInvoke<void>(
5665 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5666 RTC_DCHECK_RUN_ON(signaling_thread());
5667 if (!HandleOpenMessage_s(params, buffer)) {
5668 SignalMediaTransportReceivedData_s(params, buffer);
5669 }
5670 });
5671}
5672
5673void PeerConnection::OnChannelClosing(int channel_id) {
5674 media_transport_invoker_->AsyncInvoke<void>(
5675 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5676 RTC_DCHECK_RUN_ON(signaling_thread());
5677 SignalMediaTransportChannelClosing_s(channel_id);
5678 });
5679}
5680
5681void PeerConnection::OnChannelClosed(int channel_id) {
5682 media_transport_invoker_->AsyncInvoke<void>(
5683 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5684 RTC_DCHECK_RUN_ON(signaling_thread());
5685 SignalMediaTransportChannelClosed_s(channel_id);
5686 });
5687}
5688
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005689absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005690 if (sctp_mid_ && transport_controller_) {
5691 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5692 if (dtls_transport) {
5693 return dtls_transport->transport_name();
5694 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005695 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005696 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005697 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005698}
5699
Qingsi Wang72a43a12018-02-20 16:03:18 -08005700cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5701 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005702 network_thread()->Invoke<void>(
5703 RTC_FROM_HERE,
5704 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5705 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005706 return candidate_states_list;
5707}
5708
Steve Anton5dfde182018-02-06 10:34:40 -08005709std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5710 const {
5711 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005712 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005713 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005714 if (channel) {
5715 transport_names_by_mid[channel->content_name()] =
5716 channel->transport_name();
5717 }
Steve Anton75737c02017-11-06 10:37:17 -08005718 }
Steve Anton5dfde182018-02-06 10:34:40 -08005719 if (rtp_data_channel_) {
5720 transport_names_by_mid[rtp_data_channel_->content_name()] =
5721 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005722 }
5723 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005724 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005725 RTC_DCHECK(transport_name);
5726 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005727 }
Steve Anton5dfde182018-02-06 10:34:40 -08005728 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005729}
5730
Steve Anton5dfde182018-02-06 10:34:40 -08005731std::map<std::string, cricket::TransportStats>
5732PeerConnection::GetTransportStatsByNames(
5733 const std::set<std::string>& transport_names) {
5734 if (!network_thread()->IsCurrent()) {
5735 return network_thread()
5736 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5737 RTC_FROM_HERE,
5738 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005739 }
Steve Anton5dfde182018-02-06 10:34:40 -08005740 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5741 for (const std::string& transport_name : transport_names) {
5742 cricket::TransportStats transport_stats;
5743 bool success =
5744 transport_controller_->GetStats(transport_name, &transport_stats);
5745 if (success) {
5746 transport_stats_by_name[transport_name] = std::move(transport_stats);
5747 } else {
5748 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5749 << transport_name;
5750 }
5751 }
5752 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005753}
5754
5755bool PeerConnection::GetLocalCertificate(
5756 const std::string& transport_name,
5757 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005758 if (!certificate) {
5759 return false;
5760 }
5761 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5762 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005763}
5764
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005765std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005766 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005767 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005768}
5769
5770cricket::DataChannelType PeerConnection::data_channel_type() const {
5771 return data_channel_type_;
5772}
5773
5774bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5775 return pending_ice_restarts_.find(content_name) !=
5776 pending_ice_restarts_.end();
5777}
5778
Steve Anton75737c02017-11-06 10:37:17 -08005779bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5780 return transport_controller_->NeedsIceRestart(content_name);
5781}
5782
5783void PeerConnection::OnCertificateReady(
5784 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5785 transport_controller_->SetLocalCertificate(certificate);
5786}
5787
5788void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005789 SetSessionError(SessionError::kTransport,
5790 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005791}
5792
Alex Loiko9289eda2018-11-23 16:18:59 +00005793void PeerConnection::OnTransportControllerConnectionState(
5794 cricket::IceConnectionState state) {
5795 switch (state) {
5796 case cricket::kIceConnectionConnecting:
5797 // If the current state is Connected or Completed, then there were
5798 // writable channels but now there are not, so the next state must
5799 // be Disconnected.
5800 // kIceConnectionConnecting is currently used as the default,
5801 // un-connected state by the TransportController, so its only use is
5802 // detecting disconnections.
5803 if (ice_connection_state_ ==
5804 PeerConnectionInterface::kIceConnectionConnected ||
5805 ice_connection_state_ ==
5806 PeerConnectionInterface::kIceConnectionCompleted) {
5807 SetIceConnectionState(
5808 PeerConnectionInterface::kIceConnectionDisconnected);
5809 }
5810 break;
5811 case cricket::kIceConnectionFailed:
5812 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5813 break;
5814 case cricket::kIceConnectionConnected:
5815 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5816 "all transports are writable.";
5817 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5818 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5819 break;
5820 case cricket::kIceConnectionCompleted:
5821 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5822 "all transports are complete.";
5823 if (ice_connection_state_ !=
5824 PeerConnectionInterface::kIceConnectionConnected) {
5825 // If jumping directly from "checking" to "connected",
5826 // signal "connected" first.
5827 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5828 }
5829 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5830 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5831 ReportTransportStats();
5832 break;
5833 default:
5834 RTC_NOTREACHED();
5835 }
5836}
5837
Steve Anton75737c02017-11-06 10:37:17 -08005838void PeerConnection::OnTransportControllerCandidatesGathered(
5839 const std::string& transport_name,
5840 const cricket::Candidates& candidates) {
5841 RTC_DCHECK(signaling_thread()->IsCurrent());
5842 int sdp_mline_index;
5843 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005844 RTC_LOG(LS_ERROR)
5845 << "OnTransportControllerCandidatesGathered: content name "
5846 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005847 return;
5848 }
5849
5850 for (cricket::Candidates::const_iterator citer = candidates.begin();
5851 citer != candidates.end(); ++citer) {
5852 // Use transport_name as the candidate media id.
5853 std::unique_ptr<JsepIceCandidate> candidate(
5854 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5855 if (local_description()) {
5856 mutable_local_description()->AddCandidate(candidate.get());
5857 }
5858 OnIceCandidate(std::move(candidate));
5859 }
5860}
5861
5862void PeerConnection::OnTransportControllerCandidatesRemoved(
5863 const std::vector<cricket::Candidate>& candidates) {
5864 RTC_DCHECK(signaling_thread()->IsCurrent());
5865 // Sanity check.
5866 for (const cricket::Candidate& candidate : candidates) {
5867 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005868 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005869 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005870 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005871 return;
5872 }
5873 }
5874
5875 if (local_description()) {
5876 mutable_local_description()->RemoveCandidates(candidates);
5877 }
5878 OnIceCandidatesRemoved(candidates);
5879}
5880
5881void PeerConnection::OnTransportControllerDtlsHandshakeError(
5882 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005883 RTC_HISTOGRAM_ENUMERATION(
5884 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5885 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005886}
5887
Steve Antoned10bd92017-12-05 10:52:59 -08005888void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005889 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005890 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005891 if (channel && !channel->enabled()) {
5892 channel->Enable(true);
5893 }
Steve Anton75737c02017-11-06 10:37:17 -08005894 }
5895
Steve Anton4171afb2017-11-20 10:20:22 -08005896 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005897 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005898 }
Steve Anton75737c02017-11-06 10:37:17 -08005899}
5900
5901// Returns the media index for a local ice candidate given the content name.
5902bool PeerConnection::GetLocalCandidateMediaIndex(
5903 const std::string& content_name,
5904 int* sdp_mline_index) {
5905 if (!local_description() || !sdp_mline_index) {
5906 return false;
5907 }
5908
5909 bool content_found = false;
5910 const ContentInfos& contents = local_description()->description()->contents();
5911 for (size_t index = 0; index < contents.size(); ++index) {
5912 if (contents[index].name == content_name) {
5913 *sdp_mline_index = static_cast<int>(index);
5914 content_found = true;
5915 break;
5916 }
5917 }
5918 return content_found;
5919}
5920
5921bool PeerConnection::UseCandidatesInSessionDescription(
5922 const SessionDescriptionInterface* remote_desc) {
5923 if (!remote_desc) {
5924 return true;
5925 }
5926 bool ret = true;
5927
5928 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5929 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5930 for (size_t n = 0; n < candidates->count(); ++n) {
5931 const IceCandidateInterface* candidate = candidates->at(n);
5932 bool valid = false;
5933 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5934 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005935 RTC_LOG(LS_INFO)
5936 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005937 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005938 }
5939 continue;
5940 }
5941 ret = UseCandidate(candidate);
5942 if (!ret) {
5943 break;
5944 }
5945 }
5946 }
5947 return ret;
5948}
5949
5950bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5951 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5952 size_t remote_content_size =
5953 remote_description()->description()->contents().size();
5954 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005955 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005956 return false;
5957 }
5958
5959 cricket::ContentInfo content =
5960 remote_description()->description()->contents()[mediacontent_index];
5961 std::vector<cricket::Candidate> candidates;
5962 candidates.push_back(candidate->candidate());
5963 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005964 RTCError error =
5965 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005966 if (error.ok()) {
5967 // Candidates successfully submitted for checking.
5968 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5969 ice_connection_state_ ==
5970 PeerConnectionInterface::kIceConnectionDisconnected) {
5971 // If state is New, then the session has just gotten its first remote ICE
5972 // candidates, so go to Checking.
5973 // If state is Disconnected, the session is re-using old candidates or
5974 // receiving additional ones, so go to Checking.
5975 // If state is Connected, stay Connected.
5976 // TODO(bemasc): If state is Connected, and the new candidates are for a
5977 // newly added transport, then the state actually _should_ move to
5978 // checking. Add a way to distinguish that case.
5979 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5980 }
5981 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005982 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005983 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005984 }
5985 return true;
5986}
5987
5988void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005989 // Destroy video channel first since it may have a pointer to the
5990 // voice channel.
5991 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005992 if (!video_info || video_info->rejected) {
5993 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005994 }
5995
Steve Anton6fec8802017-12-04 10:37:29 -08005996 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5997 if (!audio_info || audio_info->rejected) {
5998 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005999 }
6000
6001 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6002 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006003 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006004 }
6005}
6006
Steve Antondcc3c022017-12-22 16:02:54 -08006007RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6008 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006009 const cricket::ContentGroup* bundle_group = nullptr;
6010 if (configuration_.bundle_policy ==
6011 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006012 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006013 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006014 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6015 "max-bundle configured but session description "
6016 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006017 }
6018 }
Steve Antondcc3c022017-12-22 16:02:54 -08006019 return std::move(bundle_group);
6020}
6021
6022RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006023 // Creating the media channels. Transports should already have been created
6024 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006025 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006026 if (voice && !voice->rejected &&
6027 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006028 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006029 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006030 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6031 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006032 }
6033 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6034 }
6035
Steve Antondcc3c022017-12-22 16:02:54 -08006036 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006037 if (video && !video->rejected &&
6038 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006039 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006040 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006041 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6042 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006043 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006044 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006045 }
6046
Steve Antondcc3c022017-12-22 16:02:54 -08006047 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006048 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006049 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006050 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006051 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6052 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006053 }
6054 }
6055
Steve Anton8a006912017-12-04 15:25:56 -08006056 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006057}
6058
Steve Anton4171afb2017-11-20 10:20:22 -08006059// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006060cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006061 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006062 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006063 MediaTransportInterface* media_transport = nullptr;
6064 if (configuration_.use_media_transport) {
6065 media_transport = GetMediaTransport(mid);
6066 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006067
Steve Anton75737c02017-11-06 10:37:17 -08006068 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006069 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006070 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006071 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006072 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006073 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006074 }
Steve Anton75737c02017-11-06 10:37:17 -08006075 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6076 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006077 voice_channel->SignalSentPacket.connect(this,
6078 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006079 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006080
Steve Antoneda6ccd2017-12-04 10:21:55 -08006081 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006082}
6083
Steve Anton4171afb2017-11-20 10:20:22 -08006084// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006085cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006086 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006087 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006088 MediaTransportInterface* media_transport = nullptr;
6089 if (configuration_.use_media_transport) {
6090 media_transport = GetMediaTransport(mid);
6091 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006092
Steve Anton75737c02017-11-06 10:37:17 -08006093 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006094 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006095 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006096 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006097 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006098 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006099 }
Steve Anton75737c02017-11-06 10:37:17 -08006100 video_channel->SignalDtlsSrtpSetupFailure.connect(
6101 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006102 video_channel->SignalSentPacket.connect(this,
6103 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006104 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006105
Steve Antoneda6ccd2017-12-04 10:21:55 -08006106 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006107}
6108
Zhi Huange830e682018-03-30 10:48:35 -07006109bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006110 switch (data_channel_type_) {
6111 case cricket::DCT_MEDIA_TRANSPORT:
6112 if (network_thread()->Invoke<bool>(
6113 RTC_FROM_HERE,
6114 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6115 this, mid))) {
6116 for (const auto& channel : sctp_data_channels_) {
6117 channel->OnTransportChannelCreated();
6118 }
6119 return true;
6120 }
Steve Anton75737c02017-11-06 10:37:17 -08006121 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006122 case cricket::DCT_SCTP:
6123 if (!sctp_factory_) {
6124 RTC_LOG(LS_ERROR)
6125 << "Trying to create SCTP transport, but didn't compile with "
6126 "SCTP support (HAVE_SCTP)";
6127 return false;
6128 }
6129 if (!network_thread()->Invoke<bool>(
6130 RTC_FROM_HERE,
6131 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6132 return false;
6133 }
6134 for (const auto& channel : sctp_data_channels_) {
6135 channel->OnTransportChannelCreated();
6136 }
6137 return true;
6138 case cricket::DCT_RTP:
6139 default:
6140 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6141 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6142 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006143 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006144 if (!rtp_data_channel_) {
6145 return false;
6146 }
6147 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6148 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6149 rtp_data_channel_->SignalSentPacket.connect(
6150 this, &PeerConnection::OnSentPacket_w);
6151 rtp_data_channel_->SetRtpTransport(rtp_transport);
6152 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006153 }
6154
Steve Anton75737c02017-11-06 10:37:17 -08006155 return true;
6156}
6157
6158Call::Stats PeerConnection::GetCallStats() {
6159 if (!worker_thread()->IsCurrent()) {
6160 return worker_thread()->Invoke<Call::Stats>(
6161 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6162 }
6163 if (call_) {
6164 return call_->GetStats();
6165 } else {
6166 return Call::Stats();
6167 }
6168}
6169
Zhi Huange830e682018-03-30 10:48:35 -07006170bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006171 RTC_DCHECK(network_thread()->IsCurrent());
6172 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006173 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006174 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006175 RTC_DCHECK(dtls_transport);
6176 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006177 RTC_DCHECK(sctp_transport_);
6178 sctp_invoker_.reset(new rtc::AsyncInvoker());
6179 sctp_transport_->SignalReadyToSendData.connect(
6180 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6181 sctp_transport_->SignalDataReceived.connect(
6182 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006183 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6184 // another thread. Would be nice if there was a helper class similar to
6185 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6186 // code.
6187 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6188 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6189 sctp_transport_->SignalClosingProcedureComplete.connect(
6190 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006191 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006192 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006193 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006194}
6195
6196void PeerConnection::DestroySctpTransport_n() {
6197 RTC_DCHECK(network_thread()->IsCurrent());
6198 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006199 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006200 sctp_invoker_.reset(nullptr);
6201 sctp_ready_to_send_data_ = false;
6202}
6203
6204void PeerConnection::OnSctpTransportReadyToSendData_n() {
6205 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6206 RTC_DCHECK(network_thread()->IsCurrent());
6207 // Note: Cannot use rtc::Bind here because it will grab a reference to
6208 // PeerConnection and potentially cause PeerConnection to live longer than
6209 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6210 // be destroyed before PeerConnection is destroyed, and at that point all
6211 // pending tasks will be cleared.
6212 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6213 OnSctpTransportReadyToSendData_s(true);
6214 });
6215}
6216
6217void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6218 RTC_DCHECK(signaling_thread()->IsCurrent());
6219 sctp_ready_to_send_data_ = ready;
6220 SignalSctpReadyToSendData(ready);
6221}
6222
6223void PeerConnection::OnSctpTransportDataReceived_n(
6224 const cricket::ReceiveDataParams& params,
6225 const rtc::CopyOnWriteBuffer& payload) {
6226 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6227 RTC_DCHECK(network_thread()->IsCurrent());
6228 // Note: Cannot use rtc::Bind here because it will grab a reference to
6229 // PeerConnection and potentially cause PeerConnection to live longer than
6230 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6231 // be destroyed before PeerConnection is destroyed, and at that point all
6232 // pending tasks will be cleared.
6233 sctp_invoker_->AsyncInvoke<void>(
6234 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6235 OnSctpTransportDataReceived_s(params, payload);
6236 });
6237}
6238
6239void PeerConnection::OnSctpTransportDataReceived_s(
6240 const cricket::ReceiveDataParams& params,
6241 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006242 RTC_DCHECK_RUN_ON(signaling_thread());
6243 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006244 SignalSctpDataReceived(params, payload);
6245 }
6246}
6247
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006248void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006249 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6250 RTC_DCHECK(network_thread()->IsCurrent());
6251 sctp_invoker_->AsyncInvoke<void>(
6252 RTC_FROM_HERE, signaling_thread(),
6253 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006254 &SignalSctpClosingProcedureStartedRemotely, sid));
6255}
6256
6257void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6258 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6259 RTC_DCHECK(network_thread()->IsCurrent());
6260 sctp_invoker_->AsyncInvoke<void>(
6261 RTC_FROM_HERE, signaling_thread(),
6262 rtc::Bind(&sigslot::signal1<int>::operator(),
6263 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006264}
6265
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006266bool PeerConnection::SetupMediaTransportForDataChannels_n(
6267 const std::string& mid) {
6268 media_transport_ = transport_controller_->GetMediaTransport(mid);
6269 if (!media_transport_) {
6270 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6271 return false;
6272 }
6273
6274 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6275 media_transport_->SetDataSink(this);
6276 media_transport_data_mid_ = mid;
6277 transport_controller_->SignalMediaTransportStateChanged.connect(
6278 this, &PeerConnection::OnMediaTransportStateChanged_n);
6279 // Check the initial state right away, in case transport is already writable.
6280 OnMediaTransportStateChanged_n();
6281 return true;
6282}
6283
6284void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6285 if (!media_transport_) {
6286 return;
6287 }
6288 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6289 media_transport_data_mid_.reset();
6290 media_transport_->SetDataSink(nullptr);
6291 media_transport_invoker_ = nullptr;
6292 media_transport_ = nullptr;
6293}
6294
6295void PeerConnection::OnMediaTransportStateChanged_n() {
6296 if (!media_transport_data_mid_ ||
6297 transport_controller_->GetMediaTransportState(
6298 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6299 return;
6300 }
6301 media_transport_invoker_->AsyncInvoke<void>(
6302 RTC_FROM_HERE, signaling_thread(), [this] {
6303 RTC_DCHECK_RUN_ON(signaling_thread());
6304 media_transport_ready_to_send_data_ = true;
6305 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6306 });
6307}
6308
Steve Anton75737c02017-11-06 10:37:17 -08006309// Returns false if bundle is enabled and rtcp_mux is disabled.
6310bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6311 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6312 if (!bundle_enabled)
6313 return true;
6314
6315 const cricket::ContentGroup* bundle_group =
6316 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6317 RTC_DCHECK(bundle_group != NULL);
6318
6319 const cricket::ContentInfos& contents = desc->contents();
6320 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6321 citer != contents.end(); ++citer) {
6322 const cricket::ContentInfo* content = (&*citer);
6323 RTC_DCHECK(content != NULL);
6324 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006325 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006326 if (!HasRtcpMuxEnabled(content))
6327 return false;
6328 }
6329 }
6330 // RTCP-MUX is enabled in all the contents.
6331 return true;
6332}
6333
6334bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006335 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006336}
6337
Steve Anton06817cd2018-12-18 15:55:30 -08006338static RTCError ValidateMids(const cricket::SessionDescription& description) {
6339 std::set<std::string> mids;
6340 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006341 if (content.name.empty()) {
6342 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6343 "A media section is missing a MID attribute.");
6344 }
Steve Anton06817cd2018-12-18 15:55:30 -08006345 if (!mids.insert(content.name).second) {
6346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6347 "Duplicate a=mid value '" + content.name + "'.");
6348 }
6349 }
6350 return RTCError::OK();
6351}
6352
Steve Anton8a006912017-12-04 15:25:56 -08006353RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006354 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006355 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006356 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006357 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006358 }
6359
6360 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006362 }
6363
Steve Anton3828c062017-12-06 10:34:51 -08006364 SdpType type = sdesc->GetType();
6365 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6366 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006367 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006368 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006369 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006370 }
6371
Steve Anton06817cd2018-12-18 15:55:30 -08006372 RTCError error = ValidateMids(*sdesc->description());
6373 if (!error.ok()) {
6374 return error;
6375 }
6376
Steve Anton75737c02017-11-06 10:37:17 -08006377 // Verify crypto settings.
6378 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006379 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6380 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006381 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006382 if (!crypto_error.ok()) {
6383 return crypto_error;
6384 }
Steve Anton75737c02017-11-06 10:37:17 -08006385 }
6386
6387 // Verify ice-ufrag and ice-pwd.
6388 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006389 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6390 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006391 }
6392
6393 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006394 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6395 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006396 }
6397
6398 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6399 // m-lines that do not rtcp-mux enabled.
6400
6401 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006402 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006403 // With an answer we want to compare the new answer session description with
6404 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006405 const cricket::SessionDescription* offer_desc =
6406 (source == cricket::CS_LOCAL) ? remote_description()->description()
6407 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006408 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6409 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6410 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006411 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6412 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006413 }
6414 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006415 // The re-offers should respect the order of m= sections in current
6416 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006417 // With a re-offer, either the current local or current remote descriptions
6418 // could be the most up to date, so we would like to check against both of
6419 // them if they exist. It could be the case that one of them has a 0 port
6420 // for a media section, but the other does not. This is important to check
6421 // against in the case that we are recycling an m= section.
6422 const cricket::SessionDescription* current_desc = nullptr;
6423 const cricket::SessionDescription* secondary_current_desc = nullptr;
6424 if (local_description()) {
6425 current_desc = local_description()->description();
6426 if (remote_description()) {
6427 secondary_current_desc = remote_description()->description();
6428 }
6429 } else if (remote_description()) {
6430 current_desc = remote_description()->description();
6431 }
Steve Anton75737c02017-11-06 10:37:17 -08006432 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006433 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6434 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006435 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6436 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006437 }
6438 }
6439
Steve Antonba42e992018-04-09 14:10:01 -07006440 if (IsUnifiedPlan()) {
6441 // Ensure that each audio and video media section has at most one
6442 // "StreamParams". This will return an error if receiving a session
6443 // description from a "Plan B" endpoint which adds multiple tracks of the
6444 // same type. With Unified Plan, there can only be at most one track per
6445 // media section.
6446 for (const ContentInfo& content : sdesc->description()->contents()) {
6447 const MediaContentDescription& desc = *content.description;
6448 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6449 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6450 desc.streams().size() > 1u) {
6451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6452 "Media section has more than one track specified "
6453 "with a=ssrc lines which is not supported with "
6454 "Unified Plan.");
6455 }
6456 }
6457 }
6458
Steve Anton8a006912017-12-04 15:25:56 -08006459 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006460}
6461
Steve Anton3828c062017-12-06 10:34:51 -08006462bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006463 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006464 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006465 return (state == PeerConnectionInterface::kStable) ||
6466 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006467 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006468 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006469 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6470 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6471 }
6472}
6473
Steve Anton3828c062017-12-06 10:34:51 -08006474bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006475 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006476 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006477 return (state == PeerConnectionInterface::kStable) ||
6478 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006479 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006480 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006481 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6482 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6483 }
6484}
6485
Steve Antonf8470812017-12-04 10:46:21 -08006486const char* PeerConnection::SessionErrorToString(SessionError error) const {
6487 switch (error) {
6488 case SessionError::kNone:
6489 return "ERROR_NONE";
6490 case SessionError::kContent:
6491 return "ERROR_CONTENT";
6492 case SessionError::kTransport:
6493 return "ERROR_TRANSPORT";
6494 }
6495 RTC_NOTREACHED();
6496 return "";
6497}
6498
Steve Anton75737c02017-11-06 10:37:17 -08006499std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006500 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006501 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6502 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006503 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006504}
6505
Steve Anton8e20f172018-03-06 10:55:04 -08006506void PeerConnection::ReportSdpFormatReceived(
6507 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006508 int num_audio_mlines = 0;
6509 int num_video_mlines = 0;
6510 int num_audio_tracks = 0;
6511 int num_video_tracks = 0;
6512 for (const ContentInfo& content : remote_offer.description()->contents()) {
6513 cricket::MediaType media_type = content.media_description()->type();
6514 int num_tracks = std::max(
6515 1, static_cast<int>(content.media_description()->streams().size()));
6516 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6517 num_audio_mlines += 1;
6518 num_audio_tracks += num_tracks;
6519 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6520 num_video_mlines += 1;
6521 num_video_tracks += num_tracks;
6522 }
6523 }
6524 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6525 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6526 format = kSdpFormatReceivedComplexUnifiedPlan;
6527 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6528 format = kSdpFormatReceivedComplexPlanB;
6529 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6530 format = kSdpFormatReceivedSimple;
6531 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006532 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6533 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006534}
6535
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006536void PeerConnection::NoteUsageEvent(UsageEvent event) {
6537 RTC_DCHECK_RUN_ON(signaling_thread());
6538 usage_event_accumulator_ |= static_cast<int>(event);
6539}
6540
6541void PeerConnection::ReportUsagePattern() const {
6542 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006543 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6544 usage_event_accumulator_,
6545 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006546 const int bad_bits =
6547 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6548 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6549 const int good_bits =
6550 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6551 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6552 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6553 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6554 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006555 // If called after close(), we can't report, because observer may have
6556 // been deallocated, and therefore pointer is null. Write to log instead.
6557 if (observer_) {
6558 Observer()->OnInterestingUsage(usage_event_accumulator_);
6559 } else {
6560 RTC_LOG(LS_INFO) << "Interesting usage signature "
6561 << usage_event_accumulator_
6562 << " observed after observer shutdown";
6563 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006564 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006565}
6566
Steve Anton0ffaaa22018-02-23 10:31:30 -08006567void PeerConnection::ReportNegotiatedSdpSemantics(
6568 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006569 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006570 switch (answer.description()->msid_signaling()) {
6571 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006572 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006573 break;
6574 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006575 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006576 break;
6577 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006578 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006579 break;
6580 case cricket::kMsidSignalingMediaSection |
6581 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006582 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006583 break;
6584 default:
6585 RTC_NOTREACHED();
6586 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006587 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6588 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006589}
6590
Steve Anton75737c02017-11-06 10:37:17 -08006591// We need to check the local/remote description for the Transport instead of
6592// the session, because a new Transport added during renegotiation may have
6593// them unset while the session has them set from the previous negotiation.
6594// Not doing so may trigger the auto generation of transport description and
6595// mess up DTLS identity information, ICE credential, etc.
6596bool PeerConnection::ReadyToUseRemoteCandidate(
6597 const IceCandidateInterface* candidate,
6598 const SessionDescriptionInterface* remote_desc,
6599 bool* valid) {
6600 *valid = true;
6601
6602 const SessionDescriptionInterface* current_remote_desc =
6603 remote_desc ? remote_desc : remote_description();
6604
6605 if (!current_remote_desc) {
6606 return false;
6607 }
6608
6609 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6610 size_t remote_content_size =
6611 current_remote_desc->description()->contents().size();
6612 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006613 RTC_LOG(LS_ERROR)
6614 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6615 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006616
6617 *valid = false;
6618 return false;
6619 }
6620
6621 cricket::ContentInfo content =
6622 current_remote_desc->description()->contents()[mediacontent_index];
6623
6624 const std::string transport_name = GetTransportName(content.name);
6625 if (transport_name.empty()) {
6626 return false;
6627 }
Zhi Huange830e682018-03-30 10:48:35 -07006628 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006629}
6630
6631bool PeerConnection::SrtpRequired() const {
6632 return dtls_enabled_ ||
6633 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6634}
6635
6636void PeerConnection::OnTransportControllerGatheringState(
6637 cricket::IceGatheringState state) {
6638 RTC_DCHECK(signaling_thread()->IsCurrent());
6639 if (state == cricket::kIceGatheringGathering) {
6640 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6641 } else if (state == cricket::kIceGatheringComplete) {
6642 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6643 }
6644}
6645
6646void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006647 std::map<std::string, std::set<cricket::MediaType>>
6648 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006649 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006650 if (transceiver->internal()->channel()) {
6651 const std::string& transport_name =
6652 transceiver->internal()->channel()->transport_name();
6653 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006654 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006655 }
Steve Anton75737c02017-11-06 10:37:17 -08006656 }
6657 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006658 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6659 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006660 }
Zhi Huange830e682018-03-30 10:48:35 -07006661
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006662 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006663 if (transport_name) {
6664 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006665 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006666 }
Zhi Huange830e682018-03-30 10:48:35 -07006667
Steve Antonc7b964c2018-02-01 14:39:45 -08006668 for (const auto& entry : media_types_by_transport_name) {
6669 const std::string& transport_name = entry.first;
6670 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006671 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006672 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006673 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006674 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006675 }
6676 }
6677}
6678// Walk through the ConnectionInfos to gather best connection usage
6679// for IPv4 and IPv6.
6680void PeerConnection::ReportBestConnectionState(
6681 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006682 for (const cricket::TransportChannelStats& channel_stats :
6683 stats.channel_stats) {
6684 for (const cricket::ConnectionInfo& connection_info :
6685 channel_stats.connection_infos) {
6686 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006687 continue;
6688 }
6689
Steve Antonc7b964c2018-02-01 14:39:45 -08006690 const cricket::Candidate& local = connection_info.local_candidate;
6691 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006692
6693 // Increment the counter for IceCandidatePairType.
6694 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6695 (local.type() == RELAY_PORT_TYPE &&
6696 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006697 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6698 GetIceCandidatePairCounter(local, remote),
6699 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006700 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006701 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6702 GetIceCandidatePairCounter(local, remote),
6703 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006704 } else {
6705 RTC_CHECK(0);
6706 }
Steve Anton75737c02017-11-06 10:37:17 -08006707
6708 // Increment the counter for IP type.
6709 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006710 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6711 kBestConnections_IPv4,
6712 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006713 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006714 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6715 kBestConnections_IPv6,
6716 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006717 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006718 RTC_CHECK(!local.address().hostname().empty() &&
6719 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006720 }
6721
6722 return;
6723 }
6724 }
6725}
6726
6727void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006728 const cricket::TransportStats& stats,
6729 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006730 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6731 return;
6732 }
6733
6734 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6735 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6736 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6737 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6738 return;
6739 }
6740
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006741 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6742 for (cricket::MediaType media_type : media_types) {
6743 switch (media_type) {
6744 case cricket::MEDIA_TYPE_AUDIO:
6745 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6746 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6747 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6748 break;
6749 case cricket::MEDIA_TYPE_VIDEO:
6750 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6751 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6752 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6753 break;
6754 case cricket::MEDIA_TYPE_DATA:
6755 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6756 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6757 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6758 break;
6759 default:
6760 RTC_NOTREACHED();
6761 continue;
6762 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006763 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006764 }
6765
6766 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6767 for (cricket::MediaType media_type : media_types) {
6768 switch (media_type) {
6769 case cricket::MEDIA_TYPE_AUDIO:
6770 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6771 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6772 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6773 break;
6774 case cricket::MEDIA_TYPE_VIDEO:
6775 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6776 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6777 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6778 break;
6779 case cricket::MEDIA_TYPE_DATA:
6780 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6781 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6782 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6783 break;
6784 default:
6785 RTC_NOTREACHED();
6786 continue;
6787 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006788 }
Steve Anton75737c02017-11-06 10:37:17 -08006789 }
6790}
6791
6792void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6793 RTC_DCHECK(worker_thread()->IsCurrent());
6794 RTC_DCHECK(call_);
6795 call_->OnSentPacket(sent_packet);
6796}
6797
6798const std::string PeerConnection::GetTransportName(
6799 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006800 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006801 if (channel) {
6802 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006803 }
Steve Anton6fec8802017-12-04 10:37:29 -08006804 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006805 RTC_DCHECK(sctp_mid_);
6806 if (content_name == *sctp_mid_) {
6807 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006808 }
6809 }
6810 // Return an empty string if failed to retrieve the transport name.
6811 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006812}
6813
Steve Anton6fec8802017-12-04 10:37:29 -08006814void PeerConnection::DestroyTransceiverChannel(
6815 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6816 transceiver) {
6817 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006818
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006819 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006820 if (channel) {
6821 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006822 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006823 }
6824}
6825
6826void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006827 if (rtp_data_channel_) {
6828 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006829 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006830 rtp_data_channel_ = nullptr;
6831 }
6832
6833 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6834 // grab a reference to this PeerConnection. If this is called from the
6835 // PeerConnection destructor, the RefCountedObject vtable will have already
6836 // been destroyed (since it is a subclass of PeerConnection) and using
6837 // rtc::Bind will cause "Pure virtual function called" error to appear.
6838
6839 if (sctp_transport_) {
6840 OnDataChannelDestroyed();
6841 network_thread()->Invoke<void>(RTC_FROM_HERE,
6842 [this] { DestroySctpTransport_n(); });
6843 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006844
6845 if (media_transport_) {
6846 OnDataChannelDestroyed();
6847 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6848 RTC_DCHECK_RUN_ON(network_thread());
6849 TeardownMediaTransportForDataChannels_n();
6850 });
6851 }
Steve Anton6fec8802017-12-04 10:37:29 -08006852}
6853
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006854void PeerConnection::DestroyChannelInterface(
6855 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006856 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006857 switch (channel->media_type()) {
6858 case cricket::MEDIA_TYPE_AUDIO:
6859 channel_manager()->DestroyVoiceChannel(
6860 static_cast<cricket::VoiceChannel*>(channel));
6861 break;
6862 case cricket::MEDIA_TYPE_VIDEO:
6863 channel_manager()->DestroyVideoChannel(
6864 static_cast<cricket::VideoChannel*>(channel));
6865 break;
6866 case cricket::MEDIA_TYPE_DATA:
6867 channel_manager()->DestroyRtpDataChannel(
6868 static_cast<cricket::RtpDataChannel*>(channel));
6869 break;
6870 default:
6871 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6872 break;
6873 }
Zhi Huange830e682018-03-30 10:48:35 -07006874}
Steve Anton6fec8802017-12-04 10:37:29 -08006875
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006876bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006877 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006878 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006879 cricket::DtlsTransportInternal* dtls_transport,
6880 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006881 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006882 auto base_channel = GetChannel(mid);
6883 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006884 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006885 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006886 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006887 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006888 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006889
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006890 if (configuration_.use_media_transport) {
6891 // Only pass media transport to call object if media transport is used
6892 // for media (and not data channel).
6893 call_->MediaTransportChange(media_transport);
6894 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006895
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006896 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006897}
6898
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006899PeerConnectionObserver* PeerConnection::Observer() const {
6900 // In earlier production code, the pointer was not cleared on close,
6901 // which might have led to undefined behavior if the observer was not
6902 // deallocated, or strange crashes if it was.
6903 // We use CHECK in order to catch such behavior if it exists.
6904 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6905 RTC_CHECK(observer_);
6906 return observer_;
6907}
6908
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006909CryptoOptions PeerConnection::GetCryptoOptions() {
6910 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6911 // after it has been removed.
6912 return configuration_.crypto_options.has_value()
6913 ? *configuration_.crypto_options
6914 : factory_->options().crypto_options;
6915}
6916
Harald Alvestrand89061872018-01-02 14:08:34 +01006917void PeerConnection::ClearStatsCache() {
6918 if (stats_collector_) {
6919 stats_collector_->ClearCachedStatsReport();
6920 }
6921}
6922
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006923void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006924 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6925 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006926}
6927
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006928} // namespace webrtc