blob: f811234729fd9af4bd4096ab711cb83cc9bab441 [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_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/bind.h"
48#include "rtc_base/checks.h"
49#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010050#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080051#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020052#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020053#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080062using cricket::RidDescription;
63using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080064using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080065using cricket::SimulcastDescription;
66using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080067using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080068using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080069using cricket::TransportInfo;
70
71using cricket::LOCAL_PORT_TYPE;
72using cricket::STUN_PORT_TYPE;
73using cricket::RELAY_PORT_TYPE;
74using cricket::PRFLX_PORT_TYPE;
75
Steve Antonba818672017-11-06 10:21:57 -080076namespace webrtc {
77
Steve Anton75737c02017-11-06 10:37:17 -080078// Error messages
79const char kBundleWithoutRtcpMux[] =
80 "rtcp-mux must be enabled when BUNDLE "
81 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080082const char kInvalidCandidates[] = "Description contains invalid candidates.";
83const char kInvalidSdp[] = "Invalid session description.";
84const char kMlineMismatchInAnswer[] =
85 "The order of m-lines in answer doesn't match order in offer. Rejecting "
86 "answer.";
87const char kMlineMismatchInSubsequentOffer[] =
88 "The order of m-lines in subsequent offer doesn't match order from "
89 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080090const char kSdpWithoutDtlsFingerprint[] =
91 "Called with SDP without DTLS fingerprint.";
92const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
93const char kSdpWithoutIceUfragPwd[] =
94 "Called with SDP without ice-ufrag and ice-pwd.";
95const char kSessionError[] = "Session error code: ";
96const char kSessionErrorDesc[] = "Session error description: ";
97const char kDtlsSrtpSetupFailureRtp[] =
98 "Couldn't set up DTLS-SRTP on RTP channel.";
99const char kDtlsSrtpSetupFailureRtcp[] =
100 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101
Steve Anton75737c02017-11-06 10:37:17 -0800102namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103
Seth Hampson845e8782018-03-02 11:34:10 -0800104static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800105static const char kDefaultAudioSenderId[] = "defaulta0";
106static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700107
zhihuang8f65cdf2016-05-06 18:40:30 -0700108// The length of RTCP CNAMEs.
109static const int kRtcpCnameLength = 16;
110
Steve Antonad182762018-09-05 20:22:40 +0000111enum {
112 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
113 MSG_SET_SESSIONDESCRIPTION_FAILED,
114 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
115 MSG_GETSTATS,
116 MSG_FREE_DATACHANNELS,
117 MSG_REPORT_USAGE_PATTERN,
118};
119
Harald Alvestrand19793842018-06-25 12:03:50 +0200120static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
121
Steve Antonad182762018-09-05 20:22:40 +0000122struct SetSessionDescriptionMsg : public rtc::MessageData {
123 explicit SetSessionDescriptionMsg(
124 webrtc::SetSessionDescriptionObserver* observer)
125 : observer(observer) {}
126
127 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
128 RTCError error;
129};
130
131struct CreateSessionDescriptionMsg : public rtc::MessageData {
132 explicit CreateSessionDescriptionMsg(
133 webrtc::CreateSessionDescriptionObserver* observer)
134 : observer(observer) {}
135
136 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
137 RTCError error;
138};
139
140struct GetStatsMsg : public rtc::MessageData {
141 GetStatsMsg(webrtc::StatsObserver* observer,
142 webrtc::MediaStreamTrackInterface* track)
143 : observer(observer), track(track) {}
144 rtc::scoped_refptr<webrtc::StatsObserver> observer;
145 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
146};
147
deadbeefab9b2d12015-10-14 11:33:11 -0700148// Check if we can send |new_stream| on a PeerConnection.
149bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
150 webrtc::MediaStreamInterface* new_stream) {
151 if (!new_stream || !current_streams) {
152 return false;
153 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700154 if (current_streams->find(new_stream->id()) != nullptr) {
155 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100156 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700157 return false;
158 }
159 return true;
160}
161
deadbeef5e97fb52015-10-15 12:49:08 -0700162// If the direction is "recvonly" or "inactive", treat the description
163// as containing no streams.
164// See: https://code.google.com/p/webrtc/issues/detail?id=5054
165std::vector<cricket::StreamParams> GetActiveStreams(
166 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800167 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700168 ? desc->streams()
169 : std::vector<cricket::StreamParams>();
170}
171
deadbeefab9b2d12015-10-14 11:33:11 -0700172bool IsValidOfferToReceiveMedia(int value) {
173 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
174 return (value >= Options::kUndefined) &&
175 (value <= Options::kMaxOfferToReceiveMedia);
176}
177
zhihuang1c378ed2017-08-17 14:10:50 -0700178// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800179void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700180 const std::vector<rtc::scoped_refptr<
181 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700182 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200183 cricket::MediaDescriptionOptions* video_media_description_options,
184 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700185 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700186 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
187 if (audio_media_description_options) {
188 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700189 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700190 }
191 } else {
192 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
193 if (video_media_description_options) {
194 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800195 sender->id(), sender->internal()->stream_ids(), {},
196 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700197 }
198 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700199 }
zhihuang1c378ed2017-08-17 14:10:50 -0700200}
olka3c747662017-08-17 06:50:32 -0700201
zhihuang1c378ed2017-08-17 14:10:50 -0700202// Add options to |session_options| from |rtp_data_channels|.
203void AddRtpDataChannelOptions(
204 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
205 rtp_data_channels,
206 cricket::MediaDescriptionOptions* data_media_description_options) {
207 if (!data_media_description_options) {
208 return;
209 }
deadbeefab9b2d12015-10-14 11:33:11 -0700210 // Check for data channels.
211 for (const auto& kv : rtp_data_channels) {
212 const DataChannel* channel = kv.second;
213 if (channel->state() == DataChannel::kConnecting ||
214 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700215 // Legacy RTP data channels are signaled with the track/stream ID set to
216 // the data channel's label.
217 data_media_description_options->AddRtpDataChannel(channel->label(),
218 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700219 }
220 }
221}
222
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700223uint32_t ConvertIceTransportTypeToCandidateFilter(
224 PeerConnectionInterface::IceTransportsType type) {
225 switch (type) {
226 case PeerConnectionInterface::kNone:
227 return cricket::CF_NONE;
228 case PeerConnectionInterface::kRelay:
229 return cricket::CF_RELAY;
230 case PeerConnectionInterface::kNoHost:
231 return (cricket::CF_ALL & ~cricket::CF_HOST);
232 case PeerConnectionInterface::kAll:
233 return cricket::CF_ALL;
234 default:
nissec80e7412017-01-11 05:56:46 -0800235 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700236 }
237 return cricket::CF_NONE;
238}
239
deadbeef293e9262017-01-11 12:28:30 -0800240// Helper to set an error and return from a method.
241bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
242 if (error) {
243 error->set_type(type);
244 }
245 return type == webrtc::RTCErrorType::NONE;
246}
247
Steve Anton038834f2017-07-14 15:59:59 -0700248bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700249 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700250 if (error_out) {
251 *error_out = std::move(error);
252 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700253 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700254}
255
Steve Antonba818672017-11-06 10:21:57 -0800256std::string GetSignalingStateString(
257 PeerConnectionInterface::SignalingState state) {
258 switch (state) {
259 case PeerConnectionInterface::kStable:
260 return "kStable";
261 case PeerConnectionInterface::kHaveLocalOffer:
262 return "kHaveLocalOffer";
263 case PeerConnectionInterface::kHaveLocalPrAnswer:
264 return "kHavePrAnswer";
265 case PeerConnectionInterface::kHaveRemoteOffer:
266 return "kHaveRemoteOffer";
267 case PeerConnectionInterface::kHaveRemotePrAnswer:
268 return "kHaveRemotePrAnswer";
269 case PeerConnectionInterface::kClosed:
270 return "kClosed";
271 }
272 RTC_NOTREACHED();
273 return "";
274}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700275
Steve Anton75737c02017-11-06 10:37:17 -0800276IceCandidatePairType GetIceCandidatePairCounter(
277 const cricket::Candidate& local,
278 const cricket::Candidate& remote) {
279 const auto& l = local.type();
280 const auto& r = remote.type();
281 const auto& host = LOCAL_PORT_TYPE;
282 const auto& srflx = STUN_PORT_TYPE;
283 const auto& relay = RELAY_PORT_TYPE;
284 const auto& prflx = PRFLX_PORT_TYPE;
285 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800286 bool local_hostname =
287 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
288 bool remote_hostname = !remote.address().hostname().empty() &&
289 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800290 bool local_private = IPIsPrivate(local.address().ipaddr());
291 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800292 if (local_hostname) {
293 if (remote_hostname) {
294 return kIceCandidatePairHostNameHostName;
295 } else if (remote_private) {
296 return kIceCandidatePairHostNameHostPrivate;
297 } else {
298 return kIceCandidatePairHostNameHostPublic;
299 }
300 } else if (local_private) {
301 if (remote_hostname) {
302 return kIceCandidatePairHostPrivateHostName;
303 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800304 return kIceCandidatePairHostPrivateHostPrivate;
305 } else {
306 return kIceCandidatePairHostPrivateHostPublic;
307 }
308 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800309 if (remote_hostname) {
310 return kIceCandidatePairHostPublicHostName;
311 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800312 return kIceCandidatePairHostPublicHostPrivate;
313 } else {
314 return kIceCandidatePairHostPublicHostPublic;
315 }
316 }
317 }
318 if (l == host && r == srflx)
319 return kIceCandidatePairHostSrflx;
320 if (l == host && r == relay)
321 return kIceCandidatePairHostRelay;
322 if (l == host && r == prflx)
323 return kIceCandidatePairHostPrflx;
324 if (l == srflx && r == host)
325 return kIceCandidatePairSrflxHost;
326 if (l == srflx && r == srflx)
327 return kIceCandidatePairSrflxSrflx;
328 if (l == srflx && r == relay)
329 return kIceCandidatePairSrflxRelay;
330 if (l == srflx && r == prflx)
331 return kIceCandidatePairSrflxPrflx;
332 if (l == relay && r == host)
333 return kIceCandidatePairRelayHost;
334 if (l == relay && r == srflx)
335 return kIceCandidatePairRelaySrflx;
336 if (l == relay && r == relay)
337 return kIceCandidatePairRelayRelay;
338 if (l == relay && r == prflx)
339 return kIceCandidatePairRelayPrflx;
340 if (l == prflx && r == host)
341 return kIceCandidatePairPrflxHost;
342 if (l == prflx && r == srflx)
343 return kIceCandidatePairPrflxSrflx;
344 if (l == prflx && r == relay)
345 return kIceCandidatePairPrflxRelay;
346 return kIceCandidatePairMax;
347}
348
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800349// Logic to decide if an m= section can be recycled. This means that the new
350// m= section is not rejected, but the old local or remote m= section is
351// rejected. |old_content_one| and |old_content_two| refer to the m= section
352// of the old remote and old local descriptions in no particular order.
353// We need to check both the old local and remote because either
354// could be the most current from the latest negotation.
355bool IsMediaSectionBeingRecycled(SdpType type,
356 const ContentInfo& content,
357 const ContentInfo* old_content_one,
358 const ContentInfo* old_content_two) {
359 return type == SdpType::kOffer && !content.rejected &&
360 ((old_content_one && old_content_one->rejected) ||
361 (old_content_two && old_content_two->rejected));
362}
363
Steve Anton75737c02017-11-06 10:37:17 -0800364// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800365// |current_desc|. The number of m= sections in |new_desc| should be no
366// less than |current_desc|. In the case of checking an answer's
367// |new_desc|, the |current_desc| is the last offer that was set as the
368// local or remote. In the case of checking an offer's |new_desc| we
369// check against the local and remote descriptions stored from the last
370// negotiation, because either of these could be the most up to date for
371// possible rejected m sections. These are the |current_desc| and
372// |secondary_current_desc|.
373bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
374 const SessionDescription* secondary_current_desc,
375 const SessionDescription& new_desc,
376 const SdpType type) {
377 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800378 return false;
379 }
380
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800381 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
382 const cricket::ContentInfo* secondary_content_info = nullptr;
383 if (secondary_current_desc &&
384 i < secondary_current_desc->contents().size()) {
385 secondary_content_info = &secondary_current_desc->contents()[i];
386 }
387 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
388 &current_desc.contents()[i],
389 secondary_content_info)) {
390 // For new offer descriptions, if the media section can be recycled, it's
391 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800392 continue;
393 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800394 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800395 return false;
396 }
397 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800398 new_desc.contents()[i].media_description();
399 const MediaContentDescription* current_desc_mdesc =
400 current_desc.contents()[i].media_description();
401 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800402 return false;
403 }
404 }
405 return true;
406}
407
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800408bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
409 const SessionDescription& desc2) {
410 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800411}
412
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700413void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
414 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200415 // Array of structs needed to map {KeyExchangeProtocolType,
416 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
417 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
418 static constexpr struct {
419 KeyExchangeProtocolType protocol_type;
420 cricket::MediaType media_type;
421 KeyExchangeProtocolMedia protocol_media;
422 } kEnumCounterKeyProtocolMediaMap[] = {
423 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
424 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
425 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
426 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
427 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
428 kEnumCounterKeyProtocolMediaTypeDtlsData},
429 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
430 kEnumCounterKeyProtocolMediaTypeSdesAudio},
431 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
432 kEnumCounterKeyProtocolMediaTypeSdesVideo},
433 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
434 kEnumCounterKeyProtocolMediaTypeSdesData},
435 };
436
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700437 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
438 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100439
Mirko Bonadeiab499822018-09-11 10:43:20 +0200440 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
441 if (i.protocol_type == protocol_type && i.media_type == media_type) {
442 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
443 i.protocol_media,
444 kEnumCounterKeyProtocolMediaTypeMax);
445 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100446 }
447}
448
Harald Alvestrand76829d72018-07-18 23:24:36 +0200449void NoteAddIceCandidateResult(int result) {
450 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
451 kAddIceCandidateMax);
452}
453
Steve Anton75737c02017-11-06 10:37:17 -0800454// Checks that each non-rejected content has SDES crypto keys or a DTLS
455// fingerprint, unless it's in a BUNDLE group, in which case only the
456// BUNDLE-tag section (first media section/description in the BUNDLE group)
457// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
458// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
459// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700460RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800461 const cricket::ContentGroup* bundle =
462 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800463 for (const cricket::ContentInfo& content_info : desc->contents()) {
464 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800465 continue;
466 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100467 // Note what media is used with each crypto protocol, for all sections.
468 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
469 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700470 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800471 const std::string& mid = content_info.name;
472 if (bundle && bundle->HasContentName(mid) &&
473 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800474 // This isn't the first media section in the BUNDLE group, so it's not
475 // required to have crypto attributes, since only the crypto attributes
476 // from the first section actually get used.
477 continue;
478 }
479
480 // If the content isn't rejected or bundled into another m= section, crypto
481 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800482 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800483 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800484 if (!media || !tinfo) {
485 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800486 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800487 }
488 if (dtls_enabled) {
489 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100490 RTC_LOG(LS_WARNING)
491 << "Session description must have DTLS fingerprint if "
492 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800493 return RTCError(RTCErrorType::INVALID_PARAMETER,
494 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800495 }
496 } else {
497 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800499 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800500 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800501 }
502 }
503 }
Steve Anton8a006912017-12-04 15:25:56 -0800504 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800505}
506
507// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
508// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
509// media section/description in the BUNDLE group) needs a ufrag and pwd.
510bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
511 const cricket::ContentGroup* bundle =
512 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800513 for (const cricket::ContentInfo& content_info : desc->contents()) {
514 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800515 continue;
516 }
Steve Anton8a006912017-12-04 15:25:56 -0800517 const std::string& mid = content_info.name;
518 if (bundle && bundle->HasContentName(mid) &&
519 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800520 // This isn't the first media section in the BUNDLE group, so it's not
521 // required to have ufrag/password, since only the ufrag/password from
522 // the first section actually get used.
523 continue;
524 }
525
526 // If the content isn't rejected or bundled into another m= section,
527 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800528 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (!tinfo) {
530 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100531 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800532 return false;
533 }
534 if (tinfo->description.ice_ufrag.empty() ||
535 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100536 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800537 return false;
538 }
539 }
540 return true;
541}
542
Steve Anton75737c02017-11-06 10:37:17 -0800543// Get the SCTP port out of a SessionDescription.
544// Return -1 if not found.
545int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800546 const cricket::DataContentDescription* data_desc =
547 GetFirstDataContentDescription(session_description);
548 RTC_DCHECK(data_desc);
549 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 return -1;
551 }
Steve Anton75737c02017-11-06 10:37:17 -0800552 std::string value;
553 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
554 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800555 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800556 if (!codec.Matches(match_pattern)) {
557 continue;
558 }
559 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
560 return rtc::FromString<int>(value);
561 }
562 }
563 return -1;
564}
565
Steve Anton75737c02017-11-06 10:37:17 -0800566// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
567bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
568 const SessionDescriptionInterface* new_desc,
569 const std::string& content_name) {
570 if (!old_desc) {
571 return false;
572 }
573 const SessionDescription* new_sd = new_desc->description();
574 const SessionDescription* old_sd = old_desc->description();
575 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
576 if (!cinfo || cinfo->rejected) {
577 return false;
578 }
579 // If the content isn't rejected, check if ufrag and password has changed.
580 const cricket::TransportDescription* new_transport_desc =
581 new_sd->GetTransportDescriptionByName(content_name);
582 const cricket::TransportDescription* old_transport_desc =
583 old_sd->GetTransportDescriptionByName(content_name);
584 if (!new_transport_desc || !old_transport_desc) {
585 // No transport description exists. This is not an ICE restart.
586 return false;
587 }
588 if (cricket::IceCredentialsChanged(
589 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
590 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100591 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
592 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800593 return true;
594 }
595 return false;
596}
597
Steve Anton80dd7b52018-02-16 17:08:42 -0800598// Generates a string error message for SetLocalDescription/SetRemoteDescription
599// from an RTCError.
600std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
601 SdpType type,
602 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200603 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800604 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
605 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200606 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800607}
608
Seth Hampson5b4f0752018-04-02 16:31:36 -0700609std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
610 std::string output = "streams=[";
611 const char* separator = "";
612 for (const auto& stream_id : stream_ids) {
613 output.append(separator).append(stream_id);
614 separator = ", ";
615 }
616 output.append("]");
617 return output;
618}
619
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200620absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700621 int rtc_configuration_parameter) {
622 if (rtc_configuration_parameter ==
623 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200624 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700625 }
626 return rtc_configuration_parameter;
627}
628
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800629cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
630 switch (type) {
631 case DataMessageType::kText:
632 return cricket::DMT_TEXT;
633 case DataMessageType::kBinary:
634 return cricket::DMT_BINARY;
635 case DataMessageType::kControl:
636 return cricket::DMT_CONTROL;
637 default:
638 return cricket::DMT_NONE;
639 }
640 return cricket::DMT_NONE;
641}
642
643DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
644 switch (type) {
645 case cricket::DMT_TEXT:
646 return DataMessageType::kText;
647 case cricket::DMT_BINARY:
648 return DataMessageType::kBinary;
649 case cricket::DMT_CONTROL:
650 return DataMessageType::kControl;
651 case cricket::DMT_NONE:
652 default:
653 RTC_NOTREACHED();
654 }
655 return DataMessageType::kControl;
656}
657
Steve Anton75737c02017-11-06 10:37:17 -0800658} // namespace
659
Henrik Boström31638672017-11-23 17:48:32 +0100660// Upon completion, posts a task to execute the callback of the
661// SetSessionDescriptionObserver asynchronously on the same thread. At this
662// point, the state of the peer connection might no longer reflect the effects
663// of the SetRemoteDescription operation, as the peer connection could have been
664// modified during the post.
665// TODO(hbos): Remove this class once we remove the version of
666// PeerConnectionInterface::SetRemoteDescription() that takes a
667// SetSessionDescriptionObserver as an argument.
668class PeerConnection::SetRemoteDescriptionObserverAdapter
669 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
670 public:
671 SetRemoteDescriptionObserverAdapter(
672 rtc::scoped_refptr<PeerConnection> pc,
673 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
674 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
675
676 // SetRemoteDescriptionObserverInterface implementation.
677 void OnSetRemoteDescriptionComplete(RTCError error) override {
678 if (error.ok())
679 pc_->PostSetSessionDescriptionSuccess(wrapper_);
680 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100681 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100682 }
683
684 private:
685 rtc::scoped_refptr<PeerConnection> pc_;
686 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
687};
688
deadbeef293e9262017-01-11 12:28:30 -0800689bool PeerConnectionInterface::RTCConfiguration::operator==(
690 const PeerConnectionInterface::RTCConfiguration& o) const {
691 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700692 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800693 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000694 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700695 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800696 BundlePolicy bundle_policy;
697 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700698 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
699 int ice_candidate_pool_size;
700 bool disable_ipv6;
701 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700702 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100703 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700704 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200705 absl::optional<int> screencast_min_bitrate;
706 absl::optional<bool> combined_audio_video_bwe;
707 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800708 TcpCandidatePolicy tcp_candidate_policy;
709 CandidateNetworkPolicy candidate_network_policy;
710 int audio_jitter_buffer_max_packets;
711 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100712 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100713 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800714 int ice_connection_receiving_timeout;
715 int ice_backup_candidate_pair_ping_interval;
716 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800717 bool prioritize_most_likely_ice_candidate_pairs;
718 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800719 bool prune_turn_ports;
720 bool presume_writable_when_fully_relayed;
721 bool enable_ice_renomination;
722 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200723 absl::optional<int> ice_check_interval_strong_connectivity;
724 absl::optional<int> ice_check_interval_weak_connectivity;
725 absl::optional<int> ice_check_min_interval;
726 absl::optional<int> ice_unwritable_timeout;
727 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800728 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200729 absl::optional<int> stun_candidate_keepalive_interval;
730 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200731 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800732 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200733 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700734 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700735 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700736 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700737 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100738 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800739 };
740 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
741 "Did you add something to RTCConfiguration and forget to "
742 "update operator==?");
743 return type == o.type && servers == o.servers &&
744 bundle_policy == o.bundle_policy &&
745 rtcp_mux_policy == o.rtcp_mux_policy &&
746 tcp_candidate_policy == o.tcp_candidate_policy &&
747 candidate_network_policy == o.candidate_network_policy &&
748 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
749 audio_jitter_buffer_fast_accelerate ==
750 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100751 audio_jitter_buffer_min_delay_ms ==
752 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100753 audio_jitter_buffer_enable_rtx_handling ==
754 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800755 ice_connection_receiving_timeout ==
756 o.ice_connection_receiving_timeout &&
757 ice_backup_candidate_pair_ping_interval ==
758 o.ice_backup_candidate_pair_ping_interval &&
759 continual_gathering_policy == o.continual_gathering_policy &&
760 certificates == o.certificates &&
761 prioritize_most_likely_ice_candidate_pairs ==
762 o.prioritize_most_likely_ice_candidate_pairs &&
763 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800764 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700765 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100766 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800767 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800768 screencast_min_bitrate == o.screencast_min_bitrate &&
769 combined_audio_video_bwe == o.combined_audio_video_bwe &&
770 enable_dtls_srtp == o.enable_dtls_srtp &&
771 ice_candidate_pool_size == o.ice_candidate_pool_size &&
772 prune_turn_ports == o.prune_turn_ports &&
773 presume_writable_when_fully_relayed ==
774 o.presume_writable_when_fully_relayed &&
775 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800776 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800777 ice_check_interval_strong_connectivity ==
778 o.ice_check_interval_strong_connectivity &&
779 ice_check_interval_weak_connectivity ==
780 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700781 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700782 ice_unwritable_timeout == o.ice_unwritable_timeout &&
783 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800784 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800785 stun_candidate_keepalive_interval ==
786 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200787 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800788 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800789 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700790 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700791 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700792 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700793 use_media_transport_for_data_channels ==
794 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100795 crypto_options == o.crypto_options &&
796 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800797}
798
799bool PeerConnectionInterface::RTCConfiguration::operator!=(
800 const PeerConnectionInterface::RTCConfiguration& o) const {
801 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800802}
803
zhihuang8f65cdf2016-05-06 18:40:30 -0700804// Generate a RTCP CNAME when a PeerConnection is created.
805std::string GenerateRtcpCname() {
806 std::string cname;
807 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100808 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800809 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700810 }
811 return cname;
812}
813
zhihuang1c378ed2017-08-17 14:10:50 -0700814bool ValidateOfferAnswerOptions(
815 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
816 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
817 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700818}
819
zhihuang1c378ed2017-08-17 14:10:50 -0700820// From |rtc_options|, fill parts of |session_options| shared by all generated
821// m= sections (in other words, nothing that involves a map/array).
822void ExtractSharedMediaSessionOptions(
823 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
824 cricket::MediaSessionOptions* session_options) {
825 session_options->vad_enabled = rtc_options.voice_activity_detection;
826 session_options->bundle_enabled = rtc_options.use_rtp_mux;
827}
zhihuanga77e6bb2017-08-14 18:17:48 -0700828
zhihuang38ede132017-06-15 12:52:32 -0700829PeerConnection::PeerConnection(PeerConnectionFactory* factory,
830 std::unique_ptr<RtcEventLog> event_log,
831 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700833 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700834 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700835 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700836 remote_streams_(StreamCollection::Create()),
837 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838
839PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100840 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800841 RTC_DCHECK_RUN_ON(signaling_thread());
842
Steve Anton8af21862017-12-15 11:20:13 -0800843 // Need to stop transceivers before destroying the stats collector because
844 // AudioRtpSender has a reference to the StatsCollector it will update when
845 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100846 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800847 transceiver->Stop();
848 }
Steve Anton4171afb2017-11-20 10:20:22 -0800849
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700850 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800851 if (stats_collector_) {
852 stats_collector_->WaitForPendingRequest();
853 stats_collector_ = nullptr;
854 }
Steve Anton75737c02017-11-06 10:37:17 -0800855
Steve Anton8af21862017-12-15 11:20:13 -0800856 // Don't destroy BaseChannels until after stats has been cleaned up so that
857 // the last stats request can still read from the channels.
858 DestroyAllChannels();
859
Mirko Bonadei675513b2017-11-09 11:09:25 +0100860 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800861
862 webrtc_session_desc_factory_.reset();
863 sctp_invoker_.reset();
864 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800865 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800866 transport_controller_.reset();
867
deadbeef91dd5672016-05-18 16:55:30 -0700868 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700869 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700870 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700871 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700872 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700873 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800874 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700875 event_log_.reset();
876 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000877}
878
Steve Anton8af21862017-12-15 11:20:13 -0800879void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800880 // Destroy video channels first since they may have a pointer to a voice
881 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100882 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800883 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800884 DestroyTransceiverChannel(transceiver);
885 }
886 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100887 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800888 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800889 DestroyTransceiverChannel(transceiver);
890 }
891 }
892 DestroyDataChannel();
893}
894
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000895bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000896 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700897 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100898 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700899
900 RTCError config_error = ValidateConfiguration(configuration);
901 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100902 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700903 return false;
904 }
905
Benjamin Wrightcab58882018-05-02 15:12:47 -0700906 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LS_ERROR)
908 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100909 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800910 return false;
911 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200912
Benjamin Wrightcab58882018-05-02 15:12:47 -0700913 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800914 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100915 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100916 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800917 return false;
918 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700919
Benjamin Wrightcab58882018-05-02 15:12:47 -0700920 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700921 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700922 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700923 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800924
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200925 cricket::ServerAddresses stun_servers;
926 std::vector<cricket::RelayServerConfig> turn_servers;
927
928 RTCErrorType parse_error =
929 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
930 if (parse_error != RTCErrorType::NONE) {
931 return false;
932 }
933
deadbeef91dd5672016-05-18 16:55:30 -0700934 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700935 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700936 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200937 RTC_FROM_HERE,
938 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
939 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940 return false;
941 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200942 // If initialization was successful, note if STUN or TURN servers
943 // were supplied.
944 if (!stun_servers.empty()) {
945 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
946 }
947 if (!turn_servers.empty()) {
948 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
949 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700951 // Send information about IPv4/IPv6 status.
952 PeerConnectionAddressFamilyCounter address_family;
953 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
954 address_family = kPeerConnection_IPv6;
955 } else {
956 address_family = kPeerConnection_IPv4;
957 }
958 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
959 kPeerConnectionAddressFamilyCounter_Max);
960
Zhi Huange830e682018-03-30 10:48:35 -0700961 const PeerConnectionFactoryInterface::Options& options = factory_->options();
962
Steve Anton75737c02017-11-06 10:37:17 -0800963 // RFC 3264: The numeric value of the session id and version in the
964 // o line MUST be representable with a "64 bit signed integer".
965 // Due to this constraint session id |session_id_| is max limited to
966 // LLONG_MAX.
967 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700968 JsepTransportController::Config config;
969 config.redetermine_role_on_ice_restart =
970 configuration.redetermine_role_on_ice_restart;
971 config.ssl_max_version = factory_->options().ssl_max_version;
972 config.disable_encryption = options.disable_encryption;
973 config.bundle_policy = configuration.bundle_policy;
974 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700975 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
976 // stub.
977 config.crypto_options = configuration.crypto_options.has_value()
978 ? *configuration.crypto_options
979 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700980 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700981 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700982#if defined(ENABLE_EXTERNAL_AUTH)
983 config.enable_external_auth = true;
984#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700985 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700986
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700987 if (configuration.use_media_transport ||
988 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700989 if (!factory_->media_transport_factory()) {
990 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700991 << "PeerConnecton is initialized with use_media_transport = true or "
992 << "use_media_transport_for_data_channels = true "
993 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700994 return false;
995 }
996
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -0800997 config.use_media_transport_for_media = configuration.use_media_transport;
998 config.use_media_transport_for_data_channels =
999 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001000 config.media_transport_factory = factory_->media_transport_factory();
1001 }
1002
Zhi Huange830e682018-03-30 10:48:35 -07001003 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001004 signaling_thread(), network_thread(), port_allocator_.get(),
1005 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001006 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001007 this, &PeerConnection::OnTransportControllerConnectionState);
1008 transport_controller_->SignalStandardizedIceConnectionState.connect(
1009 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001010 transport_controller_->SignalConnectionState.connect(
1011 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001012 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001013 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001014 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001015 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001016 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001017 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1018 transport_controller_->SignalDtlsHandshakeError.connect(
1019 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1020
1021 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001022
deadbeefab9b2d12015-10-14 11:33:11 -07001023 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001024 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025
Steve Antonba818672017-11-06 10:21:57 -08001026 configuration_ = configuration;
1027
Steve Anton75737c02017-11-06 10:37:17 -08001028 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1029 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1030 if (!configuration.certificates.empty()) {
1031 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1032 // just picking the first one. The decision should be made based on the DTLS
1033 // handshake. The DTLS negotiations need to know about all certificates.
1034 certificate = configuration.certificates[0];
1035 }
1036
Steve Antond25da372017-11-06 14:50:29 -08001037 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001038
1039 if (options.disable_encryption) {
1040 dtls_enabled_ = false;
1041 } else {
1042 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001043 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001044 // |configuration| can override the default |dtls_enabled_| value.
1045 if (configuration.enable_dtls_srtp) {
1046 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1047 }
1048 }
1049
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001050 if (configuration.use_media_transport_for_data_channels) {
1051 if (configuration.enable_rtp_data_channel) {
1052 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1053 "use_media_transport_for_data_channels are "
1054 "incompatible and cannot both be set to true";
1055 return false;
1056 }
1057 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1058 } else if (configuration.enable_rtp_data_channel) {
1059 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1060 // set. It takes precendence over the disable_sctp_data_channels
1061 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001062 data_channel_type_ = cricket::DCT_RTP;
1063 } else {
1064 // DTLS has to be enabled to use SCTP.
1065 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1066 data_channel_type_ = cricket::DCT_SCTP;
1067 }
1068 }
1069
1070 video_options_.screencast_min_bitrate_kbps =
1071 configuration.screencast_min_bitrate;
1072 audio_options_.combined_audio_video_bwe =
1073 configuration.combined_audio_video_bwe;
1074
1075 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001076 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001077
1078 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001079 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001080
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001081 audio_options_.audio_jitter_buffer_min_delay_ms =
1082 configuration.audio_jitter_buffer_min_delay_ms;
1083
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001084 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1085 configuration.audio_jitter_buffer_enable_rtx_handling;
1086
Steve Anton75737c02017-11-06 10:37:17 -08001087 // Whether the certificate generator/certificate is null or not determines
1088 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1089 // the right instructions by clearing the variables if needed.
1090 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001091 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001092 certificate = nullptr;
1093 } else if (certificate) {
1094 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001095 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001096 }
1097
1098 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1099 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001100 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001101 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1102 this, &PeerConnection::OnCertificateReady);
1103
1104 if (options.disable_encryption) {
1105 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1106 }
1107
1108 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001109 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001110 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001111
Steve Anton4171afb2017-11-20 10:20:22 -08001112 // Add default audio/video transceivers for Plan B SDP.
1113 if (!IsUnifiedPlan()) {
1114 transceivers_.push_back(
1115 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1116 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1117 transceivers_.push_back(
1118 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1119 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1120 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001121 int delay_ms =
1122 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001123 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1124 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001125 return true;
1126}
1127
Steve Anton038834f2017-07-14 15:59:59 -07001128RTCError PeerConnection::ValidateConfiguration(
1129 const RTCConfiguration& config) const {
1130 if (config.ice_regather_interval_range &&
1131 config.continual_gathering_policy == GATHER_ONCE) {
1132 return RTCError(RTCErrorType::INVALID_PARAMETER,
1133 "ice_regather_interval_range specified but continual "
1134 "gathering policy is GATHER_ONCE");
1135 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001136 auto result =
1137 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1138 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001139}
1140
Yves Gerey665174f2018-06-19 15:03:05 +02001141rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001142 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1143 "Plan SdpSemantics. Please use GetSenders "
1144 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001145 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146}
1147
Yves Gerey665174f2018-06-19 15:03:05 +02001148rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001149 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1150 "Plan SdpSemantics. Please use GetReceivers "
1151 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001152 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001153}
1154
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001155bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001156 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1157 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001158 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001159 if (IsClosed()) {
1160 return false;
1161 }
deadbeefab9b2d12015-10-14 11:33:11 -07001162 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 return false;
1164 }
deadbeefab9b2d12015-10-14 11:33:11 -07001165
1166 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001167 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1168 observer->SignalAudioTrackAdded.connect(this,
1169 &PeerConnection::OnAudioTrackAdded);
1170 observer->SignalAudioTrackRemoved.connect(
1171 this, &PeerConnection::OnAudioTrackRemoved);
1172 observer->SignalVideoTrackAdded.connect(this,
1173 &PeerConnection::OnVideoTrackAdded);
1174 observer->SignalVideoTrackRemoved.connect(
1175 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001176 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001177
deadbeefab9b2d12015-10-14 11:33:11 -07001178 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001179 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001180 }
1181 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001182 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001183 }
1184
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001185 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001186 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001187 return true;
1188}
1189
1190void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001191 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1192 "Plan SdpSemantics. Please use RemoveTrack "
1193 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001194 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001195 if (!IsClosed()) {
1196 for (const auto& track : local_stream->GetAudioTracks()) {
1197 RemoveAudioTrack(track.get(), local_stream);
1198 }
1199 for (const auto& track : local_stream->GetVideoTracks()) {
1200 RemoveVideoTrack(track.get(), local_stream);
1201 }
deadbeefab9b2d12015-10-14 11:33:11 -07001202 }
deadbeefab9b2d12015-10-14 11:33:11 -07001203 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001204 stream_observers_.erase(
1205 std::remove_if(
1206 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001207 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001208 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001209 }),
1210 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001211
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001212 if (IsClosed()) {
1213 return;
1214 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001215 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216}
1217
Steve Anton2d6c76a2018-01-05 17:10:52 -08001218RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001219 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001220 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001221 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001222 if (!track) {
1223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1224 }
1225 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1226 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1227 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1228 "Track has invalid kind: " + track->kind());
1229 }
Steve Antonf9381f02017-12-14 10:23:57 -08001230 if (IsClosed()) {
1231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1232 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001233 }
Steve Anton4171afb2017-11-20 10:20:22 -08001234 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001235 LOG_AND_RETURN_ERROR(
1236 RTCErrorType::INVALID_PARAMETER,
1237 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001238 }
Steve Antonf9381f02017-12-14 10:23:57 -08001239 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001240 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1241 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001242 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001243 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001244 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001245 }
1246 return sender_or_error;
1247}
deadbeefe1f9d832016-01-14 15:35:42 -08001248
Steve Antonf9381f02017-12-14 10:23:57 -08001249RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1250PeerConnection::AddTrackPlanB(
1251 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001252 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001253 if (stream_ids.size() > 1u) {
1254 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1255 "AddTrack with more than one stream is not "
1256 "supported with Plan B semantics.");
1257 }
1258 std::vector<std::string> adjusted_stream_ids = stream_ids;
1259 if (adjusted_stream_ids.empty()) {
1260 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1261 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001262 cricket::MediaType media_type =
1263 (track->kind() == MediaStreamTrackInterface::kAudioKind
1264 ? cricket::MEDIA_TYPE_AUDIO
1265 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001266 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001267 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001268 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001269 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001270 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001271 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001272 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001273 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001274 if (sender_info) {
1275 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001276 }
Steve Antonf9381f02017-12-14 10:23:57 -08001277 } else {
1278 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001279 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001280 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001281 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001282 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001283 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001284 if (sender_info) {
1285 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001286 }
deadbeefe1f9d832016-01-14 15:35:42 -08001287 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001288 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001289}
deadbeefe1f9d832016-01-14 15:35:42 -08001290
Steve Antonf9381f02017-12-14 10:23:57 -08001291RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1292PeerConnection::AddTrackUnifiedPlan(
1293 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001294 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001295 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1296 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001297 RTC_LOG(LS_INFO) << "Reusing an existing "
1298 << cricket::MediaTypeToString(transceiver->media_type())
1299 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001300 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001301 transceiver->internal()->set_direction(
1302 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001303 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001304 transceiver->internal()->set_direction(
1305 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001306 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001307 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001308 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001309 } else {
1310 cricket::MediaType media_type =
1311 (track->kind() == MediaStreamTrackInterface::kAudioKind
1312 ? cricket::MEDIA_TYPE_AUDIO
1313 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001314 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1315 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001316 std::string sender_id = track->id();
1317 // Avoid creating a sender with an existing ID by generating a random ID.
1318 // This can happen if this is the second time AddTrack has created a sender
1319 // for this track.
1320 if (FindSenderById(sender_id)) {
1321 sender_id = rtc::CreateRandomUuid();
1322 }
Florent Castelli892acf02018-10-01 22:47:20 +02001323 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001324 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1325 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001326 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001327 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001328 }
Steve Antonf9381f02017-12-14 10:23:57 -08001329 return transceiver->sender();
1330}
1331
1332rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1333PeerConnection::FindFirstTransceiverForAddedTrack(
1334 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1335 RTC_DCHECK(track);
1336 for (auto transceiver : transceivers_) {
1337 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001338 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001339 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001340 !transceiver->internal()->has_ever_been_used_to_send() &&
1341 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001342 return transceiver;
1343 }
1344 }
1345 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001346}
1347
1348bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1349 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001350 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001351}
1352
Steve Anton24db5732018-07-23 10:27:33 -07001353RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001354 rtc::scoped_refptr<RtpSenderInterface> sender) {
1355 if (!sender) {
1356 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1357 }
deadbeefe1f9d832016-01-14 15:35:42 -08001358 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001359 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1360 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001361 }
Steve Antonf9381f02017-12-14 10:23:57 -08001362 if (IsUnifiedPlan()) {
1363 auto transceiver = FindTransceiverBySender(sender);
1364 if (!transceiver || !sender->track()) {
1365 return RTCError::OK();
1366 }
1367 sender->SetTrack(nullptr);
1368 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001369 transceiver->internal()->set_direction(
1370 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001371 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001372 transceiver->internal()->set_direction(
1373 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001374 }
Steve Anton4171afb2017-11-20 10:20:22 -08001375 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001376 bool removed;
1377 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1378 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1379 } else {
1380 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1381 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1382 }
1383 if (!removed) {
1384 LOG_AND_RETURN_ERROR(
1385 RTCErrorType::INVALID_PARAMETER,
1386 "Couldn't find sender " + sender->id() + " to remove.");
1387 }
Steve Anton4171afb2017-11-20 10:20:22 -08001388 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001389 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001390 return RTCError::OK();
1391}
1392
1393rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1394PeerConnection::FindTransceiverBySender(
1395 rtc::scoped_refptr<RtpSenderInterface> sender) {
1396 for (auto transceiver : transceivers_) {
1397 if (transceiver->sender() == sender) {
1398 return transceiver;
1399 }
1400 }
1401 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001402}
1403
Steve Anton9158ef62017-11-27 13:01:52 -08001404RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1405PeerConnection::AddTransceiver(
1406 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1407 return AddTransceiver(track, RtpTransceiverInit());
1408}
1409
1410RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1411PeerConnection::AddTransceiver(
1412 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1413 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001414 RTC_CHECK(IsUnifiedPlan())
1415 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001416 if (!track) {
1417 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1418 }
1419 cricket::MediaType media_type;
1420 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1421 media_type = cricket::MEDIA_TYPE_AUDIO;
1422 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1423 media_type = cricket::MEDIA_TYPE_VIDEO;
1424 } else {
1425 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1426 "Track kind is not audio or video");
1427 }
1428 return AddTransceiver(media_type, track, init);
1429}
1430
1431RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1432PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1433 return AddTransceiver(media_type, RtpTransceiverInit());
1434}
1435
1436RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1437PeerConnection::AddTransceiver(cricket::MediaType media_type,
1438 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001439 RTC_CHECK(IsUnifiedPlan())
1440 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001441 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1442 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1443 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1444 "media type is not audio or video");
1445 }
1446 return AddTransceiver(media_type, nullptr, init);
1447}
1448
1449RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1450PeerConnection::AddTransceiver(
1451 cricket::MediaType media_type,
1452 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001453 const RtpTransceiverInit& init,
1454 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001455 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1456 media_type == cricket::MEDIA_TYPE_VIDEO));
1457 if (track) {
1458 RTC_DCHECK_EQ(media_type,
1459 (track->kind() == MediaStreamTrackInterface::kAudioKind
1460 ? cricket::MEDIA_TYPE_AUDIO
1461 : cricket::MEDIA_TYPE_VIDEO));
1462 }
1463
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001464 size_t num_rids = absl::c_count_if(init.send_encodings,
1465 [](const RtpEncodingParameters& encoding) {
1466 return !encoding.rid.empty();
1467 });
1468 if (num_rids > 0 && num_rids != init.send_encodings.size()) {
Florent Castelli892acf02018-10-01 22:47:20 +02001469 LOG_AND_RETURN_ERROR(
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001470 RTCErrorType::INVALID_PARAMETER,
1471 "RIDs must be provided for either all or none of the send encodings.");
Florent Castelli892acf02018-10-01 22:47:20 +02001472 }
1473
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001474 if (absl::c_any_of(init.send_encodings,
1475 [](const RtpEncodingParameters& encoding) {
1476 return encoding.ssrc.has_value();
1477 })) {
1478 LOG_AND_RETURN_ERROR(
1479 RTCErrorType::UNSUPPORTED_PARAMETER,
1480 "Attempted to set an unimplemented parameter of RtpParameters.");
Florent Castelli892acf02018-10-01 22:47:20 +02001481 }
1482
1483 RtpParameters parameters;
1484 parameters.encodings = init.send_encodings;
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001485
1486 // Encodings are dropped from the tail if too many are provided.
1487 if (parameters.encodings.size() > kMaxSimulcastStreams) {
1488 parameters.encodings.erase(
1489 parameters.encodings.begin() + kMaxSimulcastStreams,
1490 parameters.encodings.end());
1491 }
1492
1493 // Single RID should be removed.
1494 if (parameters.encodings.size() == 1 &&
1495 !parameters.encodings[0].rid.empty()) {
1496 RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
1497 parameters.encodings[0].rid.clear();
1498 }
1499
1500 // If RIDs were not provided, they are generated for simulcast scenario.
1501 if (parameters.encodings.size() > 1 && num_rids == 0) {
1502 rtc::UniqueStringGenerator rid_generator;
1503 for (RtpEncodingParameters& encoding : parameters.encodings) {
1504 encoding.rid = rid_generator();
1505 }
1506 }
1507
Florent Castelli892acf02018-10-01 22:47:20 +02001508 if (UnimplementedRtpParameterHasValue(parameters)) {
1509 LOG_AND_RETURN_ERROR(
1510 RTCErrorType::UNSUPPORTED_PARAMETER,
1511 "Attempted to set an unimplemented parameter of RtpParameters.");
1512 }
Steve Anton9158ef62017-11-27 13:01:52 -08001513
Florent Castellic1a0bcb2019-01-29 14:26:48 +01001514 auto result = cricket::CheckRtpParametersValues(parameters);
1515 if (!result.ok()) {
1516 LOG_AND_RETURN_ERROR(result.type(), result.message());
1517 }
1518
Steve Anton3d954a62018-04-02 11:27:23 -07001519 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1520 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001521 // Set the sender ID equal to the track ID if the track is specified unless
1522 // that sender ID is already in use.
1523 std::string sender_id =
1524 (track && !FindSenderById(track->id()) ? track->id()
1525 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001526 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
Amit Hilbuchce470aa2019-02-06 17:09:52 -08001527 parameters.encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001528 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1529 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1530 transceiver->internal()->set_direction(init.direction);
1531
Steve Anton22da89f2018-01-25 13:58:07 -08001532 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001533 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001534 }
Steve Antonf9381f02017-12-14 10:23:57 -08001535
1536 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1537}
1538
Steve Anton02ee47c2018-01-10 16:26:06 -08001539rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1540PeerConnection::CreateSender(
1541 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001542 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001543 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001544 const std::vector<std::string>& stream_ids,
1545 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001546 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001547 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1548 RTC_DCHECK(!track ||
1549 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1550 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1551 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001552 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001553 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001554 } else {
1555 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1556 RTC_DCHECK(!track ||
1557 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1558 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001559 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001560 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001561 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001562 bool set_track_succeeded = sender->SetTrack(track);
1563 RTC_DCHECK(set_track_succeeded);
1564 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001565 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001566 return sender;
1567}
1568
1569rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1570PeerConnection::CreateReceiver(cricket::MediaType media_type,
1571 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001572 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1573 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001574 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001575 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001576 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1577 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001578 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001579 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001580 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001581 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001582 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1583 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001584 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001585 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001586 return receiver;
1587}
1588
1589rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1590PeerConnection::CreateAndAddTransceiver(
1591 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1592 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1593 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001594 // Ensure that the new sender does not have an ID that is already in use by
1595 // another sender.
1596 // Allow receiver IDs to conflict since those come from remote SDP (which
1597 // could be invalid, but should not cause a crash).
1598 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001599 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1600 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001601 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001602 transceiver->internal()->SignalNegotiationNeeded.connect(
1603 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001604 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001605}
1606
Steve Anton52d86772018-02-20 15:48:12 -08001607void PeerConnection::OnNegotiationNeeded() {
1608 RTC_DCHECK_RUN_ON(signaling_thread());
1609 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001610 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001611}
1612
deadbeeffac06552015-11-25 11:26:01 -08001613rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001614 const std::string& kind,
1615 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001616 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1617 "Plan SdpSemantics. Please use AddTransceiver "
1618 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001619 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001620 if (IsClosed()) {
1621 return nullptr;
1622 }
Steve Anton4171afb2017-11-20 10:20:22 -08001623
Seth Hampson5b4f0752018-04-02 16:31:36 -07001624 // Internally we need to have one stream with Plan B semantics, so we
1625 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001626 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001627 if (stream_id.empty()) {
1628 stream_ids.push_back(rtc::CreateRandomUuid());
1629 RTC_LOG(LS_INFO)
1630 << "No stream_id specified for sender. Generated stream ID: "
1631 << stream_ids[0];
1632 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001633 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001634 }
1635
Steve Anton4171afb2017-11-20 10:20:22 -08001636 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001637 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001638 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001639 auto* audio_sender = new AudioRtpSender(
1640 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001641 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001642 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001643 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001644 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001645 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001646 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001647 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001648 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001649 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001650 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001651 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001652 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001653 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001654 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001655 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001656 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001657
deadbeefe1f9d832016-01-14 15:35:42 -08001658 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001659}
1660
deadbeef70ab1a12015-09-28 16:53:55 -07001661std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1662 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001663 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001664 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001665 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001666 }
1667 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001668}
1669
Steve Anton4171afb2017-11-20 10:20:22 -08001670std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1671PeerConnection::GetSendersInternal() const {
1672 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1673 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001674 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001675 auto senders = transceiver->internal()->senders();
1676 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1677 }
1678 return all_senders;
1679}
1680
deadbeef70ab1a12015-09-28 16:53:55 -07001681std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1682PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001683 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001684 for (const auto& receiver : GetReceiversInternal()) {
1685 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001686 }
1687 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001688}
1689
Steve Anton4171afb2017-11-20 10:20:22 -08001690std::vector<
1691 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1692PeerConnection::GetReceiversInternal() const {
1693 std::vector<
1694 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1695 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001696 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001697 auto receivers = transceiver->internal()->receivers();
1698 all_receivers.insert(all_receivers.end(), receivers.begin(),
1699 receivers.end());
1700 }
1701 return all_receivers;
1702}
1703
Steve Anton9158ef62017-11-27 13:01:52 -08001704std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1705PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001706 RTC_CHECK(IsUnifiedPlan())
1707 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001708 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001709 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001710 all_transceivers.push_back(transceiver);
1711 }
1712 return all_transceivers;
1713}
1714
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001715bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001716 MediaStreamTrackInterface* track,
1717 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001718 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001719 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001720 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001721 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722 return false;
1723 }
1724
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001725 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001726 // The StatsCollector is used to tell if a track is valid because it may
1727 // remember tracks that the PeerConnection previously removed.
1728 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001729 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1730 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001731 return false;
1732 }
Steve Antonad182762018-09-05 20:22:40 +00001733 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1734 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001735 return true;
1736}
1737
hbos74e1a4f2016-09-15 23:33:01 -07001738void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001739 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001740 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001741 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001742 stats_collector_->GetStatsReport(callback);
1743}
1744
Henrik Boström1df1bf82018-03-20 13:24:20 +01001745void PeerConnection::GetStats(
1746 rtc::scoped_refptr<RtpSenderInterface> selector,
1747 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1748 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1749 RTC_DCHECK(callback);
1750 RTC_DCHECK(stats_collector_);
1751 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1752 if (selector) {
1753 for (const auto& proxy_transceiver : transceivers_) {
1754 for (const auto& proxy_sender :
1755 proxy_transceiver->internal()->senders()) {
1756 if (proxy_sender == selector) {
1757 internal_sender = proxy_sender->internal();
1758 break;
1759 }
1760 }
1761 if (internal_sender)
1762 break;
1763 }
1764 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001765 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001766 // belong to the PeerConnection (in Plan B, senders can be removed from the
1767 // PeerConnection). This means that "all the stats objects representing the
1768 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1769 // produces an empty stats report.
1770 stats_collector_->GetStatsReport(internal_sender, callback);
1771}
1772
1773void PeerConnection::GetStats(
1774 rtc::scoped_refptr<RtpReceiverInterface> selector,
1775 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1776 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1777 RTC_DCHECK(callback);
1778 RTC_DCHECK(stats_collector_);
1779 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1780 if (selector) {
1781 for (const auto& proxy_transceiver : transceivers_) {
1782 for (const auto& proxy_receiver :
1783 proxy_transceiver->internal()->receivers()) {
1784 if (proxy_receiver == selector) {
1785 internal_receiver = proxy_receiver->internal();
1786 break;
1787 }
1788 }
1789 if (internal_receiver)
1790 break;
1791 }
1792 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001793 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001794 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1795 // the PeerConnection). This means that "all the stats objects representing
1796 // the selector" is an empty set. Invoking GetStatsReport() with a null
1797 // selector produces an empty stats report.
1798 stats_collector_->GetStatsReport(internal_receiver, callback);
1799}
1800
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1802 return signaling_state_;
1803}
1804
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805PeerConnectionInterface::IceConnectionState
1806PeerConnection::ice_connection_state() {
1807 return ice_connection_state_;
1808}
1809
Alex Loiko9289eda2018-11-23 16:18:59 +00001810PeerConnectionInterface::IceConnectionState
1811PeerConnection::standardized_ice_connection_state() {
1812 return standardized_ice_connection_state_;
1813}
1814
Jonas Olsson635474e2018-10-18 15:58:17 +02001815PeerConnectionInterface::PeerConnectionState
1816PeerConnection::peer_connection_state() {
1817 return connection_state_;
1818}
1819
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820PeerConnectionInterface::IceGatheringState
1821PeerConnection::ice_gathering_state() {
1822 return ice_gathering_state_;
1823}
1824
Yves Gerey665174f2018-06-19 15:03:05 +02001825rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 const std::string& label,
1827 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001828 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001829
deadbeefab9b2d12015-10-14 11:33:11 -07001830 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001831
kwibergd1fe2812016-04-27 06:47:29 -07001832 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001833 if (config) {
1834 internal_config.reset(new InternalDataChannelInit(*config));
1835 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001836 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001837 InternalCreateDataChannel(label, internal_config.get()));
1838 if (!channel.get()) {
1839 return nullptr;
1840 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001842 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1843 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001844 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001845 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001846 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001847 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001848 return DataChannelProxy::Create(signaling_thread(), channel.get());
1849}
1850
1851void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001852 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001853 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001854
nisse7ce109a2017-01-31 00:57:56 -08001855 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001856 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001857 return;
1858 }
deadbeefab9b2d12015-10-14 11:33:11 -07001859
Steve Anton8d3444d2017-10-20 15:30:51 -07001860 if (IsClosed()) {
1861 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001862 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001863 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001864 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001865 return;
1866 }
1867
zhihuang1c378ed2017-08-17 14:10:50 -07001868 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001869 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001870 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001871 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001872 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001873 return;
1874 }
1875
Steve Anton22da89f2018-01-25 13:58:07 -08001876 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1877 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1878 if (IsUnifiedPlan()) {
1879 RTCError error = HandleLegacyOfferOptions(options);
1880 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001881 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001882 return;
1883 }
1884 }
1885
zhihuang1c378ed2017-08-17 14:10:50 -07001886 cricket::MediaSessionOptions session_options;
1887 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001888 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889}
1890
Steve Anton22da89f2018-01-25 13:58:07 -08001891RTCError PeerConnection::HandleLegacyOfferOptions(
1892 const RTCOfferAnswerOptions& options) {
1893 RTC_DCHECK(IsUnifiedPlan());
1894
1895 if (options.offer_to_receive_audio == 0) {
1896 RemoveRecvDirectionFromReceivingTransceiversOfType(
1897 cricket::MEDIA_TYPE_AUDIO);
1898 } else if (options.offer_to_receive_audio == 1) {
1899 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1900 } else if (options.offer_to_receive_audio > 1) {
1901 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1902 "offer_to_receive_audio > 1 is not supported.");
1903 }
1904
1905 if (options.offer_to_receive_video == 0) {
1906 RemoveRecvDirectionFromReceivingTransceiversOfType(
1907 cricket::MEDIA_TYPE_VIDEO);
1908 } else if (options.offer_to_receive_video == 1) {
1909 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1910 } else if (options.offer_to_receive_video > 1) {
1911 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1912 "offer_to_receive_video > 1 is not supported.");
1913 }
1914
1915 return RTCError::OK();
1916}
1917
1918void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1919 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001920 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001921 RtpTransceiverDirection new_direction =
1922 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1923 if (new_direction != transceiver->direction()) {
1924 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1925 << " transceiver (MID="
1926 << transceiver->mid().value_or("<not set>") << ") from "
1927 << RtpTransceiverDirectionToString(
1928 transceiver->direction())
1929 << " to "
1930 << RtpTransceiverDirectionToString(new_direction)
1931 << " since CreateOffer specified offer_to_receive=0";
1932 transceiver->internal()->set_direction(new_direction);
1933 }
Steve Anton22da89f2018-01-25 13:58:07 -08001934 }
1935}
1936
1937void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1938 cricket::MediaType media_type) {
1939 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001940 RTC_LOG(LS_INFO)
1941 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1942 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001943 RtpTransceiverInit init;
1944 init.direction = RtpTransceiverDirection::kRecvOnly;
1945 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1946 }
1947}
1948
1949std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1950PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1951 std::vector<
1952 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1953 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001954 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001955 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001956 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1957 receiving_transceivers.push_back(transceiver);
1958 }
1959 }
1960 return receiving_transceivers;
1961}
1962
htaa2a49d92016-03-04 02:51:39 -08001963void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1964 const RTCOfferAnswerOptions& options) {
1965 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001966 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001967 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001968 return;
1969 }
1970
Steve Antondffead82018-02-06 10:31:29 -08001971 if (!(signaling_state_ == kHaveRemoteOffer ||
1972 signaling_state_ == kHaveLocalPrAnswer)) {
1973 std::string error =
1974 "PeerConnection cannot create an answer in a state other than "
1975 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001976 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001977 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001978 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001979 return;
1980 }
1981
Steve Antondffead82018-02-06 10:31:29 -08001982 // The remote description should be set if we're in the right state.
1983 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001984
Steve Anton22da89f2018-01-25 13:58:07 -08001985 if (IsUnifiedPlan()) {
1986 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1987 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1988 "supported with Unified Plan semantics. Use the "
1989 "RtpTransceiver API instead.";
1990 }
1991 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1992 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1993 "supported with Unified Plan semantics. Use the "
1994 "RtpTransceiver API instead.";
1995 }
1996 }
1997
htaa2a49d92016-03-04 02:51:39 -08001998 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001999 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08002000
Steve Antond25da372017-11-06 14:50:29 -08002001 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002002}
2003
2004void PeerConnection::SetLocalDescription(
2005 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08002006 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002007 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002008
Steve Anton80dd7b52018-02-16 17:08:42 -08002009 // The SetLocalDescription contract is that we take ownership of the session
2010 // description regardless of the outcome, so wrap it in a unique_ptr right
2011 // away. Ideally, SetLocalDescription's signature will be changed to take the
2012 // description as a unique_ptr argument to formalize this agreement.
2013 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
2014
nisse7ce109a2017-01-31 00:57:56 -08002015 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002016 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002017 return;
2018 }
Steve Anton8a006912017-12-04 15:25:56 -08002019
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002020 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002021 PostSetSessionDescriptionFailure(
2022 observer,
2023 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002024 return;
2025 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002026
Steve Anton80dd7b52018-02-16 17:08:42 -08002027 // If a session error has occurred the PeerConnection is in a possibly
2028 // inconsistent state so fail right away.
2029 if (session_error() != SessionError::kNone) {
2030 std::string error_message = GetSessionErrorMsg();
2031 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002032 PostSetSessionDescriptionFailure(
2033 observer,
2034 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002035 return;
2036 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002037
Steve Anton80dd7b52018-02-16 17:08:42 -08002038 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2039 if (!error.ok()) {
2040 std::string error_message = GetSetDescriptionErrorMessage(
2041 cricket::CS_LOCAL, desc->GetType(), error);
2042 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002043 PostSetSessionDescriptionFailure(
2044 observer,
2045 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002046 return;
2047 }
2048
2049 // Grab the description type before moving ownership to ApplyLocalDescription,
2050 // which may destroy it before returning.
2051 const SdpType type = desc->GetType();
2052
2053 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002054 // |desc| may be destroyed at this point.
2055
2056 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002057 // If ApplyLocalDescription fails, the PeerConnection could be in an
2058 // inconsistent state, so act conservatively here and set the session error
2059 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2060 SetSessionError(SessionError::kContent, error.message());
2061 std::string error_message =
2062 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2063 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002064 PostSetSessionDescriptionFailure(
2065 observer,
2066 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002067 return;
2068 }
Steve Anton8a006912017-12-04 15:25:56 -08002069 RTC_DCHECK(local_description());
2070
2071 PostSetSessionDescriptionSuccess(observer);
2072
Steve Antonad182762018-09-05 20:22:40 +00002073 // MaybeStartGathering needs to be called after posting
2074 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2075 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002076 transport_controller_->MaybeStartGathering();
2077
Steve Antona3a92c22017-12-07 10:27:41 -08002078 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002079 // TODO(deadbeef): We already had to hop to the network thread for
2080 // MaybeStartGathering...
2081 network_thread()->Invoke<void>(
2082 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2083 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002084 // Make UMA notes about what was agreed to.
2085 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002086 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002087 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002088}
2089
2090RTCError PeerConnection::ApplyLocalDescription(
2091 std::unique_ptr<SessionDescriptionInterface> desc) {
2092 RTC_DCHECK_RUN_ON(signaling_thread());
2093 RTC_DCHECK(desc);
2094
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002095 // Update stats here so that we have the most recent stats for tracks and
2096 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002097 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002098
Steve Antondcc3c022017-12-22 16:02:54 -08002099 // Take a reference to the old local description since it's used below to
2100 // compare against the new local description. When setting the new local
2101 // description, grab ownership of the replaced session description in case it
2102 // is the same as |old_local_description|, to keep it alive for the duration
2103 // of the method.
2104 const SessionDescriptionInterface* old_local_description =
2105 local_description();
2106 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002107 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002108 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002109 replaced_local_description = pending_local_description_
2110 ? std::move(pending_local_description_)
2111 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002112 current_local_description_ = std::move(desc);
2113 pending_local_description_ = nullptr;
2114 current_remote_description_ = std::move(pending_remote_description_);
2115 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002116 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002117 pending_local_description_ = std::move(desc);
2118 }
2119 // The session description to apply now must be accessed by
2120 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002121 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002122
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002123 if (!is_caller_) {
2124 if (remote_description()) {
2125 // Remote description was applied first, so this PC is the callee.
2126 is_caller_ = false;
2127 } else {
2128 // Local description is applied first, so this PC is the caller.
2129 is_caller_ = true;
2130 }
2131 }
2132
Zhi Huange830e682018-03-30 10:48:35 -07002133 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2134 if (!error.ok()) {
2135 return error;
2136 }
2137
Steve Antondcc3c022017-12-22 16:02:54 -08002138 if (IsUnifiedPlan()) {
2139 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002140 cricket::CS_LOCAL, *local_description(), old_local_description,
2141 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002142 if (!error.ok()) {
2143 return error;
2144 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002145 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2146 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002147 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002148 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2149 // Note that code paths that don't set MID won't be able to use
2150 // information about DTLS transports.
2151 if (transceiver->mid()) {
2152 auto dtls_transport =
2153 LookupDtlsTransportByMidInternal(*transceiver->mid());
2154 transceiver->internal()->sender_internal()->set_transport(
2155 dtls_transport);
2156 transceiver->internal()->receiver_internal()->set_transport(
2157 dtls_transport);
2158 }
2159
Steve Antondcc3c022017-12-22 16:02:54 -08002160 const ContentInfo* content =
2161 FindMediaSectionForTransceiver(transceiver, local_description());
2162 if (!content) {
2163 continue;
2164 }
2165 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002166 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2167 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002168 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002169 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2170 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2171 // "recvonly", process the removal of a remote track for the media
2172 // description, given transceiver, removeList, and muteTracks.
2173 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2174 (transceiver->internal()->fired_direction() &&
2175 RtpTransceiverDirectionHasRecv(
2176 *transceiver->internal()->fired_direction()))) {
2177 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2178 &removed_streams);
2179 }
2180 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2181 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002182 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002183 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002184 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002185 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002186 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002187 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002188 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002189 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002190 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002191 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002192 }
2193 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002194 // Media channels will be created only when offer is set. These may use new
2195 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002196 if (type == SdpType::kOffer) {
2197 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2198 // description is applied. Restore back to old description.
2199 RTCError error = CreateChannels(*local_description()->description());
2200 if (!error.ok()) {
2201 return error;
2202 }
2203 }
Steve Antondcc3c022017-12-22 16:02:54 -08002204 // Remove unused channels if MediaContentDescription is rejected.
2205 RemoveUnusedChannels(local_description()->description());
2206 }
Steve Anton8a006912017-12-04 15:25:56 -08002207
Zhi Huange830e682018-03-30 10:48:35 -07002208 error = UpdateSessionState(type, cricket::CS_LOCAL,
2209 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002210 if (!error.ok()) {
2211 return error;
2212 }
Steve Antondcc3c022017-12-22 16:02:54 -08002213
Steve Anton8a006912017-12-04 15:25:56 -08002214 if (remote_description()) {
2215 // Now that we have a local description, we can push down remote candidates.
2216 UseCandidatesInSessionDescription(remote_description());
2217 }
2218
2219 pending_ice_restarts_.clear();
2220 if (session_error() != SessionError::kNone) {
2221 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2222 }
2223
deadbeefab9b2d12015-10-14 11:33:11 -07002224 // If setting the description decided our SSL role, allocate any necessary
2225 // SCTP sids.
2226 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002227 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002228 AllocateSctpSids(role);
2229 }
2230
Steve Antond3679212018-01-17 17:41:02 -08002231 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002232 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002233 const ContentInfo* content =
2234 FindMediaSectionForTransceiver(transceiver, local_description());
2235 if (!content) {
2236 continue;
2237 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002238 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2239 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002240 // 0 is a special value meaning "this sender has no associated send
2241 // stream". Need to call this so the sender won't attempt to configure
2242 // a no longer existing stream and run into DCHECKs in the lower
2243 // layers.
2244 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002245 } else {
2246 // Get the StreamParams from the channel which could generate SSRCs.
2247 const std::vector<StreamParams>& streams = channel->local_streams();
2248 transceiver->internal()->sender_internal()->set_stream_ids(
2249 streams[0].stream_ids());
2250 transceiver->internal()->sender_internal()->SetSsrc(
2251 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002252 }
2253 }
2254 } else {
2255 // Plan B semantics.
2256
Steve Antondcc3c022017-12-22 16:02:54 -08002257 // Update state and SSRC of local MediaStreams and DataChannels based on the
2258 // local session description.
2259 const cricket::ContentInfo* audio_content =
2260 GetFirstAudioContent(local_description()->description());
2261 if (audio_content) {
2262 if (audio_content->rejected) {
2263 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2264 } else {
2265 const cricket::AudioContentDescription* audio_desc =
2266 audio_content->media_description()->as_audio();
2267 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2268 }
deadbeeffaac4972015-11-12 15:33:07 -08002269 }
deadbeefab9b2d12015-10-14 11:33:11 -07002270
Steve Antondcc3c022017-12-22 16:02:54 -08002271 const cricket::ContentInfo* video_content =
2272 GetFirstVideoContent(local_description()->description());
2273 if (video_content) {
2274 if (video_content->rejected) {
2275 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2276 } else {
2277 const cricket::VideoContentDescription* video_desc =
2278 video_content->media_description()->as_video();
2279 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2280 }
deadbeeffaac4972015-11-12 15:33:07 -08002281 }
deadbeefab9b2d12015-10-14 11:33:11 -07002282 }
2283
2284 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002285 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002286 if (data_content) {
2287 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002288 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002289 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002290 cricket::kMediaProtocolRtpPrefix)) {
2291 UpdateLocalRtpDataChannels(data_desc->streams());
2292 }
2293 }
2294
Steve Anton8a006912017-12-04 15:25:56 -08002295 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002296}
2297
Steve Anton06817cd2018-12-18 15:55:30 -08002298// The SDP parser used to populate these values by default for the 'content
2299// name' if an a=mid line was absent.
2300static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2301 switch (media_type) {
2302 case cricket::MEDIA_TYPE_AUDIO:
2303 return cricket::CN_AUDIO;
2304 case cricket::MEDIA_TYPE_VIDEO:
2305 return cricket::CN_VIDEO;
2306 case cricket::MEDIA_TYPE_DATA:
2307 return cricket::CN_DATA;
2308 }
2309 RTC_NOTREACHED();
2310 return "";
2311}
2312
2313void PeerConnection::FillInMissingRemoteMids(
2314 cricket::SessionDescription* remote_description) {
2315 RTC_DCHECK(remote_description);
2316 const cricket::ContentInfos& local_contents =
2317 (local_description() ? local_description()->description()->contents()
2318 : cricket::ContentInfos());
Steve Anton06817cd2018-12-18 15:55:30 -08002319 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2320 cricket::ContentInfo& content = remote_description->contents()[i];
2321 if (!content.name.empty()) {
2322 continue;
2323 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002324 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002325 absl::string_view source_explanation;
2326 if (IsUnifiedPlan()) {
2327 if (i < local_contents.size()) {
2328 new_mid = local_contents[i].name;
2329 source_explanation = "from the matching local media section";
2330 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002331 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002332 source_explanation = "generated just now";
2333 }
2334 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002335 new_mid = std::string(
2336 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002337 source_explanation = "to match pre-existing behavior";
2338 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002339 content.name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002340 remote_description->transport_infos()[i].content_name =
2341 std::string(new_mid);
2342 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2343 << " is missing an a=mid line. Filling in the value '"
2344 << new_mid << "' " << source_explanation << ".";
2345 }
2346}
2347
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002348void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002349 SetSessionDescriptionObserver* observer,
2350 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002351 SetRemoteDescription(
2352 std::unique_ptr<SessionDescriptionInterface>(desc),
2353 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2354 new SetRemoteDescriptionObserverAdapter(this, observer)));
2355}
2356
2357void PeerConnection::SetRemoteDescription(
2358 std::unique_ptr<SessionDescriptionInterface> desc,
2359 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002360 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002361
nisse7ce109a2017-01-31 00:57:56 -08002362 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002363 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002364 return;
2365 }
Steve Anton8a006912017-12-04 15:25:56 -08002366
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002367 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002368 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002369 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002370 return;
2371 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002372
Steve Anton80dd7b52018-02-16 17:08:42 -08002373 // If a session error has occurred the PeerConnection is in a possibly
2374 // inconsistent state so fail right away.
2375 if (session_error() != SessionError::kNone) {
2376 std::string error_message = GetSessionErrorMsg();
2377 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2378 observer->OnSetRemoteDescriptionComplete(
2379 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2380 return;
2381 }
Steve Anton71439a62018-02-15 11:53:06 -08002382
Steve Antonba42e992018-04-09 14:10:01 -07002383 if (desc->GetType() == SdpType::kOffer) {
2384 // Report to UMA the format of the received offer.
2385 ReportSdpFormatReceived(*desc);
2386 }
2387
Steve Anton06817cd2018-12-18 15:55:30 -08002388 // Handle remote descriptions missing a=mid lines for interop with legacy end
2389 // points.
2390 FillInMissingRemoteMids(desc->description());
2391
Steve Anton80dd7b52018-02-16 17:08:42 -08002392 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002393 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002394 std::string error_message = GetSetDescriptionErrorMessage(
2395 cricket::CS_REMOTE, desc->GetType(), error);
2396 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002397 observer->OnSetRemoteDescriptionComplete(
2398 RTCError(error.type(), std::move(error_message)));
2399 return;
2400 }
Steve Anton71439a62018-02-15 11:53:06 -08002401
Steve Anton80dd7b52018-02-16 17:08:42 -08002402 // Grab the description type before moving ownership to
2403 // ApplyRemoteDescription, which may destroy it before returning.
2404 const SdpType type = desc->GetType();
2405
2406 error = ApplyRemoteDescription(std::move(desc));
2407 // |desc| may be destroyed at this point.
2408
2409 if (!error.ok()) {
2410 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2411 // inconsistent state, so act conservatively here and set the session error
2412 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2413 SetSessionError(SessionError::kContent, error.message());
2414 std::string error_message =
2415 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2416 RTC_LOG(LS_ERROR) << error_message;
2417 observer->OnSetRemoteDescriptionComplete(
2418 RTCError(error.type(), std::move(error_message)));
2419 return;
2420 }
2421 RTC_DCHECK(remote_description());
2422
2423 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002424 // TODO(deadbeef): We already had to hop to the network thread for
2425 // MaybeStartGathering...
2426 network_thread()->Invoke<void>(
2427 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2428 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002429 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002430 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002431 }
2432
2433 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002434 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002435}
2436
2437RTCError PeerConnection::ApplyRemoteDescription(
2438 std::unique_ptr<SessionDescriptionInterface> desc) {
2439 RTC_DCHECK_RUN_ON(signaling_thread());
2440 RTC_DCHECK(desc);
2441
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442 // Update stats here so that we have the most recent stats for tracks and
2443 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002444 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002445
Steve Antondcc3c022017-12-22 16:02:54 -08002446 // Take a reference to the old remote description since it's used below to
2447 // compare against the new remote description. When setting the new remote
2448 // description, grab ownership of the replaced session description in case it
2449 // is the same as |old_remote_description|, to keep it alive for the duration
2450 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002451 const SessionDescriptionInterface* old_remote_description =
2452 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002453 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002454 SdpType type = desc->GetType();
2455 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002456 replaced_remote_description = pending_remote_description_
2457 ? std::move(pending_remote_description_)
2458 : std::move(current_remote_description_);
2459 current_remote_description_ = std::move(desc);
2460 pending_remote_description_ = nullptr;
2461 current_local_description_ = std::move(pending_local_description_);
2462 } else {
2463 replaced_remote_description = std::move(pending_remote_description_);
2464 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465 }
Steve Anton8a006912017-12-04 15:25:56 -08002466 // The session description to apply now must be accessed by
2467 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002468 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002469
Zhi Huange830e682018-03-30 10:48:35 -07002470 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2471 if (!error.ok()) {
2472 return error;
2473 }
Steve Anton8a006912017-12-04 15:25:56 -08002474 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002475 if (IsUnifiedPlan()) {
2476 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002477 cricket::CS_REMOTE, *remote_description(), local_description(),
2478 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002479 if (!error.ok()) {
2480 return error;
2481 }
Steve Antondcc3c022017-12-22 16:02:54 -08002482 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002483 // Media channels will be created only when offer is set. These may use new
2484 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002485 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002486 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002487 // description is applied. Restore back to old description.
2488 RTCError error = CreateChannels(*remote_description()->description());
2489 if (!error.ok()) {
2490 return error;
2491 }
2492 }
Steve Antondcc3c022017-12-22 16:02:54 -08002493 // Remove unused channels if MediaContentDescription is rejected.
2494 RemoveUnusedChannels(remote_description()->description());
2495 }
Steve Anton8a006912017-12-04 15:25:56 -08002496
Zhi Huange830e682018-03-30 10:48:35 -07002497 // NOTE: Candidates allocation will be initiated only when
2498 // SetLocalDescription is called.
2499 error = UpdateSessionState(type, cricket::CS_REMOTE,
2500 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002501 if (!error.ok()) {
2502 return error;
2503 }
2504
2505 if (local_description() &&
2506 !UseCandidatesInSessionDescription(remote_description())) {
2507 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2508 }
2509
2510 if (old_remote_description) {
2511 for (const cricket::ContentInfo& content :
2512 old_remote_description->description()->contents()) {
2513 // Check if this new SessionDescription contains new ICE ufrag and
2514 // password that indicates the remote peer requests an ICE restart.
2515 // TODO(deadbeef): When we start storing both the current and pending
2516 // remote description, this should reset pending_ice_restarts and compare
2517 // against the current description.
2518 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2519 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002520 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002521 pending_ice_restarts_.insert(content.name);
2522 }
2523 } else {
2524 // We retain all received candidates only if ICE is not restarted.
2525 // When ICE is restarted, all previous candidates belong to an old
2526 // generation and should not be kept.
2527 // TODO(deadbeef): This goes against the W3C spec which says the remote
2528 // description should only contain candidates from the last set remote
2529 // description plus any candidates added since then. We should remove
2530 // this once we're sure it won't break anything.
2531 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2532 old_remote_description, content.name, mutable_remote_description());
2533 }
2534 }
2535 }
2536
2537 if (session_error() != SessionError::kNone) {
2538 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2539 }
2540
2541 // Set the the ICE connection state to connecting since the connection may
2542 // become writable with peer reflexive candidates before any remote candidate
2543 // is signaled.
2544 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2545 // is to have a new signal the indicates a change in checking state from the
2546 // transport and expose a new checking() member from transport that can be
2547 // read to determine the current checking state. The existing SignalConnecting
2548 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002549 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002550 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002551 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2552 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2553 }
2554
deadbeefab9b2d12015-10-14 11:33:11 -07002555 // If setting the description decided our SSL role, allocate any necessary
2556 // SCTP sids.
2557 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002558 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002559 AllocateSctpSids(role);
2560 }
2561
Steve Antondcc3c022017-12-22 16:02:54 -08002562 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002563 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002564 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002565 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002566 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002567 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002568 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002569 const ContentInfo* content =
2570 FindMediaSectionForTransceiver(transceiver, remote_description());
2571 if (!content) {
2572 continue;
2573 }
2574 const MediaContentDescription* media_desc = content->media_description();
2575 RtpTransceiverDirection local_direction =
2576 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002577 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2578 // RTCSessionDescription: Set the associated remote streams given
2579 // transceiver.[[Receiver]], msids, addList, and removeList".
2580 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2581 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2582 std::vector<std::string> stream_ids;
2583 if (!media_desc->streams().empty()) {
2584 // The remote description has signaled the stream IDs.
2585 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002586 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002587 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2588 << " (" << GetStreamIdsString(stream_ids) << ").";
2589 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2590 stream_ids, &added_streams,
2591 &removed_streams);
2592 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2593 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2594 // and transceiver's current direction is neither sendrecv nor recvonly,
2595 // process the addition of a remote track for the media description.
2596 if (!transceiver->fired_direction() ||
2597 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2598 RTC_LOG(LS_INFO)
2599 << "Processing the addition of a remote track for MID="
2600 << content->name << ".";
2601 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002602 }
Steve Antondcc3c022017-12-22 16:02:54 -08002603 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002604 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002605 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2606 // removal of a remote track for the media description, given transceiver,
2607 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002608 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002609 (transceiver->fired_direction() &&
2610 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2611 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2612 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002613 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002614 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002615 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002616 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002617 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002618 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002619 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002620 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002621 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002622 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2623 if (transceiver->mid()) {
2624 auto dtls_transport =
2625 LookupDtlsTransportByMidInternal(*transceiver->mid());
2626 transceiver->internal()->sender_internal()->set_transport(
2627 dtls_transport);
2628 transceiver->internal()->receiver_internal()->set_transport(
2629 dtls_transport);
2630 }
Steve Antondcc3c022017-12-22 16:02:54 -08002631 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002632 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002633 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002634 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002635 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2636 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002637 transceiver->Stop();
2638 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002639 if (!content->rejected &&
2640 RtpTransceiverDirectionHasRecv(local_direction)) {
2641 // Set ssrc to 0 in the case of an unsignalled ssrc.
2642 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002643 if (!media_desc->streams().empty() &&
2644 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002645 ssrc = media_desc->streams()[0].first_ssrc();
2646 }
2647 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002648 }
Steve Antondcc3c022017-12-22 16:02:54 -08002649 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002650 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002651 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002652 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002653 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002654 observer->OnTrack(transceiver);
2655 observer->OnAddTrack(transceiver->receiver(),
2656 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002657 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002658 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002659 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002660 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002661 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002662 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002663 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002664 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002665 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002666 }
Steve Antondcc3c022017-12-22 16:02:54 -08002667 }
2668
Henrik Boströmfdb92012017-11-09 19:55:44 +01002669 const cricket::ContentInfo* audio_content =
2670 GetFirstAudioContent(remote_description()->description());
2671 const cricket::ContentInfo* video_content =
2672 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002673 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002674 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002675 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002676 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002677 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002678 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002679
2680 // Check if the descriptions include streams, just in case the peer supports
2681 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002682 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002683 (audio_desc && !audio_desc->streams().empty()) ||
2684 (video_desc && !video_desc->streams().empty())) {
2685 remote_peer_supports_msid_ = true;
2686 }
deadbeefab9b2d12015-10-14 11:33:11 -07002687
2688 // We wait to signal new streams until we finish processing the description,
2689 // since only at that point will new streams have all their tracks.
2690 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2691
Steve Antondcc3c022017-12-22 16:02:54 -08002692 if (!IsUnifiedPlan()) {
2693 // TODO(steveanton): When removing RTP senders/receivers in response to a
2694 // rejected media section, there is some cleanup logic that expects the
2695 // voice/ video channel to still be set. But in this method the voice/video
2696 // channel would have been destroyed by the SetRemoteDescription caller
2697 // above so the cleanup that relies on them fails to run. The RemoveSenders
2698 // calls should be moved to right before the DestroyChannel calls to fix
2699 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002700
Steve Antondcc3c022017-12-22 16:02:54 -08002701 // Find all audio rtp streams and create corresponding remote AudioTracks
2702 // and MediaStreams.
2703 if (audio_content) {
2704 if (audio_content->rejected) {
2705 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2706 } else {
2707 bool default_audio_track_needed =
2708 !remote_peer_supports_msid_ &&
2709 RtpTransceiverDirectionHasSend(audio_desc->direction());
2710 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2711 default_audio_track_needed, audio_desc->type(),
2712 new_streams);
2713 }
deadbeeffaac4972015-11-12 15:33:07 -08002714 }
deadbeefab9b2d12015-10-14 11:33:11 -07002715
Steve Antondcc3c022017-12-22 16:02:54 -08002716 // Find all video rtp streams and create corresponding remote VideoTracks
2717 // and MediaStreams.
2718 if (video_content) {
2719 if (video_content->rejected) {
2720 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2721 } else {
2722 bool default_video_track_needed =
2723 !remote_peer_supports_msid_ &&
2724 RtpTransceiverDirectionHasSend(video_desc->direction());
2725 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2726 default_video_track_needed, video_desc->type(),
2727 new_streams);
2728 }
deadbeeffaac4972015-11-12 15:33:07 -08002729 }
deadbeefab9b2d12015-10-14 11:33:11 -07002730
Steve Antondcc3c022017-12-22 16:02:54 -08002731 // Update the DataChannels with the information from the remote peer.
2732 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002733 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002734 cricket::kMediaProtocolRtpPrefix)) {
2735 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2736 }
deadbeefab9b2d12015-10-14 11:33:11 -07002737 }
deadbeefab9b2d12015-10-14 11:33:11 -07002738
Steve Antondcc3c022017-12-22 16:02:54 -08002739 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002740 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002741 for (size_t i = 0; i < new_streams->count(); ++i) {
2742 MediaStreamInterface* new_stream = new_streams->at(i);
2743 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002744 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002745 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2746 }
deadbeefab9b2d12015-10-14 11:33:11 -07002747
Steve Antondcc3c022017-12-22 16:02:54 -08002748 UpdateEndedRemoteMediaStreams();
2749 }
deadbeefab9b2d12015-10-14 11:33:11 -07002750
Steve Anton8a006912017-12-04 15:25:56 -08002751 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002752}
2753
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002754void PeerConnection::SetAssociatedRemoteStreams(
2755 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2756 const std::vector<std::string>& stream_ids,
2757 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2758 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2759 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2760 for (const std::string& stream_id : stream_ids) {
2761 rtc::scoped_refptr<MediaStreamInterface> stream =
2762 remote_streams_->find(stream_id);
2763 if (!stream) {
2764 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2765 MediaStream::Create(stream_id));
2766 remote_streams_->AddStream(stream);
2767 added_streams->push_back(stream);
2768 }
2769 media_streams.push_back(stream);
2770 }
2771 // Special case: "a=msid" missing, use random stream ID.
2772 if (media_streams.empty() &&
2773 !(remote_description()->description()->msid_signaling() &
2774 cricket::kMsidSignalingMediaSection)) {
2775 if (!missing_msid_default_stream_) {
2776 missing_msid_default_stream_ = MediaStreamProxy::Create(
2777 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2778 added_streams->push_back(missing_msid_default_stream_);
2779 }
2780 media_streams.push_back(missing_msid_default_stream_);
2781 }
2782 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2783 receiver->streams();
2784 // SetStreams() will add/remove the receiver's track to/from the streams. This
2785 // differs from the spec - the spec uses an "addList" and "removeList" to
2786 // update the stream-track relationships in a later step. We do this earlier,
2787 // changing the order of things, but the end-result is the same.
2788 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2789 // instead. https://crbug.com/webrtc/9480
2790 receiver->SetStreams(media_streams);
2791 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2792}
2793
Steve Anton0f5400a2018-07-17 14:25:36 -07002794void PeerConnection::ProcessRemovalOfRemoteTrack(
2795 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2796 transceiver,
2797 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2798 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2799 RTC_DCHECK(transceiver->mid());
2800 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2801 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002802 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002803 transceiver->internal()->receiver_internal()->streams();
2804 // This will remove the remote track from the streams.
2805 transceiver->internal()->receiver_internal()->set_stream_ids({});
2806 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002807 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2808}
2809
2810void PeerConnection::RemoveRemoteStreamsIfEmpty(
2811 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2812 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2813 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2814 // streams, see if the stream was removed by checking if this was the last
2815 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002816 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002817 if (remote_stream->GetAudioTracks().empty() &&
2818 remote_stream->GetVideoTracks().empty()) {
2819 remote_streams_->RemoveStream(remote_stream);
2820 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002821 }
2822 }
2823}
2824
Steve Antondcc3c022017-12-22 16:02:54 -08002825RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2826 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002827 const SessionDescriptionInterface& new_session,
2828 const SessionDescriptionInterface* old_local_description,
2829 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002830 RTC_DCHECK(IsUnifiedPlan());
2831
Steve Anton7464fca2018-01-19 11:10:37 -08002832 const cricket::ContentGroup* bundle_group = nullptr;
2833 if (new_session.GetType() == SdpType::kOffer) {
2834 auto bundle_group_or_error =
2835 GetEarlyBundleGroup(*new_session.description());
2836 if (!bundle_group_or_error.ok()) {
2837 return bundle_group_or_error.MoveError();
2838 }
2839 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002840 }
Steve Antondcc3c022017-12-22 16:02:54 -08002841
Steve Antondcc3c022017-12-22 16:02:54 -08002842 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002843 for (size_t i = 0; i < new_contents.size(); ++i) {
2844 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002845 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002846 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002847 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2848 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002849 const cricket::ContentInfo* old_local_content = nullptr;
2850 if (old_local_description &&
2851 i < old_local_description->description()->contents().size()) {
2852 old_local_content =
2853 &old_local_description->description()->contents()[i];
2854 }
2855 const cricket::ContentInfo* old_remote_content = nullptr;
2856 if (old_remote_description &&
2857 i < old_remote_description->description()->contents().size()) {
2858 old_remote_content =
2859 &old_remote_description->description()->contents()[i];
2860 }
Steve Antondcc3c022017-12-22 16:02:54 -08002861 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002862 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2863 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002864 if (!transceiver_or_error.ok()) {
2865 return transceiver_or_error.MoveError();
2866 }
2867 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002868 RTCError error =
2869 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2870 if (!error.ok()) {
2871 return error;
2872 }
2873 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002874 if (GetDataMid() && new_content.name != *GetDataMid()) {
2875 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002876 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2877 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002878 continue;
2879 }
2880 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2881 if (!error.ok()) {
2882 return error;
2883 }
Steve Antondcc3c022017-12-22 16:02:54 -08002884 } else {
2885 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2886 "Unknown section type.");
2887 }
2888 }
2889
2890 return RTCError::OK();
2891}
2892
2893RTCError PeerConnection::UpdateTransceiverChannel(
2894 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2895 transceiver,
2896 const cricket::ContentInfo& content,
2897 const cricket::ContentGroup* bundle_group) {
2898 RTC_DCHECK(IsUnifiedPlan());
2899 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002900 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002901 if (content.rejected) {
2902 if (channel) {
2903 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002904 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002905 }
2906 } else {
2907 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002908 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002909 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002910 } else {
Steve Anton69470252018-02-09 11:43:08 -08002911 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002912 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002913 }
2914 if (!channel) {
2915 LOG_AND_RETURN_ERROR(
2916 RTCErrorType::INTERNAL_ERROR,
2917 "Failed to create channel for mid=" + content.name);
2918 }
2919 transceiver->internal()->SetChannel(channel);
2920 }
2921 }
2922 return RTCError::OK();
2923}
2924
Steve Antonfa2260d2017-12-28 16:38:23 -08002925RTCError PeerConnection::UpdateDataChannel(
2926 cricket::ContentSource source,
2927 const cricket::ContentInfo& content,
2928 const cricket::ContentGroup* bundle_group) {
2929 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002930 // If data channels are disabled, ignore this media section. CreateAnswer
2931 // will take care of rejecting it.
2932 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002933 }
2934 if (content.rejected) {
2935 DestroyDataChannel();
2936 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002937 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002938 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002939 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2940 "Failed to create data channel.");
2941 }
2942 }
2943 if (source == cricket::CS_REMOTE) {
2944 const MediaContentDescription* data_desc = content.media_description();
2945 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2946 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2947 }
2948 }
2949 }
2950 return RTCError::OK();
2951}
2952
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002953// This method will extract any send encodings that were sent by the remote
2954// connection. This is currently only relevant for Simulcast scenario (where
2955// the number of layers may be communicated by the server).
2956static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2957 const MediaContentDescription& desc) {
2958 if (!desc.HasSimulcast()) {
2959 return {};
2960 }
2961 std::vector<RtpEncodingParameters> result;
2962 const SimulcastDescription& simulcast = desc.simulcast_description();
2963
2964 // This is a remote description, the parameters we are after should appear
2965 // as receive streams.
2966 for (const auto& alternatives : simulcast.receive_layers()) {
2967 RTC_DCHECK(!alternatives.empty());
2968 // There is currently no way to specify or choose from alternatives.
2969 // We will always use the first alternative, which is the most preferred.
2970 const SimulcastLayer& layer = alternatives[0];
2971 RtpEncodingParameters parameters;
2972 parameters.rid = layer.rid;
2973 parameters.active = !layer.is_paused;
2974 result.push_back(parameters);
2975 }
2976
2977 return result;
2978}
2979
2980static RTCError UpdateSimulcastLayerStatusInSender(
2981 const std::vector<SimulcastLayer>& layers,
2982 RtpSenderInterface* sender) {
2983 RTC_DCHECK(sender);
2984 RtpParameters parameters = sender->GetParameters();
2985
2986 // The simulcast envelope cannot be changed, only the status of the streams.
2987 // So we will iterate over the send encodings rather than the layers.
2988 for (RtpEncodingParameters& encoding : parameters.encodings) {
2989 auto iter = std::find_if(layers.begin(), layers.end(),
2990 [&encoding](const SimulcastLayer& layer) {
2991 return layer.rid == encoding.rid;
2992 });
2993 // A layer that cannot be found may have been removed by the remote party.
2994 encoding.active = iter != layers.end() && !iter->is_paused;
2995 }
2996
2997 return sender->SetParameters(parameters);
2998}
2999
3000static RTCError DisableSimulcastInSender(RtpSenderInterface* sender) {
3001 RTC_DCHECK(sender);
3002 RtpParameters parameters = sender->GetParameters();
3003 if (parameters.encodings.empty()) {
3004 return RTCError::OK();
3005 }
3006
3007 bool first_layer_status = parameters.encodings[0].active;
3008 for (RtpEncodingParameters& encoding : parameters.encodings) {
3009 // TODO(bugs.webrtc.org/10251): Active does not really disable the layer.
3010 // The user might enable it at a later point in time even though it was
3011 // rejected.
3012 encoding.active = false;
3013 }
3014 parameters.encodings[0].active = first_layer_status;
3015
3016 return sender->SetParameters(parameters);
3017}
3018
Steve Antondcc3c022017-12-22 16:02:54 -08003019RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
3020PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003021 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08003022 size_t mline_index,
3023 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003024 const ContentInfo* old_local_content,
3025 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08003026 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003027 // If this is an offer then the m= section might be recycled. If the m=
3028 // section is being recycled (defined as: rejected in the current local or
3029 // remote description and not rejected in new description), dissociate the
3030 // currently associated RtpTransceiver by setting its mid property to null,
3031 // and discard the mapping between the transceiver and its m= section index.
3032 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3033 old_remote_content)) {
3034 // We want to dissociate the transceiver that has the rejected mid.
3035 const std::string& old_mid =
3036 (old_local_content && old_local_content->rejected)
3037 ? old_local_content->name
3038 : old_remote_content->name;
3039 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003040 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003041 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3042 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003043 old_transceiver->internal()->set_mid(absl::nullopt);
3044 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003045 }
3046 }
3047 const MediaContentDescription* media_desc = content.media_description();
3048 auto transceiver = GetAssociatedTransceiver(content.name);
3049 if (source == cricket::CS_LOCAL) {
3050 // Find the RtpTransceiver that corresponds to this m= section, using the
3051 // mapping between transceivers and m= section indices established when
3052 // creating the offer.
3053 if (!transceiver) {
3054 transceiver = GetTransceiverByMLineIndex(mline_index);
3055 }
3056 if (!transceiver) {
3057 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3058 "Unknown transceiver");
3059 }
3060 } else {
3061 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3062 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3063 // of the same type...
Amit Hilbuchce470aa2019-02-06 17:09:52 -08003064 // When simulcast is requested, a transceiver cannot be associated because
3065 // AddTrack cannot be called to initialize it.
Steve Antondcc3c022017-12-22 16:02:54 -08003066 if (!transceiver &&
Amit Hilbuchce470aa2019-02-06 17:09:52 -08003067 RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
3068 !media_desc->HasSimulcast()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003069 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3070 }
3071 // If no RtpTransceiver was found in the previous step, create one with a
3072 // recvonly direction.
3073 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003074 RTC_LOG(LS_INFO) << "Adding "
3075 << cricket::MediaTypeToString(media_desc->type())
3076 << " transceiver for MID=" << content.name
3077 << " at i=" << mline_index
3078 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003079 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003080 std::vector<RtpEncodingParameters> send_encodings =
3081 GetSendEncodingsFromRemoteDescription(*media_desc);
3082 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3083 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003084 std::string receiver_id;
3085 if (!media_desc->streams().empty()) {
3086 receiver_id = media_desc->streams()[0].id;
3087 } else {
3088 receiver_id = rtc::CreateRandomUuid();
3089 }
3090 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003091 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003092 transceiver->internal()->set_direction(
3093 RtpTransceiverDirection::kRecvOnly);
3094 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003095
3096 // Check if the offer indicated simulcast but the answer rejected it.
3097 // This can happen when simulcast is not supported on the remote party.
3098 // This check can be simplified to comparing the number of send encodings,
3099 // but that might break legacy implementation in which simulcast is not
3100 // signaled in the remote description.
3101 if (old_local_content && old_local_content->media_description() &&
3102 old_local_content->media_description()->HasSimulcast() &&
3103 !media_desc->HasSimulcast()) {
3104 RTCError error =
3105 DisableSimulcastInSender(transceiver->internal()->sender());
3106 if (!error.ok()) {
3107 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3108 return std::move(error);
3109 }
3110 }
Steve Antondcc3c022017-12-22 16:02:54 -08003111 }
3112 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003113 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003114 LOG_AND_RETURN_ERROR(
3115 RTCErrorType::INVALID_PARAMETER,
3116 "Transceiver type does not match media description type.");
3117 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003118 if (media_desc->HasSimulcast()) {
3119 std::vector<SimulcastLayer> layers =
3120 source == cricket::CS_LOCAL
3121 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3122 : media_desc->simulcast_description()
3123 .receive_layers()
3124 .GetAllLayers();
3125 RTCError error = UpdateSimulcastLayerStatusInSender(
3126 layers, transceiver->internal()->sender());
3127 if (!error.ok()) {
3128 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3129 return std::move(error);
3130 }
3131 }
Steve Antondcc3c022017-12-22 16:02:54 -08003132 // Associate the found or created RtpTransceiver with the m= section by
3133 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3134 // section, and establish a mapping between the transceiver and the index of
3135 // the m= section.
3136 transceiver->internal()->set_mid(content.name);
3137 transceiver->internal()->set_mline_index(mline_index);
3138 return std::move(transceiver);
3139}
3140
3141rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3142PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3143 RTC_DCHECK(IsUnifiedPlan());
3144 for (auto transceiver : transceivers_) {
3145 if (transceiver->mid() == mid) {
3146 return transceiver;
3147 }
3148 }
3149 return nullptr;
3150}
3151
3152rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3153PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3154 RTC_DCHECK(IsUnifiedPlan());
3155 for (auto transceiver : transceivers_) {
3156 if (transceiver->internal()->mline_index() == mline_index) {
3157 return transceiver;
3158 }
3159 }
3160 return nullptr;
3161}
3162
3163rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3164PeerConnection::FindAvailableTransceiverToReceive(
3165 cricket::MediaType media_type) const {
3166 RTC_DCHECK(IsUnifiedPlan());
3167 // From JSEP section 5.10 (Applying a Remote Description):
3168 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3169 // the same type that were added to the PeerConnection by addTrack and are not
3170 // associated with any m= section and are not stopped, find the first such
3171 // RtpTransceiver.
3172 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003173 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003174 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3175 !transceiver->stopped()) {
3176 return transceiver;
3177 }
3178 }
3179 return nullptr;
3180}
3181
Steve Antoned10bd92017-12-05 10:52:59 -08003182const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3183 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3184 transceiver,
3185 const SessionDescriptionInterface* sdesc) const {
3186 RTC_DCHECK(transceiver);
3187 RTC_DCHECK(sdesc);
3188 if (IsUnifiedPlan()) {
3189 if (!transceiver->internal()->mid()) {
3190 // This transceiver is not associated with a media section yet.
3191 return nullptr;
3192 }
3193 return sdesc->description()->GetContentByName(
3194 *transceiver->internal()->mid());
3195 } else {
3196 // Plan B only allows at most one audio and one video section, so use the
3197 // first media section of that type.
3198 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003199 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003200 }
3201}
3202
deadbeef46c73892016-11-16 19:42:04 -08003203PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3204 return configuration_;
3205}
3206
deadbeef293e9262017-01-11 12:28:30 -08003207bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3208 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003209 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003210 if (IsClosed()) {
3211 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3212 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3213 }
3214
Qingsi Wanga2d60672018-04-11 16:57:45 -07003215 // According to JSEP, after setLocalDescription, changing the candidate pool
3216 // size is not allowed, and changing the set of ICE servers will not result
3217 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003218 if (local_description() && configuration.ice_candidate_pool_size !=
3219 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003220 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3221 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003222 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003223 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003224
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003225 if (local_description() &&
3226 configuration.use_media_transport != configuration_.use_media_transport) {
3227 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3228 "SetLocalDescription.";
3229 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3230 }
3231
3232 if (remote_description() &&
3233 configuration.use_media_transport != configuration_.use_media_transport) {
3234 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3235 "SetRemoteDescription.";
3236 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3237 }
3238
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003239 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003240 configuration.use_media_transport_for_data_channels !=
3241 configuration_.use_media_transport_for_data_channels) {
3242 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3243 "after calling SetLocalDescription.";
3244 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3245 }
3246
3247 if (remote_description() &&
3248 configuration.use_media_transport_for_data_channels !=
3249 configuration_.use_media_transport_for_data_channels) {
3250 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3251 "after calling SetRemoteDescription.";
3252 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3253 }
3254
3255 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003256 configuration.crypto_options != configuration_.crypto_options) {
3257 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3258 "SetLocalDescription.";
3259 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3260 }
3261
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003262 if (configuration.use_media_transport_for_data_channels ||
3263 configuration.use_media_transport) {
3264 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3265 << "Media transport requires MaxBundle policy.";
3266 }
3267
deadbeef293e9262017-01-11 12:28:30 -08003268 // The simplest (and most future-compatible) way to tell if the config was
3269 // modified in an invalid way is to copy each property we do support
3270 // modifying, then use operator==. There are far more properties we don't
3271 // support modifying than those we do, and more could be added.
3272 RTCConfiguration modified_config = configuration_;
3273 modified_config.servers = configuration.servers;
3274 modified_config.type = configuration.type;
3275 modified_config.ice_candidate_pool_size =
3276 configuration.ice_candidate_pool_size;
3277 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003278 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003279 modified_config.ice_check_interval_strong_connectivity =
3280 configuration.ice_check_interval_strong_connectivity;
3281 modified_config.ice_check_interval_weak_connectivity =
3282 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003283 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3284 modified_config.ice_unwritable_min_checks =
3285 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003286 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003287 modified_config.stun_candidate_keepalive_interval =
3288 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003289 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003290 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003291 modified_config.active_reset_srtp_params =
3292 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003293 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003294 modified_config.use_media_transport_for_data_channels =
3295 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003296 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003297 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003298 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3299 }
3300
Steve Anton038834f2017-07-14 15:59:59 -07003301 // Validate the modified configuration.
3302 RTCError validate_error = ValidateConfiguration(modified_config);
3303 if (!validate_error.ok()) {
3304 return SafeSetError(std::move(validate_error), error);
3305 }
3306
deadbeef293e9262017-01-11 12:28:30 -08003307 // Note that this isn't possible through chromium, since it's an unsigned
3308 // short in WebIDL.
3309 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003310 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003311 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3312 }
3313
3314 // Parse ICE servers before hopping to network thread.
3315 cricket::ServerAddresses stun_servers;
3316 std::vector<cricket::RelayServerConfig> turn_servers;
3317 RTCErrorType parse_error =
3318 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3319 if (parse_error != RTCErrorType::NONE) {
3320 return SafeSetError(parse_error, error);
3321 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003322 // Note if STUN or TURN servers were supplied.
3323 if (!stun_servers.empty()) {
3324 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3325 }
3326 if (!turn_servers.empty()) {
3327 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3328 }
deadbeef293e9262017-01-11 12:28:30 -08003329
3330 // In theory this shouldn't fail.
3331 if (!network_thread()->Invoke<bool>(
3332 RTC_FROM_HERE,
3333 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3334 stun_servers, turn_servers, modified_config.type,
3335 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003336 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003337 modified_config.turn_customizer,
3338 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003339 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003340 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3341 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003342
deadbeefd1a38b52016-12-10 13:15:33 -08003343 // As described in JSEP, calling setConfiguration with new ICE servers or
3344 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3345 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003346 if (modified_config.servers != configuration_.servers ||
3347 modified_config.type != configuration_.type ||
3348 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003349 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003350 }
skvladd1f5fda2017-02-03 16:54:05 -08003351
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003352 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003353 transport_controller_->SetMediaTransportSettings(
3354 modified_config.use_media_transport,
3355 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003356
Zhi Huangb57e1692018-06-12 11:41:11 -07003357 if (configuration_.active_reset_srtp_params !=
3358 modified_config.active_reset_srtp_params) {
3359 transport_controller_->SetActiveResetSrtpParams(
3360 modified_config.active_reset_srtp_params);
3361 }
3362
deadbeef293e9262017-01-11 12:28:30 -08003363 configuration_ = modified_config;
3364 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003365}
3366
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003367bool PeerConnection::AddIceCandidate(
3368 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003369 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003370 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003371 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003372 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003373 return false;
3374 }
Steve Antond25da372017-11-06 14:50:29 -08003375
3376 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003377 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003378 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003379 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003380 return false;
3381 }
3382
3383 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003384 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003385 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003386 return false;
3387 }
3388
3389 bool valid = false;
3390 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3391 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003392 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003393 return false;
3394 }
3395
3396 // Add this candidate to the remote session description.
3397 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003398 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003399 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003400 return false;
3401 }
3402
3403 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003404 bool result = UseCandidate(ice_candidate);
3405 if (result) {
3406 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3407 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3408 } else {
3409 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3410 }
3411 return result;
Steve Antond25da372017-11-06 14:50:29 -08003412 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003413 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003414 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003415 return true;
3416 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003417}
3418
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003419bool PeerConnection::RemoveIceCandidates(
3420 const std::vector<cricket::Candidate>& candidates) {
3421 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003422 if (IsClosed()) {
3423 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3424 return false;
3425 }
3426
Steve Antond25da372017-11-06 14:50:29 -08003427 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003428 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3429 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003430 return false;
3431 }
3432
3433 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003434 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003435 return false;
3436 }
3437
3438 size_t number_removed =
3439 mutable_remote_description()->RemoveCandidates(candidates);
3440 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003441 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003442 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003443 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003444 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003445 }
3446
3447 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003448 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3449 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003450 RTC_LOG(LS_ERROR)
3451 << "RemoveIceCandidates: Error when removing remote candidates: "
3452 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003453 }
3454 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003455}
3456
Niels Möller0c4f7be2018-05-07 14:01:37 +02003457RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003458 if (!worker_thread()->IsCurrent()) {
3459 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003460 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003461 }
3462
Niels Möller0c4f7be2018-05-07 14:01:37 +02003463 const bool has_min = bitrate.min_bitrate_bps.has_value();
3464 const bool has_start = bitrate.start_bitrate_bps.has_value();
3465 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003466 if (has_min && *bitrate.min_bitrate_bps < 0) {
3467 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3468 "min_bitrate_bps <= 0");
3469 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003470 if (has_start) {
3471 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003472 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003473 "start_bitrate_bps < min_bitrate_bps");
3474 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003475 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3476 "curent_bitrate_bps < 0");
3477 }
3478 }
3479 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003480 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003481 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003482 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003483 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3484 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3485 "max_bitrate_bps < min_bitrate_bps");
3486 } else if (*bitrate.max_bitrate_bps < 0) {
3487 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3488 "max_bitrate_bps < 0");
3489 }
3490 }
3491
zstein4b979802017-06-02 14:37:37 -07003492 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003493 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003494
3495 return RTCError::OK();
3496}
3497
Alex Narest78609d52017-10-20 10:37:47 +02003498void PeerConnection::SetBitrateAllocationStrategy(
3499 std::unique_ptr<rtc::BitrateAllocationStrategy>
3500 bitrate_allocation_strategy) {
3501 rtc::Thread* worker_thread = factory_->worker_thread();
3502 if (!worker_thread->IsCurrent()) {
3503 rtc::BitrateAllocationStrategy* strategy_raw =
3504 bitrate_allocation_strategy.release();
3505 auto functor = [this, strategy_raw]() {
3506 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003507 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003508 };
3509 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3510 return;
3511 }
3512 RTC_DCHECK(call_.get());
3513 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3514}
3515
henrika5f6bf242017-11-01 11:06:56 +01003516void PeerConnection::SetAudioPlayout(bool playout) {
3517 if (!worker_thread()->IsCurrent()) {
3518 worker_thread()->Invoke<void>(
3519 RTC_FROM_HERE,
3520 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3521 return;
3522 }
3523 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003524 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003525 audio_state->SetPlayout(playout);
3526}
3527
3528void PeerConnection::SetAudioRecording(bool recording) {
3529 if (!worker_thread()->IsCurrent()) {
3530 worker_thread()->Invoke<void>(
3531 RTC_FROM_HERE,
3532 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3533 return;
3534 }
3535 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003536 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003537 audio_state->SetRecording(recording);
3538}
3539
Steve Anton8c0f7a72017-10-03 10:03:10 -07003540std::unique_ptr<rtc::SSLCertificate>
3541PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003542 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3543 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003544 return nullptr;
3545 }
Steve Antonf25303e2018-10-16 15:23:31 -07003546 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003547}
3548
Zhi Huang70b820f2018-01-27 14:16:15 -08003549std::unique_ptr<rtc::SSLCertChain>
3550PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003551 auto audio_transceiver = GetFirstAudioTransceiver();
3552 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003553 return nullptr;
3554 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003555 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003556 audio_transceiver->internal()->channel()->transport_name());
3557}
3558
3559rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3560PeerConnection::GetFirstAudioTransceiver() const {
3561 for (auto transceiver : transceivers_) {
3562 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3563 return transceiver;
3564 }
3565 }
3566 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003567}
3568
ivoc14d5dbe2016-07-04 07:06:55 -07003569bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3570 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003571 // TODO(eladalon): It would be better to not allow negative values into PC.
3572 const size_t max_size = (max_size_bytes < 0)
3573 ? RtcEventLog::kUnlimitedOutput
3574 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003575 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3576 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3577 output_period_ms = 5000;
3578 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003579 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003580 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003581 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003582}
3583
Bjorn Tereliusde939432017-11-20 17:38:14 +01003584bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3585 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003586 // TODO(eladalon): In C++14, this can be done with a lambda.
3587 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003588 bool operator()() {
3589 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3590 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003591 PeerConnection* const pc;
3592 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003593 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003594 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003595 return worker_thread()->Invoke<bool>(
3596 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003597}
3598
3599void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003600 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003601 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3602}
3603
Harald Alvestrandad88c882018-11-28 16:47:46 +01003604rtc::scoped_refptr<DtlsTransportInterface>
3605PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3606 return transport_controller_->LookupDtlsTransportByMid(mid);
3607}
3608
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003609rtc::scoped_refptr<DtlsTransport>
3610PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3611 return transport_controller_->LookupDtlsTransportByMid(mid);
3612}
3613
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003614const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003615 return pending_local_description_ ? pending_local_description_.get()
3616 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003617}
3618
3619const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003620 return pending_remote_description_ ? pending_remote_description_.get()
3621 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003622}
3623
deadbeeffe4a8a42016-12-20 17:56:17 -08003624const SessionDescriptionInterface* PeerConnection::current_local_description()
3625 const {
Steve Anton75737c02017-11-06 10:37:17 -08003626 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003627}
3628
3629const SessionDescriptionInterface* PeerConnection::current_remote_description()
3630 const {
Steve Anton75737c02017-11-06 10:37:17 -08003631 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003632}
3633
3634const SessionDescriptionInterface* PeerConnection::pending_local_description()
3635 const {
Steve Anton75737c02017-11-06 10:37:17 -08003636 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003637}
3638
3639const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3640 const {
Steve Anton75737c02017-11-06 10:37:17 -08003641 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003642}
3643
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003644void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003645 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003646 // Update stats here so that we have the most recent stats for tracks and
3647 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003648 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003649
Steve Anton75737c02017-11-06 10:37:17 -08003650 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003651 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003652
Mirko Bonadei739baf02019-01-27 17:29:42 +01003653 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003654 transceiver->Stop();
3655 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003656
3657 // Ensure that all asynchronous stats requests are completed before destroying
3658 // the transport controller below.
3659 if (stats_collector_) {
3660 stats_collector_->WaitForPendingRequest();
3661 }
3662
3663 // Don't destroy BaseChannels until after stats has been cleaned up so that
3664 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003665 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003666
Qingsi Wang93a84392018-01-30 17:13:09 -08003667 // The event log is used in the transport controller, which must be outlived
3668 // by the former. CreateOffer by the peer connection is implemented
3669 // asynchronously and if the peer connection is closed without resetting the
3670 // WebRTC session description factory, the session description factory would
3671 // call the transport controller.
3672 webrtc_session_desc_factory_.reset();
3673 transport_controller_.reset();
3674
deadbeef42a42632017-03-10 15:18:00 -08003675 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003676 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3677 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003678
Steve Anton978b8762017-09-29 12:15:02 -07003679 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003680 call_.reset();
3681 // The event log must outlive call (and any other object that uses it).
3682 event_log_.reset();
3683 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003684 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003685 // The .h file says that observer can be discarded after close() returns.
3686 // Make sure this is true.
3687 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003688}
3689
Steve Antonad182762018-09-05 20:22:40 +00003690void PeerConnection::OnMessage(rtc::Message* msg) {
3691 switch (msg->message_id) {
3692 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3693 SetSessionDescriptionMsg* param =
3694 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3695 param->observer->OnSuccess();
3696 delete param;
3697 break;
3698 }
3699 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3700 SetSessionDescriptionMsg* param =
3701 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3702 param->observer->OnFailure(std::move(param->error));
3703 delete param;
3704 break;
3705 }
3706 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3707 CreateSessionDescriptionMsg* param =
3708 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3709 param->observer->OnFailure(std::move(param->error));
3710 delete param;
3711 break;
3712 }
3713 case MSG_GETSTATS: {
3714 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3715 StatsReports reports;
3716 stats_->GetStats(param->track, &reports);
3717 param->observer->OnComplete(reports);
3718 delete param;
3719 break;
3720 }
3721 case MSG_FREE_DATACHANNELS: {
3722 sctp_data_channels_to_free_.clear();
3723 break;
3724 }
3725 case MSG_REPORT_USAGE_PATTERN: {
3726 ReportUsagePattern();
3727 break;
3728 }
3729 default:
3730 RTC_NOTREACHED() << "Not implemented";
3731 break;
3732 }
3733}
3734
Steve Antonafb0bb72018-02-20 11:35:37 -08003735cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3736 RTC_DCHECK(!IsUnifiedPlan());
3737 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3738 GetAudioTransceiver()->internal()->channel());
3739 if (voice_channel) {
3740 return voice_channel->media_channel();
3741 } else {
3742 return nullptr;
3743 }
3744}
3745
3746cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3747 RTC_DCHECK(!IsUnifiedPlan());
3748 auto* video_channel = static_cast<cricket::VideoChannel*>(
3749 GetVideoTransceiver()->internal()->channel());
3750 if (video_channel) {
3751 return video_channel->media_channel();
3752 } else {
3753 return nullptr;
3754 }
3755}
3756
Steve Anton4171afb2017-11-20 10:20:22 -08003757void PeerConnection::CreateAudioReceiver(
3758 MediaStreamInterface* stream,
3759 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003760 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3761 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003762 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3763 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003764 auto* audio_receiver = new AudioRtpReceiver(
3765 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003766 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003767 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3768 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3769 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003770 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003771 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003772 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003773}
3774
Steve Anton4171afb2017-11-20 10:20:22 -08003775void PeerConnection::CreateVideoReceiver(
3776 MediaStreamInterface* stream,
3777 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003778 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3779 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003780 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3781 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003782 auto* video_receiver = new VideoRtpReceiver(
3783 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003784 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003785 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3786 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3787 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003788 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Mirko Bonadei05cf6be2019-01-31 21:38:12 +01003789 Observer()->OnAddTrack(receiver, streams);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003790 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003791}
3792
deadbeef70ab1a12015-09-28 16:53:55 -07003793// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3794// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003795rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003796 const RtpSenderInfo& remote_sender_info) {
3797 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3798 if (!receiver) {
3799 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3800 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003801 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003802 }
Steve Anton4171afb2017-11-20 10:20:22 -08003803 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3804 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3805 } else {
3806 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3807 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003808 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003809}
3810
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003811void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3812 MediaStreamInterface* stream) {
3813 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003814 RTC_DCHECK(track);
3815 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003816 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003817 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003818 // We already have a sender for this track, so just change the stream_id
3819 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003820 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003821 return;
3822 }
3823
3824 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003825 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003826 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003827 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003828 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003829 // If the sender has already been configured in SDP, we call SetSsrc,
3830 // which will connect the sender to the underlying transport. This can
3831 // occur if a local session description that contains the ID of the sender
3832 // is set before AddStream is called. It can also occur if the local
3833 // session description is not changed and RemoveStream is called, and
3834 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003835 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003836 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003837 if (sender_info) {
3838 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003839 }
3840}
3841
3842// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3843// indefinitely, when we have unified plan SDP.
3844void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3845 MediaStreamInterface* stream) {
3846 RTC_DCHECK(!IsClosed());
3847 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003848 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003849 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3850 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003851 return;
3852 }
Steve Anton4171afb2017-11-20 10:20:22 -08003853 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003854}
3855
3856void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3857 MediaStreamInterface* stream) {
3858 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003859 RTC_DCHECK(track);
3860 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003861 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003862 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003863 // We already have a sender for this track, so just change the stream_id
3864 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003865 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003866 return;
3867 }
3868
3869 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003870 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003871 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003872 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003873 GetVideoTransceiver()->internal()->AddSender(new_sender);
3874 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003875 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003876 if (sender_info) {
3877 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003878 }
3879}
3880
3881void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3882 MediaStreamInterface* stream) {
3883 RTC_DCHECK(!IsClosed());
3884 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003885 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003886 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3887 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003888 return;
3889 }
Steve Anton4171afb2017-11-20 10:20:22 -08003890 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003891}
3892
Steve Antonba818672017-11-06 10:21:57 -08003893void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003894 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003895 if (ice_connection_state_ == new_state) {
3896 return;
3897 }
3898
deadbeefcbecd352015-09-23 11:50:27 -07003899 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003900 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003901 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003902 return;
3903 }
Steve Antonba818672017-11-06 10:21:57 -08003904
Mirko Bonadei675513b2017-11-09 11:09:25 +01003905 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3906 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003907 RTC_DCHECK(ice_connection_state_ !=
3908 PeerConnectionInterface::kIceConnectionClosed);
3909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003910 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003911 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003912}
3913
Alex Loiko9289eda2018-11-23 16:18:59 +00003914void PeerConnection::SetStandardizedIceConnectionState(
3915 PeerConnectionInterface::IceConnectionState new_state) {
3916 RTC_DCHECK(signaling_thread()->IsCurrent());
3917 if (standardized_ice_connection_state_ == new_state)
3918 return;
3919 if (IsClosed())
3920 return;
3921 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003922 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003923}
3924
Jonas Olsson635474e2018-10-18 15:58:17 +02003925void PeerConnection::SetConnectionState(
3926 PeerConnectionInterface::PeerConnectionState new_state) {
3927 RTC_DCHECK(signaling_thread()->IsCurrent());
3928 if (connection_state_ == new_state)
3929 return;
3930 if (IsClosed())
3931 return;
3932 connection_state_ = new_state;
3933 Observer()->OnConnectionChange(new_state);
3934}
3935
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003936void PeerConnection::OnIceGatheringChange(
3937 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003938 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003939 if (IsClosed()) {
3940 return;
3941 }
3942 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003943 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003944}
3945
jbauch81bf7b02017-03-25 08:31:12 -07003946void PeerConnection::OnIceCandidate(
3947 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003948 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003949 if (IsClosed()) {
3950 return;
3951 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003952 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003953 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3954 candidate->candidate().address().IsPrivateIP()) {
3955 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3956 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003957 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003958}
3959
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003960void PeerConnection::OnIceCandidatesRemoved(
3961 const std::vector<cricket::Candidate>& candidates) {
3962 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003963 if (IsClosed()) {
3964 return;
3965 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003966 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003967}
3968
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003969void PeerConnection::ChangeSignalingState(
3970 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003971 RTC_DCHECK(signaling_thread()->IsCurrent());
3972 if (signaling_state_ == signaling_state) {
3973 return;
3974 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003975 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3976 << GetSignalingStateString(signaling_state_)
3977 << " New state: "
3978 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003979 signaling_state_ = signaling_state;
3980 if (signaling_state == kClosed) {
3981 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003982 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003983 standardized_ice_connection_state_ =
3984 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003985 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3986 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003987 if (ice_gathering_state_ != kIceGatheringComplete) {
3988 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003989 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003990 }
3991 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003992 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003993}
3994
deadbeefeb459812015-12-15 19:24:43 -08003995void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3996 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003997 if (IsClosed()) {
3998 return;
3999 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004000 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004001 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004002}
4003
deadbeefeb459812015-12-15 19:24:43 -08004004void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
4005 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004006 if (IsClosed()) {
4007 return;
4008 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004009 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004010 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004011}
4012
4013void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
4014 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004015 if (IsClosed()) {
4016 return;
4017 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004018 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004019 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004020}
4021
4022void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
4023 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07004024 if (IsClosed()) {
4025 return;
4026 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07004027 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004028 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08004029}
4030
Henrik Boström31638672017-11-23 17:48:32 +01004031void PeerConnection::PostSetSessionDescriptionSuccess(
4032 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00004033 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4034 signaling_thread()->Post(RTC_FROM_HERE, this,
4035 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004036}
4037
deadbeefab9b2d12015-10-14 11:33:11 -07004038void PeerConnection::PostSetSessionDescriptionFailure(
4039 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004040 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004041 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004042 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4043 msg->error = std::move(error);
4044 signaling_thread()->Post(RTC_FROM_HERE, this,
4045 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004046}
4047
4048void PeerConnection::PostCreateSessionDescriptionFailure(
4049 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004050 RTCError error) {
4051 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004052 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4053 msg->error = std::move(error);
4054 signaling_thread()->Post(RTC_FROM_HERE, this,
4055 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004056}
4057
zhihuang1c378ed2017-08-17 14:10:50 -07004058void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004059 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004060 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004061 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004062
Steve Antondcc3c022017-12-22 16:02:54 -08004063 if (IsUnifiedPlan()) {
4064 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4065 } else {
4066 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4067 }
4068
Steve Antonfa2260d2017-12-28 16:38:23 -08004069 // Intentionally unset the data channel type for RTP data channel with the
4070 // second condition. Otherwise the RTP data channels would be successfully
4071 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4072 // when building with chromium. We want to leave RTP data channels broken, so
4073 // people won't try to use them.
4074 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4075 session_options->data_channel_type = data_channel_type();
4076 }
4077
Steve Antondcc3c022017-12-22 16:02:54 -08004078 // Apply ICE restart flag and renomination flag.
4079 for (auto& options : session_options->media_description_options) {
4080 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4081 options.transport_options.enable_ice_renomination =
4082 configuration_.enable_ice_renomination;
4083 }
4084
4085 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004086 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004087 session_options->pooled_ice_credentials =
4088 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4089 RTC_FROM_HERE,
4090 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4091 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004092 session_options->offer_extmap_allow_mixed =
4093 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004094}
4095
4096void PeerConnection::GetOptionsForPlanBOffer(
4097 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4098 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004099 // Figure out transceiver directional preferences.
4100 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4101 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4102
4103 // By default, generate sendrecv/recvonly m= sections.
4104 bool recv_audio = true;
4105 bool recv_video = true;
4106
4107 // By default, only offer a new m= section if we have media to send with it.
4108 bool offer_new_audio_description = send_audio;
4109 bool offer_new_video_description = send_video;
4110 bool offer_new_data_description = HasDataChannels();
4111
4112 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004113 if (offer_answer_options.offer_to_receive_audio !=
4114 RTCOfferAnswerOptions::kUndefined) {
4115 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004116 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004117 offer_new_audio_description ||
4118 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004119 }
Steve Antondcc3c022017-12-22 16:02:54 -08004120 if (offer_answer_options.offer_to_receive_video !=
4121 RTCOfferAnswerOptions::kUndefined) {
4122 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004123 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004124 offer_new_video_description ||
4125 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004126 }
4127
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004128 absl::optional<size_t> audio_index;
4129 absl::optional<size_t> video_index;
4130 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004131 // If a current description exists, generate m= sections in the same order,
4132 // using the first audio/video/data section that appears and rejecting
4133 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004134 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004135 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004136 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004137 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4138 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4139 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004140 }
4141
zhihuang1c378ed2017-08-17 14:10:50 -07004142 // Add audio/video/data m= sections to the end if needed.
4143 if (!audio_index && offer_new_audio_description) {
4144 session_options->media_description_options.push_back(
4145 cricket::MediaDescriptionOptions(
4146 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004147 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4148 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004149 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004150 }
zhihuang1c378ed2017-08-17 14:10:50 -07004151 if (!video_index && offer_new_video_description) {
4152 session_options->media_description_options.push_back(
4153 cricket::MediaDescriptionOptions(
4154 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004155 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4156 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004157 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004158 }
zhihuang1c378ed2017-08-17 14:10:50 -07004159 if (!data_index && offer_new_data_description) {
4160 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004161 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004162 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004163 }
4164
4165 cricket::MediaDescriptionOptions* audio_media_description_options =
4166 !audio_index ? nullptr
4167 : &session_options->media_description_options[*audio_index];
4168 cricket::MediaDescriptionOptions* video_media_description_options =
4169 !video_index ? nullptr
4170 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004171
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004172 AddPlanBRtpSenderOptions(GetSendersInternal(),
4173 audio_media_description_options,
4174 video_media_description_options,
4175 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004176}
4177
Steve Antondcc3c022017-12-22 16:02:54 -08004178static cricket::MediaDescriptionOptions
4179GetMediaDescriptionOptionsForTransceiver(
4180 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4181 transceiver,
4182 const std::string& mid) {
4183 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004184 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004185 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004186 // This behavior is specified in JSEP. The gist is that:
4187 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4188 // sendrecv.
4189 // 2. If the MSID is included, then it must be included in any subsequent
4190 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004191 if (transceiver->stopped() ||
4192 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4193 !transceiver->internal()->has_ever_been_used_to_send())) {
4194 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004195 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004196
4197 cricket::SenderOptions sender_options;
4198 sender_options.track_id = transceiver->sender()->id();
4199 sender_options.stream_ids = transceiver->sender()->stream_ids();
4200
4201 // The following sets up RIDs and Simulcast.
4202 // RIDs are included if Simulcast is requested or if any RID was specified.
4203 RtpParameters send_parameters = transceiver->sender()->GetParameters();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004204 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4205 send_parameters.encodings.end(),
4206 [](const RtpEncodingParameters& encoding) {
4207 return !encoding.rid.empty();
4208 });
4209
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004210 std::vector<RidDescription> send_rids;
4211 SimulcastLayerList send_layers;
4212 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4213 if (encoding.rid.empty()) {
4214 continue;
4215 }
4216 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4217 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4218 }
4219
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004220 if (has_rids) {
4221 sender_options.rids = send_rids;
4222 }
4223
4224 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004225 // When RIDs are configured, we must set num_sim_layers to 0 to.
4226 // Otherwise, num_sim_layers must be 1 because either there is no
4227 // simulcast, or simulcast is acheived by munging the SDP.
4228 sender_options.num_sim_layers = has_rids ? 0 : 1;
4229 media_description_options.sender_options.push_back(sender_options);
4230
Steve Antondcc3c022017-12-22 16:02:54 -08004231 return media_description_options;
4232}
4233
Steve Anton5c72e712018-12-10 14:25:30 -08004234// Returns the ContentInfo at mline index |i|, or null if none exists.
4235static const ContentInfo* GetContentByIndex(
4236 const SessionDescriptionInterface* sdesc,
4237 size_t i) {
4238 if (!sdesc) {
4239 return nullptr;
4240 }
4241 const ContentInfos& contents = sdesc->description()->contents();
4242 return (i < contents.size() ? &contents[i] : nullptr);
4243}
4244
Steve Antondcc3c022017-12-22 16:02:54 -08004245void PeerConnection::GetOptionsForUnifiedPlanOffer(
4246 const RTCOfferAnswerOptions& offer_answer_options,
4247 cricket::MediaSessionOptions* session_options) {
4248 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4249 // Offers) and 5.2.2 (Subsequent Offers).
4250 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4251 const ContentInfos& local_contents =
4252 (local_description() ? local_description()->description()->contents()
4253 : ContentInfos());
4254 const ContentInfos& remote_contents =
4255 (remote_description() ? remote_description()->description()->contents()
4256 : ContentInfos());
4257 // The mline indices that can be recycled. New transceivers should reuse these
4258 // slots first.
4259 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004260 // First, go through each media section that exists in either the local or
4261 // remote description and generate a media section in this offer for the
4262 // associated transceiver. If a media section can be recycled, generate a
4263 // default, rejected media section here that can be later overwritten.
4264 for (size_t i = 0;
4265 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4266 // Either |local_content| or |remote_content| is non-null.
4267 const ContentInfo* local_content =
4268 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004269 const ContentInfo* current_local_content =
4270 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004271 const ContentInfo* remote_content =
4272 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004273 const ContentInfo* current_remote_content =
4274 GetContentByIndex(current_remote_description(), i);
4275 bool had_been_rejected =
4276 (current_local_content && current_local_content->rejected) ||
4277 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004278 const std::string& mid =
4279 (local_content ? local_content->name : remote_content->name);
4280 cricket::MediaType media_type =
4281 (local_content ? local_content->media_description()->type()
4282 : remote_content->media_description()->type());
4283 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4284 media_type == cricket::MEDIA_TYPE_VIDEO) {
4285 auto transceiver = GetAssociatedTransceiver(mid);
4286 RTC_CHECK(transceiver);
4287 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004288 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004289 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004290 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004291 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4292 RtpTransceiverDirection::kInactive,
4293 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004294 recycleable_mline_indices.push(i);
4295 } else {
4296 session_options->media_description_options.push_back(
4297 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4298 // CreateOffer shouldn't really cause any state changes in
4299 // PeerConnection, but we need a way to match new transceivers to new
4300 // media sections in SetLocalDescription and JSEP specifies this is done
4301 // by recording the index of the media section generated for the
4302 // transceiver in the offer.
4303 transceiver->internal()->set_mline_index(i);
4304 }
4305 } else {
4306 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004307 RTC_CHECK(GetDataMid());
4308 if (had_been_rejected || mid != *GetDataMid()) {
4309 session_options->media_description_options.push_back(
4310 GetMediaDescriptionOptionsForRejectedData(mid));
4311 } else {
4312 session_options->media_description_options.push_back(
4313 GetMediaDescriptionOptionsForActiveData(mid));
4314 }
Steve Antondcc3c022017-12-22 16:02:54 -08004315 }
4316 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004317
Steve Antondcc3c022017-12-22 16:02:54 -08004318 // Next, look for transceivers that are newly added (that is, are not stopped
4319 // and not associated). Reuse media sections marked as recyclable first,
4320 // otherwise append to the end of the offer. New media sections should be
4321 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004322 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004323 if (transceiver->mid() || transceiver->stopped()) {
4324 continue;
4325 }
4326 size_t mline_index;
4327 if (!recycleable_mline_indices.empty()) {
4328 mline_index = recycleable_mline_indices.front();
4329 recycleable_mline_indices.pop();
4330 session_options->media_description_options[mline_index] =
4331 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004332 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004333 } else {
4334 mline_index = session_options->media_description_options.size();
4335 session_options->media_description_options.push_back(
4336 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004337 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004338 }
4339 // See comment above for why CreateOffer changes the transceiver's state.
4340 transceiver->internal()->set_mline_index(mline_index);
4341 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004342 // Lastly, add a m-section if we have local data channels and an m section
4343 // does not already exist.
4344 if (!GetDataMid() && HasDataChannels()) {
4345 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004346 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004347 }
Steve Antondcc3c022017-12-22 16:02:54 -08004348}
4349
4350void PeerConnection::GetOptionsForAnswer(
4351 const RTCOfferAnswerOptions& offer_answer_options,
4352 cricket::MediaSessionOptions* session_options) {
4353 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4354
4355 if (IsUnifiedPlan()) {
4356 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4357 } else {
4358 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4359 }
4360
Steve Antonfa2260d2017-12-28 16:38:23 -08004361 // Intentionally unset the data channel type for RTP data channel. Otherwise
4362 // the RTP data channels would be successfully negotiated by default and the
4363 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4364 // We want to leave RTP data channels broken, so people won't try to use them.
4365 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4366 session_options->data_channel_type = data_channel_type();
4367 }
4368
Steve Antondcc3c022017-12-22 16:02:54 -08004369 // Apply ICE renomination flag.
4370 for (auto& options : session_options->media_description_options) {
4371 options.transport_options.enable_ice_renomination =
4372 configuration_.enable_ice_renomination;
4373 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004374
4375 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004376 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004377 session_options->pooled_ice_credentials =
4378 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4379 RTC_FROM_HERE,
4380 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4381 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004382}
4383
Steve Antondcc3c022017-12-22 16:02:54 -08004384void PeerConnection::GetOptionsForPlanBAnswer(
4385 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004386 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004387 // Figure out transceiver directional preferences.
4388 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4389 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4390
4391 // By default, generate sendrecv/recvonly m= sections. The direction is also
4392 // restricted by the direction in the offer.
4393 bool recv_audio = true;
4394 bool recv_video = true;
4395
4396 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004397 if (offer_answer_options.offer_to_receive_audio !=
4398 RTCOfferAnswerOptions::kUndefined) {
4399 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004400 }
Steve Antondcc3c022017-12-22 16:02:54 -08004401 if (offer_answer_options.offer_to_receive_video !=
4402 RTCOfferAnswerOptions::kUndefined) {
4403 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004404 }
4405
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004406 absl::optional<size_t> audio_index;
4407 absl::optional<size_t> video_index;
4408 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004409
4410 // Generate m= sections that match those in the offer.
4411 // Note that mediasession.cc will handle intersection our preferred
4412 // direction with the offered direction.
4413 GenerateMediaDescriptionOptions(
4414 remote_description(),
4415 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4416 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4417 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004418
4419 cricket::MediaDescriptionOptions* audio_media_description_options =
4420 !audio_index ? nullptr
4421 : &session_options->media_description_options[*audio_index];
4422 cricket::MediaDescriptionOptions* video_media_description_options =
4423 !video_index ? nullptr
4424 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004425
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004426 AddPlanBRtpSenderOptions(GetSendersInternal(),
4427 audio_media_description_options,
4428 video_media_description_options,
4429 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004430}
zhihuangaf388472016-11-02 16:49:48 -07004431
Steve Antondcc3c022017-12-22 16:02:54 -08004432void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4433 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4434 cricket::MediaSessionOptions* session_options) {
4435 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4436 // Answers) and 5.3.2 (Subsequent Answers).
4437 RTC_DCHECK(remote_description());
4438 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4439 for (const ContentInfo& content :
4440 remote_description()->description()->contents()) {
4441 cricket::MediaType media_type = content.media_description()->type();
4442 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4443 media_type == cricket::MEDIA_TYPE_VIDEO) {
4444 auto transceiver = GetAssociatedTransceiver(content.name);
4445 RTC_CHECK(transceiver);
4446 session_options->media_description_options.push_back(
4447 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4448 } else {
4449 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004450 // Reject all data sections if data channels are disabled.
4451 // Reject a data section if it has already been rejected.
4452 // Reject all data sections except for the first one.
4453 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4454 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004455 session_options->media_description_options.push_back(
4456 GetMediaDescriptionOptionsForRejectedData(content.name));
4457 } else {
4458 session_options->media_description_options.push_back(
4459 GetMediaDescriptionOptionsForActiveData(content.name));
4460 }
Steve Antondcc3c022017-12-22 16:02:54 -08004461 }
4462 }
htaa2a49d92016-03-04 02:51:39 -08004463}
4464
zhihuang1c378ed2017-08-17 14:10:50 -07004465void PeerConnection::GenerateMediaDescriptionOptions(
4466 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004467 RtpTransceiverDirection audio_direction,
4468 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004469 absl::optional<size_t>* audio_index,
4470 absl::optional<size_t>* video_index,
4471 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004472 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004473 for (const cricket::ContentInfo& content :
4474 session_desc->description()->contents()) {
4475 if (IsAudioContent(&content)) {
4476 // If we already have an audio m= section, reject this extra one.
4477 if (*audio_index) {
4478 session_options->media_description_options.push_back(
4479 cricket::MediaDescriptionOptions(
4480 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004481 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004482 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004483 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004484 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004485 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4486 content.name, audio_direction,
4487 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004488 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004489 }
4490 } else if (IsVideoContent(&content)) {
4491 // If we already have an video m= section, reject this extra one.
4492 if (*video_index) {
4493 session_options->media_description_options.push_back(
4494 cricket::MediaDescriptionOptions(
4495 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004496 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004497 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004498 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004499 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004500 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4501 content.name, video_direction,
4502 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004503 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004504 }
4505 } else {
4506 RTC_DCHECK(IsDataContent(&content));
4507 // If we already have an data m= section, reject this extra one.
4508 if (*data_index) {
4509 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004510 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004511 } else {
4512 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004513 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004514 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004515 }
4516 }
htaa2a49d92016-03-04 02:51:39 -08004517 }
deadbeefab9b2d12015-10-14 11:33:11 -07004518}
4519
Steve Antonfa2260d2017-12-28 16:38:23 -08004520cricket::MediaDescriptionOptions
4521PeerConnection::GetMediaDescriptionOptionsForActiveData(
4522 const std::string& mid) const {
4523 // Direction for data sections is meaningless, but legacy endpoints might
4524 // expect sendrecv.
4525 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4526 RtpTransceiverDirection::kSendRecv,
4527 /*stopped=*/false);
4528 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4529 return options;
4530}
4531
4532cricket::MediaDescriptionOptions
4533PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4534 const std::string& mid) const {
4535 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4536 RtpTransceiverDirection::kInactive,
4537 /*stopped=*/true);
4538 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4539 return options;
4540}
4541
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004542absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004543 switch (data_channel_type_) {
4544 case cricket::DCT_RTP:
4545 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004546 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004547 }
4548 return rtp_data_channel_->content_name();
4549 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004550 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004551 case cricket::DCT_MEDIA_TRANSPORT:
4552 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004553 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004554 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004555 }
4556}
4557
Steve Anton4171afb2017-11-20 10:20:22 -08004558void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4559 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4560 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004561 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004562}
4563
Steve Anton4171afb2017-11-20 10:20:22 -08004564void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004565 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004566 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004567 cricket::MediaType media_type,
4568 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004569 RTC_DCHECK(!IsUnifiedPlan());
4570
Steve Anton4171afb2017-11-20 10:20:22 -08004571 std::vector<RtpSenderInfo>* current_senders =
4572 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004573
Steve Anton4171afb2017-11-20 10:20:22 -08004574 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004575 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004576 for (auto sender_it = current_senders->begin();
4577 sender_it != current_senders->end();
4578 /* incremented manually */) {
4579 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004580 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004581 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004582 std::string params_stream_id;
4583 if (params) {
4584 params_stream_id =
4585 (!params->first_stream_id().empty() ? params->first_stream_id()
4586 : kDefaultStreamId);
4587 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004588 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004589 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004590 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004591 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004592 sender_exists) {
4593 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004594 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004595 OnRemoteSenderRemoved(info, media_type);
4596 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004597 }
4598 }
4599
Steve Anton4171afb2017-11-20 10:20:22 -08004600 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004601 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004602 if (!params.has_ssrcs()) {
4603 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4604 // sender, this means it is coming from a Unified Plan endpoint,so we just
4605 // create a default.
4606 default_sender_needed = true;
4607 break;
4608 }
4609
Seth Hampson845e8782018-03-02 11:34:10 -08004610 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004611 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004612 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4613 // not supported in Plan B, we just take the first here and create the
4614 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004615 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004616 (!params.first_stream_id().empty() ? params.first_stream_id()
4617 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004618 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004619 uint32_t ssrc = params.first_ssrc();
4620
4621 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004622 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004623 if (!stream) {
4624 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004625 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004626 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004627 remote_streams_->AddStream(stream);
4628 new_streams->AddStream(stream);
4629 }
4630
Steve Anton4171afb2017-11-20 10:20:22 -08004631 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004632 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004633 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004634 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004635 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004636 }
4637 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004638
Steve Anton4171afb2017-11-20 10:20:22 -08004639 // Add default sender if necessary.
4640 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004641 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004642 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004643 if (!default_stream) {
4644 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004645 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004646 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004647 remote_streams_->AddStream(default_stream);
4648 new_streams->AddStream(default_stream);
4649 }
Steve Anton4171afb2017-11-20 10:20:22 -08004650 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4651 ? kDefaultAudioSenderId
4652 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004653 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004654 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004655 if (!default_sender_info) {
4656 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004657 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004658 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004659 }
4660 }
deadbeefab9b2d12015-10-14 11:33:11 -07004661}
4662
Steve Anton4171afb2017-11-20 10:20:22 -08004663void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4664 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004665 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4666 << " receiver for track_id=" << sender_info.sender_id
4667 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004668
Steve Anton3d954a62018-04-02 11:27:23 -07004669 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004670 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004671 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004672 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004673 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004674 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004675 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004676 }
4677}
4678
Steve Anton4171afb2017-11-20 10:20:22 -08004679void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4680 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004681 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4682 << " receiver for track_id=" << sender_info.sender_id
4683 << " and stream_id=" << sender_info.stream_id;
4684
Seth Hampson845e8782018-03-02 11:34:10 -08004685 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004686
Henrik Boström933d8b02017-10-10 10:05:16 -07004687 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004688 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004689 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4690 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004691 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004692 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004693 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004694 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004695 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004696 }
4697 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004698 // Stopping or destroying a VideoRtpReceiver will end the
4699 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004700 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004701 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004702 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004703 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004704 // There's no guarantee the track is still available, e.g. the track may
4705 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004706 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004707 }
4708 } else {
nisseede5da42017-01-12 05:15:36 -08004709 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004710 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004711 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004712 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004713 }
deadbeefab9b2d12015-10-14 11:33:11 -07004714}
4715
4716void PeerConnection::UpdateEndedRemoteMediaStreams() {
4717 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4718 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4719 MediaStreamInterface* stream = remote_streams_->at(i);
4720 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4721 streams_to_remove.push_back(stream);
4722 }
4723 }
4724
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004725 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004726 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004727 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004728 }
4729}
4730
Steve Anton4171afb2017-11-20 10:20:22 -08004731void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004732 const std::vector<cricket::StreamParams>& streams,
4733 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004734 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004735
Seth Hampson845e8782018-03-02 11:34:10 -08004736 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004737 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004738 for (auto sender_it = current_senders->begin();
4739 sender_it != current_senders->end();
4740 /* incremented manually */) {
4741 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004742 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004743 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4744 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004745 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004746 OnLocalSenderRemoved(info, media_type);
4747 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004748 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004749 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004750 }
4751 }
4752
Steve Anton4171afb2017-11-20 10:20:22 -08004753 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004754 for (const cricket::StreamParams& params : streams) {
4755 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004756 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004757 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004758 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004759 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004760 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004761 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004762 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004763 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004764 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004765 }
4766 }
4767}
4768
Steve Anton4171afb2017-11-20 10:20:22 -08004769void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4770 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004771 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004772 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004773 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004774 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4775 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004776 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004777 return;
4778 }
4779
deadbeeffac06552015-11-25 11:26:01 -08004780 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004781 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004782 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004783 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004784 }
deadbeeffac06552015-11-25 11:26:01 -08004785
Seth Hampson5b4f0752018-04-02 16:31:36 -07004786 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004787 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004788}
4789
Steve Anton4171afb2017-11-20 10:20:22 -08004790void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4791 cricket::MediaType media_type) {
4792 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004793 if (!sender) {
4794 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004795 // SessionDescriptions has been renegotiated.
4796 return;
4797 }
deadbeeffac06552015-11-25 11:26:01 -08004798
4799 // A sender has been removed from the SessionDescription but it's still
4800 // associated with the PeerConnection. This only occurs if the SDP doesn't
4801 // match with the calls to CreateSender, AddStream and RemoveStream.
4802 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004803 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004804 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004805 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004806 }
deadbeeffac06552015-11-25 11:26:01 -08004807
Steve Anton4171afb2017-11-20 10:20:22 -08004808 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004809}
4810
4811void PeerConnection::UpdateLocalRtpDataChannels(
4812 const cricket::StreamParamsVec& streams) {
4813 std::vector<std::string> existing_channels;
4814
4815 // Find new and active data channels.
4816 for (const cricket::StreamParams& params : streams) {
4817 // |it->sync_label| is actually the data channel label. The reason is that
4818 // we use the same naming of data channels as we do for
4819 // MediaStreams and Tracks.
4820 // For MediaStreams, the sync_label is the MediaStream label and the
4821 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004822 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004823 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004824 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004825 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004826 continue;
4827 }
4828 // Set the SSRC the data channel should use for sending.
4829 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4830 existing_channels.push_back(data_channel_it->first);
4831 }
4832
4833 UpdateClosingRtpDataChannels(existing_channels, true);
4834}
4835
4836void PeerConnection::UpdateRemoteRtpDataChannels(
4837 const cricket::StreamParamsVec& streams) {
4838 std::vector<std::string> existing_channels;
4839
4840 // Find new and active data channels.
4841 for (const cricket::StreamParams& params : streams) {
4842 // The data channel label is either the mslabel or the SSRC if the mslabel
4843 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004844 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004845 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004846 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004847 auto data_channel_it = rtp_data_channels_.find(label);
4848 if (data_channel_it == rtp_data_channels_.end()) {
4849 // This is a new data channel.
4850 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4851 } else {
4852 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4853 }
4854 existing_channels.push_back(label);
4855 }
4856
4857 UpdateClosingRtpDataChannels(existing_channels, false);
4858}
4859
4860void PeerConnection::UpdateClosingRtpDataChannels(
4861 const std::vector<std::string>& active_channels,
4862 bool is_local_update) {
4863 auto it = rtp_data_channels_.begin();
4864 while (it != rtp_data_channels_.end()) {
4865 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004866 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004867 ++it;
4868 continue;
4869 }
4870
4871 if (is_local_update) {
4872 data_channel->SetSendSsrc(0);
4873 } else {
4874 data_channel->RemotePeerRequestClose();
4875 }
4876
4877 if (data_channel->state() == DataChannel::kClosed) {
4878 rtp_data_channels_.erase(it);
4879 it = rtp_data_channels_.begin();
4880 } else {
4881 ++it;
4882 }
4883 }
4884}
4885
4886void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4887 uint32_t remote_ssrc) {
4888 rtc::scoped_refptr<DataChannel> channel(
4889 InternalCreateDataChannel(label, nullptr));
4890 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004891 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004892 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004893 return;
4894 }
4895 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004896 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4897 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004898 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004899}
4900
4901rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4902 const std::string& label,
4903 const InternalDataChannelInit* config) {
4904 if (IsClosed()) {
4905 return nullptr;
4906 }
Steve Anton75737c02017-11-06 10:37:17 -08004907 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004908 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004909 << "InternalCreateDataChannel: Data is not supported in this call.";
4910 return nullptr;
4911 }
4912 InternalDataChannelInit new_config =
4913 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004914 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004915 if (new_config.id < 0) {
4916 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004917 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004918 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004919 RTC_LOG(LS_ERROR)
4920 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004921 return nullptr;
4922 }
4923 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004924 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004925 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004926 return nullptr;
4927 }
4928 }
4929
Steve Anton75737c02017-11-06 10:37:17 -08004930 rtc::scoped_refptr<DataChannel> channel(
4931 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004932 if (!channel) {
4933 sid_allocator_.ReleaseSid(new_config.id);
4934 return nullptr;
4935 }
4936
4937 if (channel->data_channel_type() == cricket::DCT_RTP) {
4938 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004939 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4940 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004941 return nullptr;
4942 }
4943 rtp_data_channels_[channel->label()] = channel;
4944 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004945 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004946 sctp_data_channels_.push_back(channel);
4947 channel->SignalClosed.connect(this,
4948 &PeerConnection::OnSctpDataChannelClosed);
4949 }
4950
Steve Anton2d8609c2018-01-23 16:38:46 -08004951 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004952 return channel;
4953}
4954
4955bool PeerConnection::HasDataChannels() const {
4956 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4957}
4958
4959void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4960 for (const auto& channel : sctp_data_channels_) {
4961 if (channel->id() < 0) {
4962 int sid;
4963 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004964 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004965 continue;
4966 }
4967 channel->SetSctpSid(sid);
4968 }
4969 }
4970}
4971
4972void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004973 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004974 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4975 ++it) {
4976 if (it->get() == channel) {
4977 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004978 // After the closing procedure is done, it's safe to use this ID for
4979 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004980 sid_allocator_.ReleaseSid(channel->id());
4981 }
deadbeefbd292462015-12-14 18:15:29 -08004982 // Since this method is triggered by a signal from the DataChannel,
4983 // we can't free it directly here; we need to free it asynchronously.
4984 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004985 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004986 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4987 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004988 return;
4989 }
4990 }
4991}
4992
deadbeefab9b2d12015-10-14 11:33:11 -07004993void PeerConnection::OnDataChannelDestroyed() {
4994 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4995 // DataChannel may callback to us and try to modify the list.
4996 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4997 temp_rtp_dcs.swap(rtp_data_channels_);
4998 for (const auto& kv : temp_rtp_dcs) {
4999 kv.second->OnTransportChannelDestroyed();
5000 }
5001
5002 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
5003 temp_sctp_dcs.swap(sctp_data_channels_);
5004 for (const auto& channel : temp_sctp_dcs) {
5005 channel->OnTransportChannelDestroyed();
5006 }
5007}
5008
5009void PeerConnection::OnDataChannelOpenMessage(
5010 const std::string& label,
5011 const InternalDataChannelInit& config) {
5012 rtc::scoped_refptr<DataChannel> channel(
5013 InternalCreateDataChannel(label, &config));
5014 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005015 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07005016 return;
5017 }
5018
deadbeefa601f5c2016-06-06 14:27:39 -07005019 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
5020 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005021 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02005022 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07005023}
5024
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005025bool PeerConnection::HandleOpenMessage_s(
5026 const cricket::ReceiveDataParams& params,
5027 const rtc::CopyOnWriteBuffer& buffer) {
5028 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
5029 // Received OPEN message; parse and signal that a new data channel should
5030 // be created.
5031 std::string label;
5032 InternalDataChannelInit config;
5033 config.id = params.ssrc;
5034 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5035 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5036 << params.ssrc;
5037 return true;
5038 }
5039 config.open_handshake_role = InternalDataChannelInit::kAcker;
5040 OnDataChannelOpenMessage(label, config);
5041 return true;
5042 }
5043 return false;
5044}
5045
Steve Anton4171afb2017-11-20 10:20:22 -08005046rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5047PeerConnection::GetAudioTransceiver() const {
5048 // This method only works with Plan B SDP, where there is a single
5049 // audio/video transceiver.
5050 RTC_DCHECK(!IsUnifiedPlan());
5051 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005052 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005053 return transceiver;
5054 }
5055 }
5056 RTC_NOTREACHED();
5057 return nullptr;
5058}
5059
5060rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5061PeerConnection::GetVideoTransceiver() const {
5062 // This method only works with Plan B SDP, where there is a single
5063 // audio/video transceiver.
5064 RTC_DCHECK(!IsUnifiedPlan());
5065 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005066 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005067 return transceiver;
5068 }
5069 }
5070 RTC_NOTREACHED();
5071 return nullptr;
5072}
5073
5074// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5075// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005076bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005077 switch (type) {
5078 case cricket::MEDIA_TYPE_AUDIO:
5079 return !GetAudioTransceiver()->internal()->senders().empty();
5080 case cricket::MEDIA_TYPE_VIDEO:
5081 return !GetVideoTransceiver()->internal()->senders().empty();
5082 case cricket::MEDIA_TYPE_DATA:
5083 return false;
5084 }
5085 RTC_NOTREACHED();
5086 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005087}
5088
Steve Anton4171afb2017-11-20 10:20:22 -08005089rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5090PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005091 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005092 for (auto sender : transceiver->internal()->senders()) {
5093 if (sender->track() == track) {
5094 return sender;
5095 }
5096 }
5097 }
5098 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005099}
5100
Steve Anton4171afb2017-11-20 10:20:22 -08005101rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5102PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005103 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005104 for (auto sender : transceiver->internal()->senders()) {
5105 if (sender->id() == sender_id) {
5106 return sender;
5107 }
5108 }
5109 }
5110 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005111}
5112
Steve Anton4171afb2017-11-20 10:20:22 -08005113rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5114PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005115 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005116 for (auto receiver : transceiver->internal()->receivers()) {
5117 if (receiver->id() == receiver_id) {
5118 return receiver;
5119 }
5120 }
5121 }
5122 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005123}
5124
Steve Anton4171afb2017-11-20 10:20:22 -08005125std::vector<PeerConnection::RtpSenderInfo>*
5126PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5127 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5128 media_type == cricket::MEDIA_TYPE_VIDEO);
5129 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5130 ? &remote_audio_sender_infos_
5131 : &remote_video_sender_infos_;
5132}
5133
5134std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005135 cricket::MediaType media_type) {
5136 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5137 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005138 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5139 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005140}
5141
Steve Anton4171afb2017-11-20 10:20:22 -08005142const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5143 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005144 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005145 const std::string sender_id) const {
5146 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005147 if (sender_info.stream_id == stream_id &&
5148 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005149 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005150 }
5151 }
5152 return nullptr;
5153}
5154
5155DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5156 for (const auto& channel : sctp_data_channels_) {
5157 if (channel->id() == sid) {
5158 return channel;
5159 }
5160 }
5161 return nullptr;
5162}
5163
deadbeef91dd5672016-05-18 16:55:30 -07005164bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005165 const cricket::ServerAddresses& stun_servers,
5166 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005167 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005168 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005169 // To handle both internal and externally created port allocator, we will
5170 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005171 port_allocator_flags_ = port_allocator_->flags();
5172 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5173 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5174 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005175 // If the disable-IPv6 flag was specified, we'll not override it
5176 // by experiment.
5177 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005178 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005179 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5180 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005181 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005182 }
5183
zhihuangb09b3f92017-03-07 14:40:51 -08005184 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005185 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005186 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005187 }
5188
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005189 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005190 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005191 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005192 }
5193
honghaiz60347052016-05-31 18:29:12 -07005194 if (configuration.candidate_network_policy ==
5195 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005196 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005197 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005198 }
5199
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005200 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005201 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005202 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5203 }
5204
Qingsi Wanga2d60672018-04-11 16:57:45 -07005205 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005206 // No step delay is used while allocating ports.
5207 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5208 port_allocator_->set_candidate_filter(
5209 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005210 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005211
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005212 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005213 for (auto& turn_server : turn_servers_copy) {
5214 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005215 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005216 // Call this last since it may create pooled allocator sessions using the
5217 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005218 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005219 stun_servers, std::move(turn_servers_copy),
5220 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5221 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005222 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005223 return true;
5224}
5225
deadbeef91dd5672016-05-18 16:55:30 -07005226bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005227 const cricket::ServerAddresses& stun_servers,
5228 const std::vector<cricket::RelayServerConfig>& turn_servers,
5229 IceTransportsType type,
5230 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005231 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005232 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005233 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005234 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005235 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005236 // According to JSEP, after setLocalDescription, changing the candidate pool
5237 // size is not allowed, and changing the set of ICE servers will not result
5238 // in new candidates being gathered.
5239 if (local_description()) {
5240 port_allocator_->FreezeCandidatePool();
5241 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005242 // Add the custom tls turn servers if they exist.
5243 auto turn_servers_copy = turn_servers;
5244 for (auto& turn_server : turn_servers_copy) {
5245 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5246 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005247 // Call this last since it may create pooled allocator sessions using the
5248 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005249 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005250 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5251 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005252}
5253
Steve Antonba818672017-11-06 10:21:57 -08005254cricket::ChannelManager* PeerConnection::channel_manager() const {
5255 return factory_->channel_manager();
5256}
5257
Elad Alon99c3fe52017-10-13 16:29:40 +02005258bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005259 std::unique_ptr<RtcEventLogOutput> output,
5260 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005261 if (!event_log_) {
5262 return false;
5263 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005264 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005265}
5266
5267void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005268 if (event_log_) {
5269 event_log_->StopLogging();
5270 }
ivoc14d5dbe2016-07-04 07:06:55 -07005271}
nisseeaabdf62017-05-05 02:23:02 -07005272
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005273cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005274 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005275 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005276 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005277 if (channel && channel->content_name() == content_name) {
5278 return channel;
5279 }
Steve Anton75737c02017-11-06 10:37:17 -08005280 }
5281 if (rtp_data_channel() &&
5282 rtp_data_channel()->content_name() == content_name) {
5283 return rtp_data_channel();
5284 }
5285 return nullptr;
5286}
5287
5288bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005289 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005290 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005291 RTC_LOG(LS_INFO)
5292 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005293 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005294 return false;
5295 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005296 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005297 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005298 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005299 return false;
5300 }
5301
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005302 absl::optional<rtc::SSLRole> dtls_role;
5303 if (sctp_mid_) {
5304 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5305 } else if (is_caller_) {
5306 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5307 }
Zhi Huange830e682018-03-30 10:48:35 -07005308 if (dtls_role) {
5309 *role = *dtls_role;
5310 return true;
5311 }
5312 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005313}
5314
5315bool PeerConnection::GetSslRole(const std::string& content_name,
5316 rtc::SSLRole* role) {
5317 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005318 RTC_LOG(LS_INFO)
5319 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005320 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005321 return false;
5322 }
5323
Zhi Huange830e682018-03-30 10:48:35 -07005324 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5325 if (dtls_role) {
5326 *role = *dtls_role;
5327 return true;
5328 }
5329 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005330}
5331
Steve Antonf8470812017-12-04 10:46:21 -08005332void PeerConnection::SetSessionError(SessionError error,
5333 const std::string& error_desc) {
5334 RTC_DCHECK_RUN_ON(signaling_thread());
5335 if (error != session_error_) {
5336 session_error_ = error;
5337 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005338 }
5339}
5340
Zhi Huange830e682018-03-30 10:48:35 -07005341RTCError PeerConnection::UpdateSessionState(
5342 SdpType type,
5343 cricket::ContentSource source,
5344 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005345 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005346
5347 // If there's already a pending error then no state transition should happen.
5348 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005349 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005350
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005351 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005352 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005353 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005354 }
5355
5356 // Update the signaling state according to the specified state machine (see
5357 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005358 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005359 ChangeSignalingState(source == cricket::CS_LOCAL
5360 ? PeerConnectionInterface::kHaveLocalOffer
5361 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005362 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005363 ChangeSignalingState(source == cricket::CS_LOCAL
5364 ? PeerConnectionInterface::kHaveLocalPrAnswer
5365 : PeerConnectionInterface::kHaveRemotePrAnswer);
5366 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005367 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005368 ChangeSignalingState(PeerConnectionInterface::kStable);
5369 }
5370
5371 // Update internal objects according to the session description's media
5372 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005373 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005374 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005375 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005376 }
5377
Steve Anton8a006912017-12-04 15:25:56 -08005378 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005379}
5380
Steve Anton8a006912017-12-04 15:25:56 -08005381RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005382 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005383 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005384 const SessionDescriptionInterface* sdesc =
5385 (source == cricket::CS_LOCAL ? local_description()
5386 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005387 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005388
5389 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005390 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005391 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005392 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005393 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005394 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005395 continue;
5396 }
5397 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005398 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005399 if (!content_desc) {
5400 continue;
5401 }
5402 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005403 bool success = (source == cricket::CS_LOCAL)
5404 ? channel->SetLocalContent(content_desc, type, &error)
5405 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005406 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005407 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005408 }
5409 }
5410
5411 // If using the RtpDataChannel, push down the new SDP section for it too.
5412 if (rtp_data_channel_) {
5413 const ContentInfo* data_content =
5414 cricket::GetFirstDataContent(sdesc->description());
5415 if (data_content && !data_content->rejected) {
5416 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005417 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005418 if (data_desc) {
5419 std::string error;
5420 bool success =
5421 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005422 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005423 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005424 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005425 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005426 }
Steve Anton75737c02017-11-06 10:37:17 -08005427 }
5428 }
5429 }
Steve Antoned10bd92017-12-05 10:52:59 -08005430
Steve Anton75737c02017-11-06 10:37:17 -08005431 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5432 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5433 if (sctp_transport_ && local_description() && remote_description() &&
5434 cricket::GetFirstDataContent(local_description()->description()) &&
5435 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005436 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005437 RTC_FROM_HERE,
5438 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005439 if (!success) {
5440 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5441 "Failed to push down SCTP parameters.");
5442 }
Steve Anton75737c02017-11-06 10:37:17 -08005443 }
Steve Antoned10bd92017-12-05 10:52:59 -08005444
Steve Anton8a006912017-12-04 15:25:56 -08005445 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005446}
5447
5448bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5449 RTC_DCHECK(network_thread()->IsCurrent());
5450 RTC_DCHECK(local_description());
5451 RTC_DCHECK(remote_description());
5452 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5453 // When we support "max-message-size", that would also be pushed down here.
5454 return sctp_transport_->Start(
5455 GetSctpPort(local_description()->description()),
5456 GetSctpPort(remote_description()->description()));
5457}
5458
Steve Anton8a006912017-12-04 15:25:56 -08005459RTCError PeerConnection::PushdownTransportDescription(
5460 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005461 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005462 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005463
Zhi Huange830e682018-03-30 10:48:35 -07005464 if (source == cricket::CS_LOCAL) {
5465 const SessionDescriptionInterface* sdesc = local_description();
5466 RTC_DCHECK(sdesc);
5467 return transport_controller_->SetLocalDescription(type,
5468 sdesc->description());
5469 } else {
5470 const SessionDescriptionInterface* sdesc = remote_description();
5471 RTC_DCHECK(sdesc);
5472 return transport_controller_->SetRemoteDescription(type,
5473 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005474 }
Steve Anton75737c02017-11-06 10:37:17 -08005475}
5476
5477bool PeerConnection::GetTransportDescription(
5478 const SessionDescription* description,
5479 const std::string& content_name,
5480 cricket::TransportDescription* tdesc) {
5481 if (!description || !tdesc) {
5482 return false;
5483 }
5484 const TransportInfo* transport_info =
5485 description->GetTransportInfoByName(content_name);
5486 if (!transport_info) {
5487 return false;
5488 }
5489 *tdesc = transport_info->description;
5490 return true;
5491}
5492
Steve Anton75737c02017-11-06 10:37:17 -08005493cricket::IceConfig PeerConnection::ParseIceConfig(
5494 const PeerConnectionInterface::RTCConfiguration& config) const {
5495 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005496 switch (config.continual_gathering_policy) {
5497 case PeerConnectionInterface::GATHER_ONCE:
5498 gathering_policy = cricket::GATHER_ONCE;
5499 break;
5500 case PeerConnectionInterface::GATHER_CONTINUALLY:
5501 gathering_policy = cricket::GATHER_CONTINUALLY;
5502 break;
5503 default:
5504 RTC_NOTREACHED();
5505 gathering_policy = cricket::GATHER_ONCE;
5506 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005507
Steve Anton75737c02017-11-06 10:37:17 -08005508 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005509 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5510 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005511 ice_config.prioritize_most_likely_candidate_pairs =
5512 config.prioritize_most_likely_ice_candidate_pairs;
5513 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005514 RTCConfigurationToIceConfigOptionalInt(
5515 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005516 ice_config.continual_gathering_policy = gathering_policy;
5517 ice_config.presume_writable_when_fully_relayed =
5518 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005519 ice_config.ice_check_interval_strong_connectivity =
5520 config.ice_check_interval_strong_connectivity;
5521 ice_config.ice_check_interval_weak_connectivity =
5522 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005523 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005524 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5525 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005526 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005527 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005528 ice_config.regather_all_networks_interval_range =
5529 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005530 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005531 return ice_config;
5532}
5533
Steve Antona41959e2018-11-28 11:15:33 -08005534static absl::string_view GetTrackIdBySsrc(
5535 const SessionDescriptionInterface* session_description,
5536 uint32_t ssrc) {
5537 if (!session_description) {
5538 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005539 }
Steve Antona41959e2018-11-28 11:15:33 -08005540 for (const cricket::ContentInfo& content :
5541 session_description->description()->contents()) {
5542 const cricket::MediaContentDescription& media =
5543 *content.media_description();
5544 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5545 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5546 const cricket::StreamParams* stream_params =
5547 cricket::GetStreamBySsrc(media.streams(), ssrc);
5548 if (stream_params) {
5549 return stream_params->id;
5550 }
5551 }
5552 }
5553 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005554}
5555
Steve Antona41959e2018-11-28 11:15:33 -08005556absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5557 return GetTrackIdBySsrc(local_description(), ssrc);
5558}
5559
5560absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5561 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005562}
5563
5564bool PeerConnection::SendData(const cricket::SendDataParams& params,
5565 const rtc::CopyOnWriteBuffer& payload,
5566 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005567 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5568 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5569 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005570 return false;
5571 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005572 if (media_transport_) {
5573 SendDataParams send_params;
5574 send_params.type = ToWebrtcDataMessageType(params.type);
5575 send_params.ordered = params.ordered;
5576 if (params.max_rtx_count >= 0) {
5577 send_params.max_rtx_count = params.max_rtx_count;
5578 } else if (params.max_rtx_ms >= 0) {
5579 send_params.max_rtx_ms = params.max_rtx_ms;
5580 }
5581 return media_transport_->SendData(params.sid, send_params, payload).ok();
5582 }
Steve Anton75737c02017-11-06 10:37:17 -08005583 return rtp_data_channel_
5584 ? rtp_data_channel_->SendData(params, payload, result)
5585 : network_thread()->Invoke<bool>(
5586 RTC_FROM_HERE,
5587 Bind(&cricket::SctpTransportInternal::SendData,
5588 sctp_transport_.get(), params, payload, result));
5589}
5590
5591bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005592 RTC_DCHECK_RUN_ON(signaling_thread());
5593 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005594 // Don't log an error here, because DataChannels are expected to call
5595 // ConnectDataChannel in this state. It's the only way to initially tell
5596 // whether or not the underlying transport is ready.
5597 return false;
5598 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005599 if (media_transport_) {
5600 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5601 &DataChannel::OnChannelReady);
5602 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5603 &DataChannel::OnDataReceived);
5604 SignalMediaTransportChannelClosing_s.connect(
5605 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5606 SignalMediaTransportChannelClosed_s.connect(
5607 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5608 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005609 rtp_data_channel_->SignalReadyToSendData.connect(
5610 webrtc_data_channel, &DataChannel::OnChannelReady);
5611 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5612 &DataChannel::OnDataReceived);
5613 } else {
5614 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5615 &DataChannel::OnChannelReady);
5616 SignalSctpDataReceived.connect(webrtc_data_channel,
5617 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005618 SignalSctpClosingProcedureStartedRemotely.connect(
5619 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5620 SignalSctpClosingProcedureComplete.connect(
5621 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005622 }
5623 return true;
5624}
5625
5626void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005627 RTC_DCHECK_RUN_ON(signaling_thread());
5628 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005629 RTC_LOG(LS_ERROR)
5630 << "DisconnectDataChannel called when rtp_data_channel_ and "
5631 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005632 return;
5633 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005634 if (media_transport_) {
5635 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5636 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5637 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5638 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5639 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005640 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5641 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5642 } else {
5643 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5644 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005645 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5646 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005647 }
5648}
5649
5650void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005651 if (media_transport_) {
5652 // No-op. Media transport does not need to add streams.
5653 return;
5654 }
Steve Anton75737c02017-11-06 10:37:17 -08005655 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005656 RTC_LOG(LS_ERROR)
5657 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005658 return;
5659 }
5660 network_thread()->Invoke<void>(
5661 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5662 sctp_transport_.get(), sid));
5663}
5664
5665void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005666 if (media_transport_) {
5667 media_transport_->CloseChannel(sid);
5668 return;
5669 }
Steve Anton75737c02017-11-06 10:37:17 -08005670 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005671 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005672 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005673 return;
5674 }
5675 network_thread()->Invoke<void>(
5676 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5677 sctp_transport_.get(), sid));
5678}
5679
5680bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005681 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005682 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005683 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005684 sctp_ready_to_send_data_;
5685}
5686
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005687void PeerConnection::OnDataReceived(int channel_id,
5688 DataMessageType type,
5689 const rtc::CopyOnWriteBuffer& buffer) {
5690 cricket::ReceiveDataParams params;
5691 params.sid = channel_id;
5692 params.type = ToCricketDataMessageType(type);
5693 media_transport_invoker_->AsyncInvoke<void>(
5694 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5695 RTC_DCHECK_RUN_ON(signaling_thread());
5696 if (!HandleOpenMessage_s(params, buffer)) {
5697 SignalMediaTransportReceivedData_s(params, buffer);
5698 }
5699 });
5700}
5701
5702void PeerConnection::OnChannelClosing(int channel_id) {
5703 media_transport_invoker_->AsyncInvoke<void>(
5704 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5705 RTC_DCHECK_RUN_ON(signaling_thread());
5706 SignalMediaTransportChannelClosing_s(channel_id);
5707 });
5708}
5709
5710void PeerConnection::OnChannelClosed(int channel_id) {
5711 media_transport_invoker_->AsyncInvoke<void>(
5712 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5713 RTC_DCHECK_RUN_ON(signaling_thread());
5714 SignalMediaTransportChannelClosed_s(channel_id);
5715 });
5716}
5717
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005718absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005719 if (sctp_mid_ && transport_controller_) {
5720 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5721 if (dtls_transport) {
5722 return dtls_transport->transport_name();
5723 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005724 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005725 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005726 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005727}
5728
Qingsi Wang72a43a12018-02-20 16:03:18 -08005729cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5730 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005731 network_thread()->Invoke<void>(
5732 RTC_FROM_HERE,
5733 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5734 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005735 return candidate_states_list;
5736}
5737
Steve Anton5dfde182018-02-06 10:34:40 -08005738std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5739 const {
5740 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005741 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005742 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005743 if (channel) {
5744 transport_names_by_mid[channel->content_name()] =
5745 channel->transport_name();
5746 }
Steve Anton75737c02017-11-06 10:37:17 -08005747 }
Steve Anton5dfde182018-02-06 10:34:40 -08005748 if (rtp_data_channel_) {
5749 transport_names_by_mid[rtp_data_channel_->content_name()] =
5750 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005751 }
5752 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005753 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005754 RTC_DCHECK(transport_name);
5755 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
Steve Anton5dfde182018-02-06 10:34:40 -08005757 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005758}
5759
Steve Anton5dfde182018-02-06 10:34:40 -08005760std::map<std::string, cricket::TransportStats>
5761PeerConnection::GetTransportStatsByNames(
5762 const std::set<std::string>& transport_names) {
5763 if (!network_thread()->IsCurrent()) {
5764 return network_thread()
5765 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5766 RTC_FROM_HERE,
5767 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005768 }
Steve Anton5dfde182018-02-06 10:34:40 -08005769 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5770 for (const std::string& transport_name : transport_names) {
5771 cricket::TransportStats transport_stats;
5772 bool success =
5773 transport_controller_->GetStats(transport_name, &transport_stats);
5774 if (success) {
5775 transport_stats_by_name[transport_name] = std::move(transport_stats);
5776 } else {
5777 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5778 << transport_name;
5779 }
5780 }
5781 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005782}
5783
5784bool PeerConnection::GetLocalCertificate(
5785 const std::string& transport_name,
5786 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005787 if (!certificate) {
5788 return false;
5789 }
5790 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5791 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005792}
5793
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005794std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005795 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005796 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005797}
5798
5799cricket::DataChannelType PeerConnection::data_channel_type() const {
5800 return data_channel_type_;
5801}
5802
5803bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5804 return pending_ice_restarts_.find(content_name) !=
5805 pending_ice_restarts_.end();
5806}
5807
Steve Anton75737c02017-11-06 10:37:17 -08005808bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5809 return transport_controller_->NeedsIceRestart(content_name);
5810}
5811
5812void PeerConnection::OnCertificateReady(
5813 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5814 transport_controller_->SetLocalCertificate(certificate);
5815}
5816
5817void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005818 SetSessionError(SessionError::kTransport,
5819 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005820}
5821
Alex Loiko9289eda2018-11-23 16:18:59 +00005822void PeerConnection::OnTransportControllerConnectionState(
5823 cricket::IceConnectionState state) {
5824 switch (state) {
5825 case cricket::kIceConnectionConnecting:
5826 // If the current state is Connected or Completed, then there were
5827 // writable channels but now there are not, so the next state must
5828 // be Disconnected.
5829 // kIceConnectionConnecting is currently used as the default,
5830 // un-connected state by the TransportController, so its only use is
5831 // detecting disconnections.
5832 if (ice_connection_state_ ==
5833 PeerConnectionInterface::kIceConnectionConnected ||
5834 ice_connection_state_ ==
5835 PeerConnectionInterface::kIceConnectionCompleted) {
5836 SetIceConnectionState(
5837 PeerConnectionInterface::kIceConnectionDisconnected);
5838 }
5839 break;
5840 case cricket::kIceConnectionFailed:
5841 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5842 break;
5843 case cricket::kIceConnectionConnected:
5844 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5845 "all transports are writable.";
5846 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5847 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5848 break;
5849 case cricket::kIceConnectionCompleted:
5850 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5851 "all transports are complete.";
5852 if (ice_connection_state_ !=
5853 PeerConnectionInterface::kIceConnectionConnected) {
5854 // If jumping directly from "checking" to "connected",
5855 // signal "connected" first.
5856 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5857 }
5858 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5859 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5860 ReportTransportStats();
5861 break;
5862 default:
5863 RTC_NOTREACHED();
5864 }
5865}
5866
Steve Anton75737c02017-11-06 10:37:17 -08005867void PeerConnection::OnTransportControllerCandidatesGathered(
5868 const std::string& transport_name,
5869 const cricket::Candidates& candidates) {
5870 RTC_DCHECK(signaling_thread()->IsCurrent());
5871 int sdp_mline_index;
5872 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005873 RTC_LOG(LS_ERROR)
5874 << "OnTransportControllerCandidatesGathered: content name "
5875 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005876 return;
5877 }
5878
5879 for (cricket::Candidates::const_iterator citer = candidates.begin();
5880 citer != candidates.end(); ++citer) {
5881 // Use transport_name as the candidate media id.
5882 std::unique_ptr<JsepIceCandidate> candidate(
5883 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5884 if (local_description()) {
5885 mutable_local_description()->AddCandidate(candidate.get());
5886 }
5887 OnIceCandidate(std::move(candidate));
5888 }
5889}
5890
5891void PeerConnection::OnTransportControllerCandidatesRemoved(
5892 const std::vector<cricket::Candidate>& candidates) {
5893 RTC_DCHECK(signaling_thread()->IsCurrent());
5894 // Sanity check.
5895 for (const cricket::Candidate& candidate : candidates) {
5896 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005897 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005898 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005899 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005900 return;
5901 }
5902 }
5903
5904 if (local_description()) {
5905 mutable_local_description()->RemoveCandidates(candidates);
5906 }
5907 OnIceCandidatesRemoved(candidates);
5908}
5909
5910void PeerConnection::OnTransportControllerDtlsHandshakeError(
5911 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005912 RTC_HISTOGRAM_ENUMERATION(
5913 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5914 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005915}
5916
Steve Antoned10bd92017-12-05 10:52:59 -08005917void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005918 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005919 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005920 if (channel && !channel->enabled()) {
5921 channel->Enable(true);
5922 }
Steve Anton75737c02017-11-06 10:37:17 -08005923 }
5924
Steve Anton4171afb2017-11-20 10:20:22 -08005925 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005926 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005927 }
Steve Anton75737c02017-11-06 10:37:17 -08005928}
5929
5930// Returns the media index for a local ice candidate given the content name.
5931bool PeerConnection::GetLocalCandidateMediaIndex(
5932 const std::string& content_name,
5933 int* sdp_mline_index) {
5934 if (!local_description() || !sdp_mline_index) {
5935 return false;
5936 }
5937
5938 bool content_found = false;
5939 const ContentInfos& contents = local_description()->description()->contents();
5940 for (size_t index = 0; index < contents.size(); ++index) {
5941 if (contents[index].name == content_name) {
5942 *sdp_mline_index = static_cast<int>(index);
5943 content_found = true;
5944 break;
5945 }
5946 }
5947 return content_found;
5948}
5949
5950bool PeerConnection::UseCandidatesInSessionDescription(
5951 const SessionDescriptionInterface* remote_desc) {
5952 if (!remote_desc) {
5953 return true;
5954 }
5955 bool ret = true;
5956
5957 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5958 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5959 for (size_t n = 0; n < candidates->count(); ++n) {
5960 const IceCandidateInterface* candidate = candidates->at(n);
5961 bool valid = false;
5962 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5963 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005964 RTC_LOG(LS_INFO)
5965 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005966 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005967 }
5968 continue;
5969 }
5970 ret = UseCandidate(candidate);
5971 if (!ret) {
5972 break;
5973 }
5974 }
5975 }
5976 return ret;
5977}
5978
5979bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5980 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5981 size_t remote_content_size =
5982 remote_description()->description()->contents().size();
5983 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005984 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005985 return false;
5986 }
5987
5988 cricket::ContentInfo content =
5989 remote_description()->description()->contents()[mediacontent_index];
5990 std::vector<cricket::Candidate> candidates;
5991 candidates.push_back(candidate->candidate());
5992 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005993 RTCError error =
5994 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005995 if (error.ok()) {
5996 // Candidates successfully submitted for checking.
5997 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5998 ice_connection_state_ ==
5999 PeerConnectionInterface::kIceConnectionDisconnected) {
6000 // If state is New, then the session has just gotten its first remote ICE
6001 // candidates, so go to Checking.
6002 // If state is Disconnected, the session is re-using old candidates or
6003 // receiving additional ones, so go to Checking.
6004 // If state is Connected, stay Connected.
6005 // TODO(bemasc): If state is Connected, and the new candidates are for a
6006 // newly added transport, then the state actually _should_ move to
6007 // checking. Add a way to distinguish that case.
6008 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
6009 }
6010 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02006011 } else {
Zhi Huange830e682018-03-30 10:48:35 -07006012 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08006013 }
6014 return true;
6015}
6016
6017void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08006018 // Destroy video channel first since it may have a pointer to the
6019 // voice channel.
6020 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08006021 if (!video_info || video_info->rejected) {
6022 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006023 }
6024
Steve Anton6fec8802017-12-04 10:37:29 -08006025 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
6026 if (!audio_info || audio_info->rejected) {
6027 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08006028 }
6029
6030 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
6031 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08006032 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08006033 }
6034}
6035
Steve Antondcc3c022017-12-22 16:02:54 -08006036RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6037 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006038 const cricket::ContentGroup* bundle_group = nullptr;
6039 if (configuration_.bundle_policy ==
6040 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006041 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006042 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006043 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6044 "max-bundle configured but session description "
6045 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006046 }
6047 }
Mirko Bonadei9f3a44f2019-01-30 13:47:42 +01006048 return bundle_group;
Steve Antondcc3c022017-12-22 16:02:54 -08006049}
6050
6051RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006052 // Creating the media channels. Transports should already have been created
6053 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006054 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006055 if (voice && !voice->rejected &&
6056 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006057 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006058 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006059 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6060 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006061 }
6062 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6063 }
6064
Steve Antondcc3c022017-12-22 16:02:54 -08006065 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006066 if (video && !video->rejected &&
6067 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006068 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006069 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006070 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6071 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006072 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006073 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006074 }
6075
Steve Antondcc3c022017-12-22 16:02:54 -08006076 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006077 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006078 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006079 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006080 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6081 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006082 }
6083 }
6084
Steve Anton8a006912017-12-04 15:25:56 -08006085 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006086}
6087
Steve Anton4171afb2017-11-20 10:20:22 -08006088// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006089cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006090 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006091 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006092 MediaTransportInterface* media_transport = nullptr;
6093 if (configuration_.use_media_transport) {
6094 media_transport = GetMediaTransport(mid);
6095 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006096
Steve Anton75737c02017-11-06 10:37:17 -08006097 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006098 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006099 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006100 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006101 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006102 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006103 }
Steve Anton75737c02017-11-06 10:37:17 -08006104 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6105 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006106 voice_channel->SignalSentPacket.connect(this,
6107 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006108 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006109
Steve Antoneda6ccd2017-12-04 10:21:55 -08006110 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006111}
6112
Steve Anton4171afb2017-11-20 10:20:22 -08006113// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006114cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006115 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006116 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006117 MediaTransportInterface* media_transport = nullptr;
6118 if (configuration_.use_media_transport) {
6119 media_transport = GetMediaTransport(mid);
6120 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006121
Steve Anton75737c02017-11-06 10:37:17 -08006122 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006123 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006124 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006125 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006126 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006127 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006128 }
Steve Anton75737c02017-11-06 10:37:17 -08006129 video_channel->SignalDtlsSrtpSetupFailure.connect(
6130 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006131 video_channel->SignalSentPacket.connect(this,
6132 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006133 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006134
Steve Antoneda6ccd2017-12-04 10:21:55 -08006135 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006136}
6137
Zhi Huange830e682018-03-30 10:48:35 -07006138bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006139 switch (data_channel_type_) {
6140 case cricket::DCT_MEDIA_TRANSPORT:
6141 if (network_thread()->Invoke<bool>(
6142 RTC_FROM_HERE,
6143 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6144 this, mid))) {
6145 for (const auto& channel : sctp_data_channels_) {
6146 channel->OnTransportChannelCreated();
6147 }
6148 return true;
6149 }
Steve Anton75737c02017-11-06 10:37:17 -08006150 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006151 case cricket::DCT_SCTP:
6152 if (!sctp_factory_) {
6153 RTC_LOG(LS_ERROR)
6154 << "Trying to create SCTP transport, but didn't compile with "
6155 "SCTP support (HAVE_SCTP)";
6156 return false;
6157 }
6158 if (!network_thread()->Invoke<bool>(
6159 RTC_FROM_HERE,
6160 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6161 return false;
6162 }
6163 for (const auto& channel : sctp_data_channels_) {
6164 channel->OnTransportChannelCreated();
6165 }
6166 return true;
6167 case cricket::DCT_RTP:
6168 default:
6169 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6170 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6171 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006172 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006173 if (!rtp_data_channel_) {
6174 return false;
6175 }
6176 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6177 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6178 rtp_data_channel_->SignalSentPacket.connect(
6179 this, &PeerConnection::OnSentPacket_w);
6180 rtp_data_channel_->SetRtpTransport(rtp_transport);
6181 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006182 }
6183
Steve Anton75737c02017-11-06 10:37:17 -08006184 return true;
6185}
6186
6187Call::Stats PeerConnection::GetCallStats() {
6188 if (!worker_thread()->IsCurrent()) {
6189 return worker_thread()->Invoke<Call::Stats>(
6190 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6191 }
6192 if (call_) {
6193 return call_->GetStats();
6194 } else {
6195 return Call::Stats();
6196 }
6197}
6198
Zhi Huange830e682018-03-30 10:48:35 -07006199bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006200 RTC_DCHECK(network_thread()->IsCurrent());
6201 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006202 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006203 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006204 RTC_DCHECK(dtls_transport);
6205 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006206 RTC_DCHECK(sctp_transport_);
6207 sctp_invoker_.reset(new rtc::AsyncInvoker());
6208 sctp_transport_->SignalReadyToSendData.connect(
6209 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6210 sctp_transport_->SignalDataReceived.connect(
6211 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006212 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6213 // another thread. Would be nice if there was a helper class similar to
6214 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6215 // code.
6216 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6217 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6218 sctp_transport_->SignalClosingProcedureComplete.connect(
6219 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006220 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006221 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006222 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006223}
6224
6225void PeerConnection::DestroySctpTransport_n() {
6226 RTC_DCHECK(network_thread()->IsCurrent());
6227 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006228 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006229 sctp_invoker_.reset(nullptr);
6230 sctp_ready_to_send_data_ = false;
6231}
6232
6233void PeerConnection::OnSctpTransportReadyToSendData_n() {
6234 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6235 RTC_DCHECK(network_thread()->IsCurrent());
6236 // Note: Cannot use rtc::Bind here because it will grab a reference to
6237 // PeerConnection and potentially cause PeerConnection to live longer than
6238 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6239 // be destroyed before PeerConnection is destroyed, and at that point all
6240 // pending tasks will be cleared.
6241 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6242 OnSctpTransportReadyToSendData_s(true);
6243 });
6244}
6245
6246void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6247 RTC_DCHECK(signaling_thread()->IsCurrent());
6248 sctp_ready_to_send_data_ = ready;
6249 SignalSctpReadyToSendData(ready);
6250}
6251
6252void PeerConnection::OnSctpTransportDataReceived_n(
6253 const cricket::ReceiveDataParams& params,
6254 const rtc::CopyOnWriteBuffer& payload) {
6255 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6256 RTC_DCHECK(network_thread()->IsCurrent());
6257 // Note: Cannot use rtc::Bind here because it will grab a reference to
6258 // PeerConnection and potentially cause PeerConnection to live longer than
6259 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6260 // be destroyed before PeerConnection is destroyed, and at that point all
6261 // pending tasks will be cleared.
6262 sctp_invoker_->AsyncInvoke<void>(
6263 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6264 OnSctpTransportDataReceived_s(params, payload);
6265 });
6266}
6267
6268void PeerConnection::OnSctpTransportDataReceived_s(
6269 const cricket::ReceiveDataParams& params,
6270 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006271 RTC_DCHECK_RUN_ON(signaling_thread());
6272 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006273 SignalSctpDataReceived(params, payload);
6274 }
6275}
6276
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006277void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006278 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6279 RTC_DCHECK(network_thread()->IsCurrent());
6280 sctp_invoker_->AsyncInvoke<void>(
6281 RTC_FROM_HERE, signaling_thread(),
6282 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006283 &SignalSctpClosingProcedureStartedRemotely, sid));
6284}
6285
6286void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6287 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6288 RTC_DCHECK(network_thread()->IsCurrent());
6289 sctp_invoker_->AsyncInvoke<void>(
6290 RTC_FROM_HERE, signaling_thread(),
6291 rtc::Bind(&sigslot::signal1<int>::operator(),
6292 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006293}
6294
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006295bool PeerConnection::SetupMediaTransportForDataChannels_n(
6296 const std::string& mid) {
6297 media_transport_ = transport_controller_->GetMediaTransport(mid);
6298 if (!media_transport_) {
6299 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6300 return false;
6301 }
6302
6303 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6304 media_transport_->SetDataSink(this);
6305 media_transport_data_mid_ = mid;
6306 transport_controller_->SignalMediaTransportStateChanged.connect(
6307 this, &PeerConnection::OnMediaTransportStateChanged_n);
6308 // Check the initial state right away, in case transport is already writable.
6309 OnMediaTransportStateChanged_n();
6310 return true;
6311}
6312
6313void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6314 if (!media_transport_) {
6315 return;
6316 }
6317 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6318 media_transport_data_mid_.reset();
6319 media_transport_->SetDataSink(nullptr);
6320 media_transport_invoker_ = nullptr;
6321 media_transport_ = nullptr;
6322}
6323
6324void PeerConnection::OnMediaTransportStateChanged_n() {
6325 if (!media_transport_data_mid_ ||
6326 transport_controller_->GetMediaTransportState(
6327 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6328 return;
6329 }
6330 media_transport_invoker_->AsyncInvoke<void>(
6331 RTC_FROM_HERE, signaling_thread(), [this] {
6332 RTC_DCHECK_RUN_ON(signaling_thread());
6333 media_transport_ready_to_send_data_ = true;
6334 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6335 });
6336}
6337
Steve Anton75737c02017-11-06 10:37:17 -08006338// Returns false if bundle is enabled and rtcp_mux is disabled.
6339bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6340 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6341 if (!bundle_enabled)
6342 return true;
6343
6344 const cricket::ContentGroup* bundle_group =
6345 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6346 RTC_DCHECK(bundle_group != NULL);
6347
6348 const cricket::ContentInfos& contents = desc->contents();
6349 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6350 citer != contents.end(); ++citer) {
6351 const cricket::ContentInfo* content = (&*citer);
6352 RTC_DCHECK(content != NULL);
6353 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006354 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006355 if (!HasRtcpMuxEnabled(content))
6356 return false;
6357 }
6358 }
6359 // RTCP-MUX is enabled in all the contents.
6360 return true;
6361}
6362
6363bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006364 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006365}
6366
Steve Anton06817cd2018-12-18 15:55:30 -08006367static RTCError ValidateMids(const cricket::SessionDescription& description) {
6368 std::set<std::string> mids;
6369 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006370 if (content.name.empty()) {
6371 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6372 "A media section is missing a MID attribute.");
6373 }
Steve Anton06817cd2018-12-18 15:55:30 -08006374 if (!mids.insert(content.name).second) {
6375 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6376 "Duplicate a=mid value '" + content.name + "'.");
6377 }
6378 }
6379 return RTCError::OK();
6380}
6381
Steve Anton8a006912017-12-04 15:25:56 -08006382RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006383 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006384 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006385 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006386 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006387 }
6388
6389 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006390 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006391 }
6392
Steve Anton3828c062017-12-06 10:34:51 -08006393 SdpType type = sdesc->GetType();
6394 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6395 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006396 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006397 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006398 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006399 }
6400
Steve Anton06817cd2018-12-18 15:55:30 -08006401 RTCError error = ValidateMids(*sdesc->description());
6402 if (!error.ok()) {
6403 return error;
6404 }
6405
Steve Anton75737c02017-11-06 10:37:17 -08006406 // Verify crypto settings.
6407 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006408 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6409 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006410 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006411 if (!crypto_error.ok()) {
6412 return crypto_error;
6413 }
Steve Anton75737c02017-11-06 10:37:17 -08006414 }
6415
6416 // Verify ice-ufrag and ice-pwd.
6417 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006418 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6419 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006420 }
6421
6422 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006423 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6424 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006425 }
6426
6427 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6428 // m-lines that do not rtcp-mux enabled.
6429
6430 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006431 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006432 // With an answer we want to compare the new answer session description with
6433 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006434 const cricket::SessionDescription* offer_desc =
6435 (source == cricket::CS_LOCAL) ? remote_description()->description()
6436 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006437 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6438 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6439 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006440 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6441 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006442 }
6443 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006444 // The re-offers should respect the order of m= sections in current
6445 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006446 // With a re-offer, either the current local or current remote descriptions
6447 // could be the most up to date, so we would like to check against both of
6448 // them if they exist. It could be the case that one of them has a 0 port
6449 // for a media section, but the other does not. This is important to check
6450 // against in the case that we are recycling an m= section.
6451 const cricket::SessionDescription* current_desc = nullptr;
6452 const cricket::SessionDescription* secondary_current_desc = nullptr;
6453 if (local_description()) {
6454 current_desc = local_description()->description();
6455 if (remote_description()) {
6456 secondary_current_desc = remote_description()->description();
6457 }
6458 } else if (remote_description()) {
6459 current_desc = remote_description()->description();
6460 }
Steve Anton75737c02017-11-06 10:37:17 -08006461 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006462 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6463 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6465 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006466 }
6467 }
6468
Steve Antonba42e992018-04-09 14:10:01 -07006469 if (IsUnifiedPlan()) {
6470 // Ensure that each audio and video media section has at most one
6471 // "StreamParams". This will return an error if receiving a session
6472 // description from a "Plan B" endpoint which adds multiple tracks of the
6473 // same type. With Unified Plan, there can only be at most one track per
6474 // media section.
6475 for (const ContentInfo& content : sdesc->description()->contents()) {
6476 const MediaContentDescription& desc = *content.description;
6477 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6478 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6479 desc.streams().size() > 1u) {
6480 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6481 "Media section has more than one track specified "
6482 "with a=ssrc lines which is not supported with "
6483 "Unified Plan.");
6484 }
6485 }
6486 }
6487
Steve Anton8a006912017-12-04 15:25:56 -08006488 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006489}
6490
Steve Anton3828c062017-12-06 10:34:51 -08006491bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006492 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006493 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006494 return (state == PeerConnectionInterface::kStable) ||
6495 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006496 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006497 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006498 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6499 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6500 }
6501}
6502
Steve Anton3828c062017-12-06 10:34:51 -08006503bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006504 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006505 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006506 return (state == PeerConnectionInterface::kStable) ||
6507 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006508 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006509 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006510 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6511 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6512 }
6513}
6514
Steve Antonf8470812017-12-04 10:46:21 -08006515const char* PeerConnection::SessionErrorToString(SessionError error) const {
6516 switch (error) {
6517 case SessionError::kNone:
6518 return "ERROR_NONE";
6519 case SessionError::kContent:
6520 return "ERROR_CONTENT";
6521 case SessionError::kTransport:
6522 return "ERROR_TRANSPORT";
6523 }
6524 RTC_NOTREACHED();
6525 return "";
6526}
6527
Steve Anton75737c02017-11-06 10:37:17 -08006528std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006529 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006530 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6531 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006532 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006533}
6534
Steve Anton8e20f172018-03-06 10:55:04 -08006535void PeerConnection::ReportSdpFormatReceived(
6536 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006537 int num_audio_mlines = 0;
6538 int num_video_mlines = 0;
6539 int num_audio_tracks = 0;
6540 int num_video_tracks = 0;
6541 for (const ContentInfo& content : remote_offer.description()->contents()) {
6542 cricket::MediaType media_type = content.media_description()->type();
6543 int num_tracks = std::max(
6544 1, static_cast<int>(content.media_description()->streams().size()));
6545 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6546 num_audio_mlines += 1;
6547 num_audio_tracks += num_tracks;
6548 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6549 num_video_mlines += 1;
6550 num_video_tracks += num_tracks;
6551 }
6552 }
6553 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6554 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6555 format = kSdpFormatReceivedComplexUnifiedPlan;
6556 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6557 format = kSdpFormatReceivedComplexPlanB;
6558 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6559 format = kSdpFormatReceivedSimple;
6560 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006561 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6562 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006563}
6564
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006565void PeerConnection::NoteUsageEvent(UsageEvent event) {
6566 RTC_DCHECK_RUN_ON(signaling_thread());
6567 usage_event_accumulator_ |= static_cast<int>(event);
6568}
6569
6570void PeerConnection::ReportUsagePattern() const {
6571 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006572 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6573 usage_event_accumulator_,
6574 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006575 const int bad_bits =
6576 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6577 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6578 const int good_bits =
6579 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6580 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6581 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6582 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6583 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006584 // If called after close(), we can't report, because observer may have
6585 // been deallocated, and therefore pointer is null. Write to log instead.
6586 if (observer_) {
6587 Observer()->OnInterestingUsage(usage_event_accumulator_);
6588 } else {
6589 RTC_LOG(LS_INFO) << "Interesting usage signature "
6590 << usage_event_accumulator_
6591 << " observed after observer shutdown";
6592 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006593 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006594}
6595
Steve Anton0ffaaa22018-02-23 10:31:30 -08006596void PeerConnection::ReportNegotiatedSdpSemantics(
6597 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006598 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006599 switch (answer.description()->msid_signaling()) {
6600 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006601 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006602 break;
6603 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006604 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006605 break;
6606 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006607 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006608 break;
6609 case cricket::kMsidSignalingMediaSection |
6610 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006611 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006612 break;
6613 default:
6614 RTC_NOTREACHED();
6615 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006616 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6617 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006618}
6619
Steve Anton75737c02017-11-06 10:37:17 -08006620// We need to check the local/remote description for the Transport instead of
6621// the session, because a new Transport added during renegotiation may have
6622// them unset while the session has them set from the previous negotiation.
6623// Not doing so may trigger the auto generation of transport description and
6624// mess up DTLS identity information, ICE credential, etc.
6625bool PeerConnection::ReadyToUseRemoteCandidate(
6626 const IceCandidateInterface* candidate,
6627 const SessionDescriptionInterface* remote_desc,
6628 bool* valid) {
6629 *valid = true;
6630
6631 const SessionDescriptionInterface* current_remote_desc =
6632 remote_desc ? remote_desc : remote_description();
6633
6634 if (!current_remote_desc) {
6635 return false;
6636 }
6637
6638 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6639 size_t remote_content_size =
6640 current_remote_desc->description()->contents().size();
6641 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006642 RTC_LOG(LS_ERROR)
6643 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6644 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006645
6646 *valid = false;
6647 return false;
6648 }
6649
6650 cricket::ContentInfo content =
6651 current_remote_desc->description()->contents()[mediacontent_index];
6652
6653 const std::string transport_name = GetTransportName(content.name);
6654 if (transport_name.empty()) {
6655 return false;
6656 }
Zhi Huange830e682018-03-30 10:48:35 -07006657 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006658}
6659
6660bool PeerConnection::SrtpRequired() const {
6661 return dtls_enabled_ ||
6662 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6663}
6664
6665void PeerConnection::OnTransportControllerGatheringState(
6666 cricket::IceGatheringState state) {
6667 RTC_DCHECK(signaling_thread()->IsCurrent());
6668 if (state == cricket::kIceGatheringGathering) {
6669 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6670 } else if (state == cricket::kIceGatheringComplete) {
6671 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6672 }
6673}
6674
6675void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006676 std::map<std::string, std::set<cricket::MediaType>>
6677 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006678 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006679 if (transceiver->internal()->channel()) {
6680 const std::string& transport_name =
6681 transceiver->internal()->channel()->transport_name();
6682 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006683 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006684 }
Steve Anton75737c02017-11-06 10:37:17 -08006685 }
6686 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006687 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6688 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006689 }
Zhi Huange830e682018-03-30 10:48:35 -07006690
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006691 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006692 if (transport_name) {
6693 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006694 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006695 }
Zhi Huange830e682018-03-30 10:48:35 -07006696
Steve Antonc7b964c2018-02-01 14:39:45 -08006697 for (const auto& entry : media_types_by_transport_name) {
6698 const std::string& transport_name = entry.first;
6699 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006700 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006701 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006702 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006703 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006704 }
6705 }
6706}
6707// Walk through the ConnectionInfos to gather best connection usage
6708// for IPv4 and IPv6.
6709void PeerConnection::ReportBestConnectionState(
6710 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006711 for (const cricket::TransportChannelStats& channel_stats :
6712 stats.channel_stats) {
6713 for (const cricket::ConnectionInfo& connection_info :
6714 channel_stats.connection_infos) {
6715 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006716 continue;
6717 }
6718
Steve Antonc7b964c2018-02-01 14:39:45 -08006719 const cricket::Candidate& local = connection_info.local_candidate;
6720 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006721
6722 // Increment the counter for IceCandidatePairType.
6723 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6724 (local.type() == RELAY_PORT_TYPE &&
6725 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006726 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6727 GetIceCandidatePairCounter(local, remote),
6728 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006729 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006730 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6731 GetIceCandidatePairCounter(local, remote),
6732 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006733 } else {
6734 RTC_CHECK(0);
6735 }
Steve Anton75737c02017-11-06 10:37:17 -08006736
6737 // Increment the counter for IP type.
6738 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006739 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6740 kBestConnections_IPv4,
6741 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006742 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006743 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6744 kBestConnections_IPv6,
6745 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006746 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006747 RTC_CHECK(!local.address().hostname().empty() &&
6748 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006749 }
6750
6751 return;
6752 }
6753 }
6754}
6755
6756void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006757 const cricket::TransportStats& stats,
6758 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006759 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6760 return;
6761 }
6762
6763 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6764 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6765 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6766 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6767 return;
6768 }
6769
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006770 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6771 for (cricket::MediaType media_type : media_types) {
6772 switch (media_type) {
6773 case cricket::MEDIA_TYPE_AUDIO:
6774 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6775 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6776 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6777 break;
6778 case cricket::MEDIA_TYPE_VIDEO:
6779 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6780 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6781 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6782 break;
6783 case cricket::MEDIA_TYPE_DATA:
6784 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6785 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6786 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6787 break;
6788 default:
6789 RTC_NOTREACHED();
6790 continue;
6791 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006792 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006793 }
6794
6795 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6796 for (cricket::MediaType media_type : media_types) {
6797 switch (media_type) {
6798 case cricket::MEDIA_TYPE_AUDIO:
6799 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6800 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6801 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6802 break;
6803 case cricket::MEDIA_TYPE_VIDEO:
6804 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6805 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6806 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6807 break;
6808 case cricket::MEDIA_TYPE_DATA:
6809 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6810 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6811 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6812 break;
6813 default:
6814 RTC_NOTREACHED();
6815 continue;
6816 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006817 }
Steve Anton75737c02017-11-06 10:37:17 -08006818 }
6819}
6820
6821void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6822 RTC_DCHECK(worker_thread()->IsCurrent());
6823 RTC_DCHECK(call_);
6824 call_->OnSentPacket(sent_packet);
6825}
6826
6827const std::string PeerConnection::GetTransportName(
6828 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006829 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006830 if (channel) {
6831 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006832 }
Steve Anton6fec8802017-12-04 10:37:29 -08006833 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006834 RTC_DCHECK(sctp_mid_);
6835 if (content_name == *sctp_mid_) {
6836 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006837 }
6838 }
6839 // Return an empty string if failed to retrieve the transport name.
6840 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006841}
6842
Steve Anton6fec8802017-12-04 10:37:29 -08006843void PeerConnection::DestroyTransceiverChannel(
6844 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6845 transceiver) {
6846 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006847
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006848 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006849 if (channel) {
6850 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006851 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006852 }
6853}
6854
6855void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006856 if (rtp_data_channel_) {
6857 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006858 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006859 rtp_data_channel_ = nullptr;
6860 }
6861
6862 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6863 // grab a reference to this PeerConnection. If this is called from the
6864 // PeerConnection destructor, the RefCountedObject vtable will have already
6865 // been destroyed (since it is a subclass of PeerConnection) and using
6866 // rtc::Bind will cause "Pure virtual function called" error to appear.
6867
6868 if (sctp_transport_) {
6869 OnDataChannelDestroyed();
6870 network_thread()->Invoke<void>(RTC_FROM_HERE,
6871 [this] { DestroySctpTransport_n(); });
6872 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006873
6874 if (media_transport_) {
6875 OnDataChannelDestroyed();
6876 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6877 RTC_DCHECK_RUN_ON(network_thread());
6878 TeardownMediaTransportForDataChannels_n();
6879 });
6880 }
Steve Anton6fec8802017-12-04 10:37:29 -08006881}
6882
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006883void PeerConnection::DestroyChannelInterface(
6884 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006885 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006886 switch (channel->media_type()) {
6887 case cricket::MEDIA_TYPE_AUDIO:
6888 channel_manager()->DestroyVoiceChannel(
6889 static_cast<cricket::VoiceChannel*>(channel));
6890 break;
6891 case cricket::MEDIA_TYPE_VIDEO:
6892 channel_manager()->DestroyVideoChannel(
6893 static_cast<cricket::VideoChannel*>(channel));
6894 break;
6895 case cricket::MEDIA_TYPE_DATA:
6896 channel_manager()->DestroyRtpDataChannel(
6897 static_cast<cricket::RtpDataChannel*>(channel));
6898 break;
6899 default:
6900 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6901 break;
6902 }
Zhi Huange830e682018-03-30 10:48:35 -07006903}
Steve Anton6fec8802017-12-04 10:37:29 -08006904
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006905bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006906 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006907 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006908 cricket::DtlsTransportInternal* dtls_transport,
6909 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006910 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006911 auto base_channel = GetChannel(mid);
6912 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006913 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006914 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006915 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006916 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006917 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006918
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006919 if (configuration_.use_media_transport) {
6920 // Only pass media transport to call object if media transport is used
6921 // for media (and not data channel).
6922 call_->MediaTransportChange(media_transport);
6923 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006924
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006925 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006926}
6927
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006928PeerConnectionObserver* PeerConnection::Observer() const {
6929 // In earlier production code, the pointer was not cleared on close,
6930 // which might have led to undefined behavior if the observer was not
6931 // deallocated, or strange crashes if it was.
6932 // We use CHECK in order to catch such behavior if it exists.
6933 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6934 RTC_CHECK(observer_);
6935 return observer_;
6936}
6937
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006938CryptoOptions PeerConnection::GetCryptoOptions() {
6939 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6940 // after it has been removed.
6941 return configuration_.crypto_options.has_value()
6942 ? *configuration_.crypto_options
6943 : factory_->options().crypto_options;
6944}
6945
Harald Alvestrand89061872018-01-02 14:08:34 +01006946void PeerConnection::ClearStatsCache() {
6947 if (stats_collector_) {
6948 stats_collector_->ClearCachedStatsReport();
6949 }
6950}
6951
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006952void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006953 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6954 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006955}
6956
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006957} // namespace webrtc