blob: e205953aaabb9040bea8ea1b3afa88cbb976cb4a [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
23#include "api/mediaconstraintsinterface.h"
24#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
26#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
Steve Anton75737c02017-11-06 10:37:17 -080056using cricket::ContentInfo;
57using cricket::ContentInfos;
58using cricket::MediaContentDescription;
59using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080060using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::TransportInfo;
62
63using cricket::LOCAL_PORT_TYPE;
64using cricket::STUN_PORT_TYPE;
65using cricket::RELAY_PORT_TYPE;
66using cricket::PRFLX_PORT_TYPE;
67
Steve Antonba818672017-11-06 10:21:57 -080068namespace webrtc {
69
Steve Anton75737c02017-11-06 10:37:17 -080070// Error messages
71const char kBundleWithoutRtcpMux[] =
72 "rtcp-mux must be enabled when BUNDLE "
73 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080074const char kInvalidCandidates[] = "Description contains invalid candidates.";
75const char kInvalidSdp[] = "Invalid session description.";
76const char kMlineMismatchInAnswer[] =
77 "The order of m-lines in answer doesn't match order in offer. Rejecting "
78 "answer.";
79const char kMlineMismatchInSubsequentOffer[] =
80 "The order of m-lines in subsequent offer doesn't match order from "
81 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080082const char kSdpWithoutDtlsFingerprint[] =
83 "Called with SDP without DTLS fingerprint.";
84const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
85const char kSdpWithoutIceUfragPwd[] =
86 "Called with SDP without ice-ufrag and ice-pwd.";
87const char kSessionError[] = "Session error code: ";
88const char kSessionErrorDesc[] = "Session error description: ";
89const char kDtlsSrtpSetupFailureRtp[] =
90 "Couldn't set up DTLS-SRTP on RTP channel.";
91const char kDtlsSrtpSetupFailureRtcp[] =
92 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
Harald Alvestrand19793842018-06-25 12:03:50 +0200109 MSG_REPORT_USAGE_PATTERN,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110};
111
Harald Alvestrand19793842018-06-25 12:03:50 +0200112static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
113
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000114struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115 explicit SetSessionDescriptionMsg(
116 webrtc::SetSessionDescriptionObserver* observer)
Yves Gerey665174f2018-06-19 15:03:05 +0200117 : observer(observer) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000119 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100120 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000121};
122
deadbeefab9b2d12015-10-14 11:33:11 -0700123struct CreateSessionDescriptionMsg : public rtc::MessageData {
124 explicit CreateSessionDescriptionMsg(
125 webrtc::CreateSessionDescriptionObserver* observer)
126 : observer(observer) {}
127
128 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100129 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700130};
131
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000133 GetStatsMsg(webrtc::StatsObserver* observer,
134 webrtc::MediaStreamTrackInterface* track)
Yves Gerey665174f2018-06-19 15:03:05 +0200135 : observer(observer), track(track) {}
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000136 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000137 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000138};
139
deadbeefab9b2d12015-10-14 11:33:11 -0700140// Check if we can send |new_stream| on a PeerConnection.
141bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
142 webrtc::MediaStreamInterface* new_stream) {
143 if (!new_stream || !current_streams) {
144 return false;
145 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700146 if (current_streams->find(new_stream->id()) != nullptr) {
147 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100148 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700149 return false;
150 }
151 return true;
152}
153
deadbeef5e97fb52015-10-15 12:49:08 -0700154// If the direction is "recvonly" or "inactive", treat the description
155// as containing no streams.
156// See: https://code.google.com/p/webrtc/issues/detail?id=5054
157std::vector<cricket::StreamParams> GetActiveStreams(
158 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800159 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700160 ? desc->streams()
161 : std::vector<cricket::StreamParams>();
162}
163
deadbeefab9b2d12015-10-14 11:33:11 -0700164bool IsValidOfferToReceiveMedia(int value) {
165 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
166 return (value >= Options::kUndefined) &&
167 (value <= Options::kMaxOfferToReceiveMedia);
168}
169
zhihuang1c378ed2017-08-17 14:10:50 -0700170// Add options to |[audio/video]_media_description_options| from |senders|.
171void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700172 const std::vector<rtc::scoped_refptr<
173 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700174 cricket::MediaDescriptionOptions* audio_media_description_options,
175 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700176 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700177 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
178 if (audio_media_description_options) {
179 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700180 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700181 }
182 } else {
183 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
184 if (video_media_description_options) {
185 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700186 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700187 }
188 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700189 }
zhihuang1c378ed2017-08-17 14:10:50 -0700190}
olka3c747662017-08-17 06:50:32 -0700191
zhihuang1c378ed2017-08-17 14:10:50 -0700192// Add options to |session_options| from |rtp_data_channels|.
193void AddRtpDataChannelOptions(
194 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
195 rtp_data_channels,
196 cricket::MediaDescriptionOptions* data_media_description_options) {
197 if (!data_media_description_options) {
198 return;
199 }
deadbeefab9b2d12015-10-14 11:33:11 -0700200 // Check for data channels.
201 for (const auto& kv : rtp_data_channels) {
202 const DataChannel* channel = kv.second;
203 if (channel->state() == DataChannel::kConnecting ||
204 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700205 // Legacy RTP data channels are signaled with the track/stream ID set to
206 // the data channel's label.
207 data_media_description_options->AddRtpDataChannel(channel->label(),
208 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700209 }
210 }
211}
212
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700213uint32_t ConvertIceTransportTypeToCandidateFilter(
214 PeerConnectionInterface::IceTransportsType type) {
215 switch (type) {
216 case PeerConnectionInterface::kNone:
217 return cricket::CF_NONE;
218 case PeerConnectionInterface::kRelay:
219 return cricket::CF_RELAY;
220 case PeerConnectionInterface::kNoHost:
221 return (cricket::CF_ALL & ~cricket::CF_HOST);
222 case PeerConnectionInterface::kAll:
223 return cricket::CF_ALL;
224 default:
nissec80e7412017-01-11 05:56:46 -0800225 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700226 }
227 return cricket::CF_NONE;
228}
229
deadbeef293e9262017-01-11 12:28:30 -0800230// Helper to set an error and return from a method.
231bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
232 if (error) {
233 error->set_type(type);
234 }
235 return type == webrtc::RTCErrorType::NONE;
236}
237
Steve Anton038834f2017-07-14 15:59:59 -0700238bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
239 if (error_out) {
240 *error_out = std::move(error);
241 }
242 return error.ok();
243}
244
Steve Antonba818672017-11-06 10:21:57 -0800245std::string GetSignalingStateString(
246 PeerConnectionInterface::SignalingState state) {
247 switch (state) {
248 case PeerConnectionInterface::kStable:
249 return "kStable";
250 case PeerConnectionInterface::kHaveLocalOffer:
251 return "kHaveLocalOffer";
252 case PeerConnectionInterface::kHaveLocalPrAnswer:
253 return "kHavePrAnswer";
254 case PeerConnectionInterface::kHaveRemoteOffer:
255 return "kHaveRemoteOffer";
256 case PeerConnectionInterface::kHaveRemotePrAnswer:
257 return "kHaveRemotePrAnswer";
258 case PeerConnectionInterface::kClosed:
259 return "kClosed";
260 }
261 RTC_NOTREACHED();
262 return "";
263}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700264
Steve Anton75737c02017-11-06 10:37:17 -0800265IceCandidatePairType GetIceCandidatePairCounter(
266 const cricket::Candidate& local,
267 const cricket::Candidate& remote) {
268 const auto& l = local.type();
269 const auto& r = remote.type();
270 const auto& host = LOCAL_PORT_TYPE;
271 const auto& srflx = STUN_PORT_TYPE;
272 const auto& relay = RELAY_PORT_TYPE;
273 const auto& prflx = PRFLX_PORT_TYPE;
274 if (l == host && r == host) {
275 bool local_private = IPIsPrivate(local.address().ipaddr());
276 bool remote_private = IPIsPrivate(remote.address().ipaddr());
277 if (local_private) {
278 if (remote_private) {
279 return kIceCandidatePairHostPrivateHostPrivate;
280 } else {
281 return kIceCandidatePairHostPrivateHostPublic;
282 }
283 } else {
284 if (remote_private) {
285 return kIceCandidatePairHostPublicHostPrivate;
286 } else {
287 return kIceCandidatePairHostPublicHostPublic;
288 }
289 }
290 }
291 if (l == host && r == srflx)
292 return kIceCandidatePairHostSrflx;
293 if (l == host && r == relay)
294 return kIceCandidatePairHostRelay;
295 if (l == host && r == prflx)
296 return kIceCandidatePairHostPrflx;
297 if (l == srflx && r == host)
298 return kIceCandidatePairSrflxHost;
299 if (l == srflx && r == srflx)
300 return kIceCandidatePairSrflxSrflx;
301 if (l == srflx && r == relay)
302 return kIceCandidatePairSrflxRelay;
303 if (l == srflx && r == prflx)
304 return kIceCandidatePairSrflxPrflx;
305 if (l == relay && r == host)
306 return kIceCandidatePairRelayHost;
307 if (l == relay && r == srflx)
308 return kIceCandidatePairRelaySrflx;
309 if (l == relay && r == relay)
310 return kIceCandidatePairRelayRelay;
311 if (l == relay && r == prflx)
312 return kIceCandidatePairRelayPrflx;
313 if (l == prflx && r == host)
314 return kIceCandidatePairPrflxHost;
315 if (l == prflx && r == srflx)
316 return kIceCandidatePairPrflxSrflx;
317 if (l == prflx && r == relay)
318 return kIceCandidatePairPrflxRelay;
319 return kIceCandidatePairMax;
320}
321
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800322// Logic to decide if an m= section can be recycled. This means that the new
323// m= section is not rejected, but the old local or remote m= section is
324// rejected. |old_content_one| and |old_content_two| refer to the m= section
325// of the old remote and old local descriptions in no particular order.
326// We need to check both the old local and remote because either
327// could be the most current from the latest negotation.
328bool IsMediaSectionBeingRecycled(SdpType type,
329 const ContentInfo& content,
330 const ContentInfo* old_content_one,
331 const ContentInfo* old_content_two) {
332 return type == SdpType::kOffer && !content.rejected &&
333 ((old_content_one && old_content_one->rejected) ||
334 (old_content_two && old_content_two->rejected));
335}
336
Steve Anton75737c02017-11-06 10:37:17 -0800337// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800338// |current_desc|. The number of m= sections in |new_desc| should be no
339// less than |current_desc|. In the case of checking an answer's
340// |new_desc|, the |current_desc| is the last offer that was set as the
341// local or remote. In the case of checking an offer's |new_desc| we
342// check against the local and remote descriptions stored from the last
343// negotiation, because either of these could be the most up to date for
344// possible rejected m sections. These are the |current_desc| and
345// |secondary_current_desc|.
346bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
347 const SessionDescription* secondary_current_desc,
348 const SessionDescription& new_desc,
349 const SdpType type) {
350 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800351 return false;
352 }
353
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800354 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
355 const cricket::ContentInfo* secondary_content_info = nullptr;
356 if (secondary_current_desc &&
357 i < secondary_current_desc->contents().size()) {
358 secondary_content_info = &secondary_current_desc->contents()[i];
359 }
360 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
361 &current_desc.contents()[i],
362 secondary_content_info)) {
363 // For new offer descriptions, if the media section can be recycled, it's
364 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800365 continue;
366 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800367 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800368 return false;
369 }
370 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800371 new_desc.contents()[i].media_description();
372 const MediaContentDescription* current_desc_mdesc =
373 current_desc.contents()[i].media_description();
374 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800375 return false;
376 }
377 }
378 return true;
379}
380
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800381bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
382 const SessionDescription& desc2) {
383 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800384}
385
Qingsi Wang78fef762018-07-11 18:33:52 +0000386void NoteKeyProtocolAndMedia(
387 KeyExchangeProtocolType protocol_type,
388 cricket::MediaType media_type,
389 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
390 if (!uma_observer)
391 return;
392 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
393 protocol_type,
394 webrtc::kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100395 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
396 KeyExchangeProtocolMedia>
397 proto_media_counter_map = {
398 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
399 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
400 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
401 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
402 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
403 kEnumCounterKeyProtocolMediaTypeDtlsData},
404 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
405 kEnumCounterKeyProtocolMediaTypeSdesAudio},
406 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
407 kEnumCounterKeyProtocolMediaTypeSdesVideo},
408 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
409 kEnumCounterKeyProtocolMediaTypeSdesData}};
410
411 auto it = proto_media_counter_map.find({protocol_type, media_type});
412 if (it != proto_media_counter_map.end()) {
Qingsi Wang78fef762018-07-11 18:33:52 +0000413 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
414 it->second,
415 kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100416 }
417}
418
Steve Anton75737c02017-11-06 10:37:17 -0800419// Checks that each non-rejected content has SDES crypto keys or a DTLS
420// fingerprint, unless it's in a BUNDLE group, in which case only the
421// BUNDLE-tag section (first media section/description in the BUNDLE group)
422// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
423// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
424// by Channel's |srtp_required| check.
Qingsi Wang78fef762018-07-11 18:33:52 +0000425RTCError VerifyCrypto(const SessionDescription* desc,
426 bool dtls_enabled,
427 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800428 const cricket::ContentGroup* bundle =
429 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800430 for (const cricket::ContentInfo& content_info : desc->contents()) {
431 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800432 continue;
433 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100434 // Note what media is used with each crypto protocol, for all sections.
435 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
436 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang78fef762018-07-11 18:33:52 +0000437 content_info.media_description()->type(),
438 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800439 const std::string& mid = content_info.name;
440 if (bundle && bundle->HasContentName(mid) &&
441 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800442 // This isn't the first media section in the BUNDLE group, so it's not
443 // required to have crypto attributes, since only the crypto attributes
444 // from the first section actually get used.
445 continue;
446 }
447
448 // If the content isn't rejected or bundled into another m= section, crypto
449 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800450 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800451 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800452 if (!media || !tinfo) {
453 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800455 }
456 if (dtls_enabled) {
457 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100458 RTC_LOG(LS_WARNING)
459 << "Session description must have DTLS fingerprint if "
460 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800461 return RTCError(RTCErrorType::INVALID_PARAMETER,
462 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800463 }
464 } else {
465 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100466 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800467 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800468 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800469 }
470 }
471 }
Steve Anton8a006912017-12-04 15:25:56 -0800472 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800473}
474
475// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
476// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
477// media section/description in the BUNDLE group) needs a ufrag and pwd.
478bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
479 const cricket::ContentGroup* bundle =
480 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800481 for (const cricket::ContentInfo& content_info : desc->contents()) {
482 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800483 continue;
484 }
Steve Anton8a006912017-12-04 15:25:56 -0800485 const std::string& mid = content_info.name;
486 if (bundle && bundle->HasContentName(mid) &&
487 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800488 // This isn't the first media section in the BUNDLE group, so it's not
489 // required to have ufrag/password, since only the ufrag/password from
490 // the first section actually get used.
491 continue;
492 }
493
494 // If the content isn't rejected or bundled into another m= section,
495 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800496 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800497 if (!tinfo) {
498 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100499 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800500 return false;
501 }
502 if (tinfo->description.ice_ufrag.empty() ||
503 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100504 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800505 return false;
506 }
507 }
508 return true;
509}
510
511bool GetTrackIdBySsrc(const SessionDescription* session_description,
512 uint32_t ssrc,
513 std::string* track_id) {
514 RTC_DCHECK(track_id != NULL);
515
Steve Antonb1c1de12017-12-21 15:14:30 -0800516 const cricket::AudioContentDescription* audio_desc =
517 cricket::GetFirstAudioContentDescription(session_description);
518 if (audio_desc) {
519 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800520 if (found) {
521 *track_id = found->id;
522 return true;
523 }
524 }
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::VideoContentDescription* video_desc =
527 cricket::GetFirstVideoContentDescription(session_description);
528 if (video_desc) {
529 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535 return false;
536}
537
538// Get the SCTP port out of a SessionDescription.
539// Return -1 if not found.
540int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800541 const cricket::DataContentDescription* data_desc =
542 GetFirstDataContentDescription(session_description);
543 RTC_DCHECK(data_desc);
544 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800545 return -1;
546 }
Steve Anton75737c02017-11-06 10:37:17 -0800547 std::string value;
548 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
549 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800550 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800551 if (!codec.Matches(match_pattern)) {
552 continue;
553 }
554 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
555 return rtc::FromString<int>(value);
556 }
557 }
558 return -1;
559}
560
Steve Anton75737c02017-11-06 10:37:17 -0800561// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
562bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
563 const SessionDescriptionInterface* new_desc,
564 const std::string& content_name) {
565 if (!old_desc) {
566 return false;
567 }
568 const SessionDescription* new_sd = new_desc->description();
569 const SessionDescription* old_sd = old_desc->description();
570 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
571 if (!cinfo || cinfo->rejected) {
572 return false;
573 }
574 // If the content isn't rejected, check if ufrag and password has changed.
575 const cricket::TransportDescription* new_transport_desc =
576 new_sd->GetTransportDescriptionByName(content_name);
577 const cricket::TransportDescription* old_transport_desc =
578 old_sd->GetTransportDescriptionByName(content_name);
579 if (!new_transport_desc || !old_transport_desc) {
580 // No transport description exists. This is not an ICE restart.
581 return false;
582 }
583 if (cricket::IceCredentialsChanged(
584 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
585 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100586 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
587 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800588 return true;
589 }
590 return false;
591}
592
Steve Anton80dd7b52018-02-16 17:08:42 -0800593// Generates a string error message for SetLocalDescription/SetRemoteDescription
594// from an RTCError.
595std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
596 SdpType type,
597 const RTCError& error) {
598 std::ostringstream oss;
599 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
600 << " " << SdpTypeToString(type) << " sdp: " << error.message();
601 return oss.str();
602}
603
Seth Hampson5b4f0752018-04-02 16:31:36 -0700604std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
605 std::string output = "streams=[";
606 const char* separator = "";
607 for (const auto& stream_id : stream_ids) {
608 output.append(separator).append(stream_id);
609 separator = ", ";
610 }
611 output.append("]");
612 return output;
613}
614
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200615absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700616 int rtc_configuration_parameter) {
617 if (rtc_configuration_parameter ==
618 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200619 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700620 }
621 return rtc_configuration_parameter;
622}
623
Steve Anton75737c02017-11-06 10:37:17 -0800624} // namespace
625
Henrik Boström31638672017-11-23 17:48:32 +0100626// Upon completion, posts a task to execute the callback of the
627// SetSessionDescriptionObserver asynchronously on the same thread. At this
628// point, the state of the peer connection might no longer reflect the effects
629// of the SetRemoteDescription operation, as the peer connection could have been
630// modified during the post.
631// TODO(hbos): Remove this class once we remove the version of
632// PeerConnectionInterface::SetRemoteDescription() that takes a
633// SetSessionDescriptionObserver as an argument.
634class PeerConnection::SetRemoteDescriptionObserverAdapter
635 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
636 public:
637 SetRemoteDescriptionObserverAdapter(
638 rtc::scoped_refptr<PeerConnection> pc,
639 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
640 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
641
642 // SetRemoteDescriptionObserverInterface implementation.
643 void OnSetRemoteDescriptionComplete(RTCError error) override {
644 if (error.ok())
645 pc_->PostSetSessionDescriptionSuccess(wrapper_);
646 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100647 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100648 }
649
650 private:
651 rtc::scoped_refptr<PeerConnection> pc_;
652 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
653};
654
deadbeef293e9262017-01-11 12:28:30 -0800655bool PeerConnectionInterface::RTCConfiguration::operator==(
656 const PeerConnectionInterface::RTCConfiguration& o) const {
657 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800659 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000660 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700661 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800662 BundlePolicy bundle_policy;
663 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700664 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
665 int ice_candidate_pool_size;
666 bool disable_ipv6;
667 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700668 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100669 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700670 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200671 absl::optional<int> screencast_min_bitrate;
672 absl::optional<bool> combined_audio_video_bwe;
673 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800674 TcpCandidatePolicy tcp_candidate_policy;
675 CandidateNetworkPolicy candidate_network_policy;
676 int audio_jitter_buffer_max_packets;
677 bool audio_jitter_buffer_fast_accelerate;
678 int ice_connection_receiving_timeout;
679 int ice_backup_candidate_pair_ping_interval;
680 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800681 bool prioritize_most_likely_ice_candidate_pairs;
682 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800683 bool prune_turn_ports;
684 bool presume_writable_when_fully_relayed;
685 bool enable_ice_renomination;
686 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200687 absl::optional<int> ice_check_interval_strong_connectivity;
688 absl::optional<int> ice_check_interval_weak_connectivity;
689 absl::optional<int> ice_check_min_interval;
690 absl::optional<int> ice_unwritable_timeout;
691 absl::optional<int> ice_unwritable_min_checks;
692 absl::optional<int> stun_candidate_keepalive_interval;
693 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200694 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800695 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200696 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700697 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800698 };
699 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
700 "Did you add something to RTCConfiguration and forget to "
701 "update operator==?");
702 return type == o.type && servers == o.servers &&
703 bundle_policy == o.bundle_policy &&
704 rtcp_mux_policy == o.rtcp_mux_policy &&
705 tcp_candidate_policy == o.tcp_candidate_policy &&
706 candidate_network_policy == o.candidate_network_policy &&
707 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
708 audio_jitter_buffer_fast_accelerate ==
709 o.audio_jitter_buffer_fast_accelerate &&
710 ice_connection_receiving_timeout ==
711 o.ice_connection_receiving_timeout &&
712 ice_backup_candidate_pair_ping_interval ==
713 o.ice_backup_candidate_pair_ping_interval &&
714 continual_gathering_policy == o.continual_gathering_policy &&
715 certificates == o.certificates &&
716 prioritize_most_likely_ice_candidate_pairs ==
717 o.prioritize_most_likely_ice_candidate_pairs &&
718 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800719 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700720 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100721 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800722 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800723 screencast_min_bitrate == o.screencast_min_bitrate &&
724 combined_audio_video_bwe == o.combined_audio_video_bwe &&
725 enable_dtls_srtp == o.enable_dtls_srtp &&
726 ice_candidate_pool_size == o.ice_candidate_pool_size &&
727 prune_turn_ports == o.prune_turn_ports &&
728 presume_writable_when_fully_relayed ==
729 o.presume_writable_when_fully_relayed &&
730 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800731 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800732 ice_check_interval_strong_connectivity ==
733 o.ice_check_interval_strong_connectivity &&
734 ice_check_interval_weak_connectivity ==
735 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700736 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700737 ice_unwritable_timeout == o.ice_unwritable_timeout &&
738 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800739 stun_candidate_keepalive_interval ==
740 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200741 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800742 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800743 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700744 network_preference == o.network_preference &&
745 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800746}
747
748bool PeerConnectionInterface::RTCConfiguration::operator!=(
749 const PeerConnectionInterface::RTCConfiguration& o) const {
750 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800751}
752
zhihuang8f65cdf2016-05-06 18:40:30 -0700753// Generate a RTCP CNAME when a PeerConnection is created.
754std::string GenerateRtcpCname() {
755 std::string cname;
756 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100757 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800758 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700759 }
760 return cname;
761}
762
zhihuang1c378ed2017-08-17 14:10:50 -0700763bool ValidateOfferAnswerOptions(
764 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
765 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
766 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700767}
768
zhihuang1c378ed2017-08-17 14:10:50 -0700769// From |rtc_options|, fill parts of |session_options| shared by all generated
770// m= sections (in other words, nothing that involves a map/array).
771void ExtractSharedMediaSessionOptions(
772 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
773 cricket::MediaSessionOptions* session_options) {
774 session_options->vad_enabled = rtc_options.voice_activity_detection;
775 session_options->bundle_enabled = rtc_options.use_rtp_mux;
776}
zhihuanga77e6bb2017-08-14 18:17:48 -0700777
zhihuang1c378ed2017-08-17 14:10:50 -0700778bool ConvertConstraintsToOfferAnswerOptions(
779 const MediaConstraintsInterface* constraints,
780 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700781 if (!constraints) {
782 return true;
783 }
zhihuang1c378ed2017-08-17 14:10:50 -0700784
785 bool value = false;
786 size_t mandatory_constraints_satisfied = 0;
787
788 if (FindConstraint(constraints,
789 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
790 &mandatory_constraints_satisfied)) {
791 offer_answer_options->offer_to_receive_audio =
792 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
793 kOfferToReceiveMediaTrue
794 : 0;
795 }
796
797 if (FindConstraint(constraints,
798 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
799 &mandatory_constraints_satisfied)) {
800 offer_answer_options->offer_to_receive_video =
801 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
802 kOfferToReceiveMediaTrue
803 : 0;
804 }
805 if (FindConstraint(constraints,
806 MediaConstraintsInterface::kVoiceActivityDetection, &value,
807 &mandatory_constraints_satisfied)) {
808 offer_answer_options->voice_activity_detection = value;
809 }
810 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
811 &mandatory_constraints_satisfied)) {
812 offer_answer_options->use_rtp_mux = value;
813 }
814 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
815 &value, &mandatory_constraints_satisfied)) {
816 offer_answer_options->ice_restart = value;
817 }
818
deadbeefab9b2d12015-10-14 11:33:11 -0700819 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
820}
821
zhihuang38ede132017-06-15 12:52:32 -0700822PeerConnection::PeerConnection(PeerConnectionFactory* factory,
823 std::unique_ptr<RtcEventLog> event_log,
824 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700826 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700827 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700828 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700829 remote_streams_(StreamCollection::Create()),
830 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831
832PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100833 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800834 RTC_DCHECK_RUN_ON(signaling_thread());
835
Steve Anton8af21862017-12-15 11:20:13 -0800836 // Need to stop transceivers before destroying the stats collector because
837 // AudioRtpSender has a reference to the StatsCollector it will update when
838 // stopping.
839 for (auto transceiver : transceivers_) {
840 transceiver->Stop();
841 }
Steve Anton4171afb2017-11-20 10:20:22 -0800842
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700843 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800844 if (stats_collector_) {
845 stats_collector_->WaitForPendingRequest();
846 stats_collector_ = nullptr;
847 }
Steve Anton75737c02017-11-06 10:37:17 -0800848
Steve Anton8af21862017-12-15 11:20:13 -0800849 // Don't destroy BaseChannels until after stats has been cleaned up so that
850 // the last stats request can still read from the channels.
851 DestroyAllChannels();
852
Mirko Bonadei675513b2017-11-09 11:09:25 +0100853 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800854
855 webrtc_session_desc_factory_.reset();
856 sctp_invoker_.reset();
857 sctp_factory_.reset();
858 transport_controller_.reset();
859
deadbeef91dd5672016-05-18 16:55:30 -0700860 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700861 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700862 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700863 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700864 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700865 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800866 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700867 event_log_.reset();
868 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869}
870
Steve Anton8af21862017-12-15 11:20:13 -0800871void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800872 // Destroy video channels first since they may have a pointer to a voice
873 // channel.
874 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800875 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800876 DestroyTransceiverChannel(transceiver);
877 }
878 }
879 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800880 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800881 DestroyTransceiverChannel(transceiver);
882 }
883 }
884 DestroyDataChannel();
885}
886
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000888 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700889 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100890 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700891
892 RTCError config_error = ValidateConfiguration(configuration);
893 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100894 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700895 return false;
896 }
897
Benjamin Wrightcab58882018-05-02 15:12:47 -0700898 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100899 RTC_LOG(LS_ERROR)
900 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100901 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800902 return false;
903 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200904
Benjamin Wrightcab58882018-05-02 15:12:47 -0700905 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800906 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100908 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800909 return false;
910 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700911
Benjamin Wrightcab58882018-05-02 15:12:47 -0700912 observer_ = dependencies.observer;
913 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700914 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800915
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200916 cricket::ServerAddresses stun_servers;
917 std::vector<cricket::RelayServerConfig> turn_servers;
918
919 RTCErrorType parse_error =
920 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
921 if (parse_error != RTCErrorType::NONE) {
922 return false;
923 }
924
deadbeef91dd5672016-05-18 16:55:30 -0700925 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700926 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700927 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200928 RTC_FROM_HERE,
929 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
930 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 return false;
932 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200933 // If initialization was successful, note if STUN or TURN servers
934 // were supplied.
935 if (!stun_servers.empty()) {
936 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
937 }
938 if (!turn_servers.empty()) {
939 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
940 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941
Zhi Huange830e682018-03-30 10:48:35 -0700942 const PeerConnectionFactoryInterface::Options& options = factory_->options();
943
Steve Anton75737c02017-11-06 10:37:17 -0800944 // RFC 3264: The numeric value of the session id and version in the
945 // o line MUST be representable with a "64 bit signed integer".
946 // Due to this constraint session id |session_id_| is max limited to
947 // LLONG_MAX.
948 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700949 JsepTransportController::Config config;
950 config.redetermine_role_on_ice_restart =
951 configuration.redetermine_role_on_ice_restart;
952 config.ssl_max_version = factory_->options().ssl_max_version;
953 config.disable_encryption = options.disable_encryption;
954 config.bundle_policy = configuration.bundle_policy;
955 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
956 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700957 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700958 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700959#if defined(ENABLE_EXTERNAL_AUTH)
960 config.enable_external_auth = true;
961#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700962 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700963 transport_controller_.reset(new JsepTransportController(
964 signaling_thread(), network_thread(), port_allocator_.get(), config));
965 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800966 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700967 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800968 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700969 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800970 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700971 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800972 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
973 transport_controller_->SignalDtlsHandshakeError.connect(
974 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
975
976 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700977
deadbeefab9b2d12015-10-14 11:33:11 -0700978 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700979 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980
Steve Antonba818672017-11-06 10:21:57 -0800981 configuration_ = configuration;
982
Steve Anton75737c02017-11-06 10:37:17 -0800983 // Obtain a certificate from RTCConfiguration if any were provided (optional).
984 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
985 if (!configuration.certificates.empty()) {
986 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
987 // just picking the first one. The decision should be made based on the DTLS
988 // handshake. The DTLS negotiations need to know about all certificates.
989 certificate = configuration.certificates[0];
990 }
991
Steve Antond25da372017-11-06 14:50:29 -0800992 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800993
994 if (options.disable_encryption) {
995 dtls_enabled_ = false;
996 } else {
997 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700998 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800999 // |configuration| can override the default |dtls_enabled_| value.
1000 if (configuration.enable_dtls_srtp) {
1001 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1002 }
1003 }
1004
1005 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
1006 // It takes precendence over the disable_sctp_data_channels
1007 // PeerConnectionFactoryInterface::Options.
1008 if (configuration.enable_rtp_data_channel) {
1009 data_channel_type_ = cricket::DCT_RTP;
1010 } else {
1011 // DTLS has to be enabled to use SCTP.
1012 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1013 data_channel_type_ = cricket::DCT_SCTP;
1014 }
1015 }
1016
1017 video_options_.screencast_min_bitrate_kbps =
1018 configuration.screencast_min_bitrate;
1019 audio_options_.combined_audio_video_bwe =
1020 configuration.combined_audio_video_bwe;
1021
1022 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001023 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001024
1025 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001026 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001027
1028 // Whether the certificate generator/certificate is null or not determines
1029 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1030 // the right instructions by clearing the variables if needed.
1031 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001032 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001033 certificate = nullptr;
1034 } else if (certificate) {
1035 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001036 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001037 }
1038
1039 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1040 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001041 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001042 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1043 this, &PeerConnection::OnCertificateReady);
1044
1045 if (options.disable_encryption) {
1046 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1047 }
1048
1049 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1050 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051
Steve Anton4171afb2017-11-20 10:20:22 -08001052 // Add default audio/video transceivers for Plan B SDP.
1053 if (!IsUnifiedPlan()) {
1054 transceivers_.push_back(
1055 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1056 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1057 transceivers_.push_back(
1058 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1059 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1060 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001061 int delay_ms =
1062 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
1063 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1064 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065 return true;
1066}
1067
Steve Anton038834f2017-07-14 15:59:59 -07001068RTCError PeerConnection::ValidateConfiguration(
1069 const RTCConfiguration& config) const {
1070 if (config.ice_regather_interval_range &&
1071 config.continual_gathering_policy == GATHER_ONCE) {
1072 return RTCError(RTCErrorType::INVALID_PARAMETER,
1073 "ice_regather_interval_range specified but continual "
1074 "gathering policy is GATHER_ONCE");
1075 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001076 auto result =
1077 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1078 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001079}
1080
Yves Gerey665174f2018-06-19 15:03:05 +02001081rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001082 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1083 "Plan SdpSemantics. Please use GetSenders "
1084 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001085 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086}
1087
Yves Gerey665174f2018-06-19 15:03:05 +02001088rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001089 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1090 "Plan SdpSemantics. Please use GetReceivers "
1091 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001092 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093}
1094
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001095bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001096 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1097 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001098 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001099 if (IsClosed()) {
1100 return false;
1101 }
deadbeefab9b2d12015-10-14 11:33:11 -07001102 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001103 return false;
1104 }
deadbeefab9b2d12015-10-14 11:33:11 -07001105
1106 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001107 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1108 observer->SignalAudioTrackAdded.connect(this,
1109 &PeerConnection::OnAudioTrackAdded);
1110 observer->SignalAudioTrackRemoved.connect(
1111 this, &PeerConnection::OnAudioTrackRemoved);
1112 observer->SignalVideoTrackAdded.connect(this,
1113 &PeerConnection::OnVideoTrackAdded);
1114 observer->SignalVideoTrackRemoved.connect(
1115 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001116 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001117
deadbeefab9b2d12015-10-14 11:33:11 -07001118 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001119 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001120 }
1121 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001122 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001123 }
1124
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001125 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126 observer_->OnRenegotiationNeeded();
1127 return true;
1128}
1129
1130void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001131 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1132 "Plan SdpSemantics. Please use RemoveTrack "
1133 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001134 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001135 if (!IsClosed()) {
1136 for (const auto& track : local_stream->GetAudioTracks()) {
1137 RemoveAudioTrack(track.get(), local_stream);
1138 }
1139 for (const auto& track : local_stream->GetVideoTracks()) {
1140 RemoveVideoTrack(track.get(), local_stream);
1141 }
deadbeefab9b2d12015-10-14 11:33:11 -07001142 }
deadbeefab9b2d12015-10-14 11:33:11 -07001143 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001144 stream_observers_.erase(
1145 std::remove_if(
1146 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001147 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001148 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001149 }),
1150 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001151
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 if (IsClosed()) {
1153 return;
1154 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001155 observer_->OnRenegotiationNeeded();
1156}
1157
Steve Anton2d6c76a2018-01-05 17:10:52 -08001158RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001159 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001160 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001161 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001162 if (!track) {
1163 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1164 }
1165 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1166 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1167 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1168 "Track has invalid kind: " + track->kind());
1169 }
Steve Antonf9381f02017-12-14 10:23:57 -08001170 if (IsClosed()) {
1171 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1172 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001173 }
Steve Anton4171afb2017-11-20 10:20:22 -08001174 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001175 LOG_AND_RETURN_ERROR(
1176 RTCErrorType::INVALID_PARAMETER,
1177 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001178 }
Steve Antonf9381f02017-12-14 10:23:57 -08001179 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001180 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1181 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001182 if (sender_or_error.ok()) {
1183 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001184 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001185 }
1186 return sender_or_error;
1187}
deadbeefe1f9d832016-01-14 15:35:42 -08001188
Steve Antonf9381f02017-12-14 10:23:57 -08001189RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1190PeerConnection::AddTrackPlanB(
1191 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001192 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001193 if (stream_ids.size() > 1u) {
1194 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1195 "AddTrack with more than one stream is not "
1196 "supported with Plan B semantics.");
1197 }
1198 std::vector<std::string> adjusted_stream_ids = stream_ids;
1199 if (adjusted_stream_ids.empty()) {
1200 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1201 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001202 cricket::MediaType media_type =
1203 (track->kind() == MediaStreamTrackInterface::kAudioKind
1204 ? cricket::MEDIA_TYPE_AUDIO
1205 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001206 auto new_sender =
1207 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001208 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001209 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001210 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001211 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001212 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001213 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001214 if (sender_info) {
1215 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001216 }
Steve Antonf9381f02017-12-14 10:23:57 -08001217 } else {
1218 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001219 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001220 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001221 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001222 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001223 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001224 if (sender_info) {
1225 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001226 }
deadbeefe1f9d832016-01-14 15:35:42 -08001227 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001228 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001229}
deadbeefe1f9d832016-01-14 15:35:42 -08001230
Steve Antonf9381f02017-12-14 10:23:57 -08001231RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1232PeerConnection::AddTrackUnifiedPlan(
1233 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001234 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001235 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1236 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001237 RTC_LOG(LS_INFO) << "Reusing an existing "
1238 << cricket::MediaTypeToString(transceiver->media_type())
1239 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001240 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001241 transceiver->internal()->set_direction(
1242 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001243 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001244 transceiver->internal()->set_direction(
1245 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001246 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001247 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001248 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001249 } else {
1250 cricket::MediaType media_type =
1251 (track->kind() == MediaStreamTrackInterface::kAudioKind
1252 ? cricket::MEDIA_TYPE_AUDIO
1253 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001254 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1255 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001256 std::string sender_id = track->id();
1257 // Avoid creating a sender with an existing ID by generating a random ID.
1258 // This can happen if this is the second time AddTrack has created a sender
1259 // for this track.
1260 if (FindSenderById(sender_id)) {
1261 sender_id = rtc::CreateRandomUuid();
1262 }
1263 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001264 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1265 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001266 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001267 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001268 }
Steve Antonf9381f02017-12-14 10:23:57 -08001269 return transceiver->sender();
1270}
1271
1272rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1273PeerConnection::FindFirstTransceiverForAddedTrack(
1274 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1275 RTC_DCHECK(track);
1276 for (auto transceiver : transceivers_) {
1277 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001278 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001279 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001280 !transceiver->internal()->has_ever_been_used_to_send() &&
1281 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001282 return transceiver;
1283 }
1284 }
1285 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001286}
1287
1288bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1289 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001290 return RemoveTrackInternal(sender).ok();
1291}
1292
1293RTCError PeerConnection::RemoveTrackInternal(
1294 rtc::scoped_refptr<RtpSenderInterface> sender) {
1295 if (!sender) {
1296 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1297 }
deadbeefe1f9d832016-01-14 15:35:42 -08001298 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1300 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001301 }
Steve Antonf9381f02017-12-14 10:23:57 -08001302 if (IsUnifiedPlan()) {
1303 auto transceiver = FindTransceiverBySender(sender);
1304 if (!transceiver || !sender->track()) {
1305 return RTCError::OK();
1306 }
1307 sender->SetTrack(nullptr);
1308 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001309 transceiver->internal()->set_direction(
1310 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001311 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001312 transceiver->internal()->set_direction(
1313 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001314 }
Steve Anton4171afb2017-11-20 10:20:22 -08001315 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001316 bool removed;
1317 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1318 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1319 } else {
1320 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1321 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1322 }
1323 if (!removed) {
1324 LOG_AND_RETURN_ERROR(
1325 RTCErrorType::INVALID_PARAMETER,
1326 "Couldn't find sender " + sender->id() + " to remove.");
1327 }
Steve Anton4171afb2017-11-20 10:20:22 -08001328 }
deadbeefe1f9d832016-01-14 15:35:42 -08001329 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001330 return RTCError::OK();
1331}
1332
1333rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1334PeerConnection::FindTransceiverBySender(
1335 rtc::scoped_refptr<RtpSenderInterface> sender) {
1336 for (auto transceiver : transceivers_) {
1337 if (transceiver->sender() == sender) {
1338 return transceiver;
1339 }
1340 }
1341 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001342}
1343
Steve Anton9158ef62017-11-27 13:01:52 -08001344RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1345PeerConnection::AddTransceiver(
1346 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1347 return AddTransceiver(track, RtpTransceiverInit());
1348}
1349
1350RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1351PeerConnection::AddTransceiver(
1352 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1353 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001354 RTC_CHECK(IsUnifiedPlan())
1355 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001356 if (!track) {
1357 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1358 }
1359 cricket::MediaType media_type;
1360 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1361 media_type = cricket::MEDIA_TYPE_AUDIO;
1362 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1363 media_type = cricket::MEDIA_TYPE_VIDEO;
1364 } else {
1365 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1366 "Track kind is not audio or video");
1367 }
1368 return AddTransceiver(media_type, track, init);
1369}
1370
1371RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1372PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1373 return AddTransceiver(media_type, RtpTransceiverInit());
1374}
1375
1376RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1377PeerConnection::AddTransceiver(cricket::MediaType media_type,
1378 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001379 RTC_CHECK(IsUnifiedPlan())
1380 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001381 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1382 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1383 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1384 "media type is not audio or video");
1385 }
1386 return AddTransceiver(media_type, nullptr, init);
1387}
1388
1389RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1390PeerConnection::AddTransceiver(
1391 cricket::MediaType media_type,
1392 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001393 const RtpTransceiverInit& init,
1394 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001395 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1396 media_type == cricket::MEDIA_TYPE_VIDEO));
1397 if (track) {
1398 RTC_DCHECK_EQ(media_type,
1399 (track->kind() == MediaStreamTrackInterface::kAudioKind
1400 ? cricket::MEDIA_TYPE_AUDIO
1401 : cricket::MEDIA_TYPE_VIDEO));
1402 }
1403
1404 // TODO(bugs.webrtc.org/7600): Verify init.
1405
Steve Anton3d954a62018-04-02 11:27:23 -07001406 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1407 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001408 // Set the sender ID equal to the track ID if the track is specified unless
1409 // that sender ID is already in use.
1410 std::string sender_id =
1411 (track && !FindSenderById(track->id()) ? track->id()
1412 : rtc::CreateRandomUuid());
1413 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001414 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1415 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1416 transceiver->internal()->set_direction(init.direction);
1417
Steve Anton22da89f2018-01-25 13:58:07 -08001418 if (fire_callback) {
1419 observer_->OnRenegotiationNeeded();
1420 }
Steve Antonf9381f02017-12-14 10:23:57 -08001421
1422 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1423}
1424
Steve Anton02ee47c2018-01-10 16:26:06 -08001425rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1426PeerConnection::CreateSender(
1427 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001428 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001429 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001430 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001431 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001432 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1433 RTC_DCHECK(!track ||
1434 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1435 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1436 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001437 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001438 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001439 } else {
1440 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1441 RTC_DCHECK(!track ||
1442 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1443 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001444 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001445 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001446 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001447 bool set_track_succeeded = sender->SetTrack(track);
1448 RTC_DCHECK(set_track_succeeded);
1449 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001450 return sender;
1451}
1452
1453rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1454PeerConnection::CreateReceiver(cricket::MediaType media_type,
1455 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001456 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1457 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001458 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001459 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001460 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1461 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001462 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001463 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001464 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001465 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001466 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1467 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001468 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001469 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001470 return receiver;
1471}
1472
1473rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1474PeerConnection::CreateAndAddTransceiver(
1475 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1476 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1477 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001478 // Ensure that the new sender does not have an ID that is already in use by
1479 // another sender.
1480 // Allow receiver IDs to conflict since those come from remote SDP (which
1481 // could be invalid, but should not cause a crash).
1482 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001483 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1484 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001485 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001486 transceiver->internal()->SignalNegotiationNeeded.connect(
1487 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001488 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001489}
1490
Steve Anton52d86772018-02-20 15:48:12 -08001491void PeerConnection::OnNegotiationNeeded() {
1492 RTC_DCHECK_RUN_ON(signaling_thread());
1493 RTC_DCHECK(!IsClosed());
1494 observer_->OnRenegotiationNeeded();
1495}
1496
deadbeeffac06552015-11-25 11:26:01 -08001497rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001498 const std::string& kind,
1499 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001500 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1501 "Plan SdpSemantics. Please use AddTransceiver "
1502 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001503 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001504 if (IsClosed()) {
1505 return nullptr;
1506 }
Steve Anton4171afb2017-11-20 10:20:22 -08001507
Seth Hampson5b4f0752018-04-02 16:31:36 -07001508 // Internally we need to have one stream with Plan B semantics, so we
1509 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001510 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001511 if (stream_id.empty()) {
1512 stream_ids.push_back(rtc::CreateRandomUuid());
1513 RTC_LOG(LS_INFO)
1514 << "No stream_id specified for sender. Generated stream ID: "
1515 << stream_ids[0];
1516 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001517 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001518 }
1519
Steve Anton4171afb2017-11-20 10:20:22 -08001520 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001521 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001522 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001523 auto* audio_sender = new AudioRtpSender(
1524 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001525 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001526 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001527 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001528 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001529 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001530 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001531 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001532 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001533 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001534 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001535 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001536 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001537 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001538 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001539 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001540 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001541
deadbeefe1f9d832016-01-14 15:35:42 -08001542 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001543}
1544
deadbeef70ab1a12015-09-28 16:53:55 -07001545std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1546 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001547 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001548 for (auto sender : GetSendersInternal()) {
1549 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001550 }
1551 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001552}
1553
Steve Anton4171afb2017-11-20 10:20:22 -08001554std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1555PeerConnection::GetSendersInternal() const {
1556 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1557 all_senders;
1558 for (auto transceiver : transceivers_) {
1559 auto senders = transceiver->internal()->senders();
1560 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1561 }
1562 return all_senders;
1563}
1564
deadbeef70ab1a12015-09-28 16:53:55 -07001565std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1566PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001567 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001568 for (const auto& receiver : GetReceiversInternal()) {
1569 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001570 }
1571 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001572}
1573
Steve Anton4171afb2017-11-20 10:20:22 -08001574std::vector<
1575 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1576PeerConnection::GetReceiversInternal() const {
1577 std::vector<
1578 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1579 all_receivers;
1580 for (auto transceiver : transceivers_) {
1581 auto receivers = transceiver->internal()->receivers();
1582 all_receivers.insert(all_receivers.end(), receivers.begin(),
1583 receivers.end());
1584 }
1585 return all_receivers;
1586}
1587
Steve Anton9158ef62017-11-27 13:01:52 -08001588std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1589PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001590 RTC_CHECK(IsUnifiedPlan())
1591 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001592 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1593 for (auto transceiver : transceivers_) {
1594 all_transceivers.push_back(transceiver);
1595 }
1596 return all_transceivers;
1597}
1598
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001599bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001600 MediaStreamTrackInterface* track,
1601 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001602 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001603 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001604 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001605 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001606 return false;
1607 }
1608
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001609 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001610 // The StatsCollector is used to tell if a track is valid because it may
1611 // remember tracks that the PeerConnection previously removed.
1612 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001613 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1614 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001615 return false;
1616 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001617 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001618 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001619 return true;
1620}
1621
hbos74e1a4f2016-09-15 23:33:01 -07001622void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001623 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001624 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001625 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001626 stats_collector_->GetStatsReport(callback);
1627}
1628
Henrik Boström1df1bf82018-03-20 13:24:20 +01001629void PeerConnection::GetStats(
1630 rtc::scoped_refptr<RtpSenderInterface> selector,
1631 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1632 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1633 RTC_DCHECK(callback);
1634 RTC_DCHECK(stats_collector_);
1635 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1636 if (selector) {
1637 for (const auto& proxy_transceiver : transceivers_) {
1638 for (const auto& proxy_sender :
1639 proxy_transceiver->internal()->senders()) {
1640 if (proxy_sender == selector) {
1641 internal_sender = proxy_sender->internal();
1642 break;
1643 }
1644 }
1645 if (internal_sender)
1646 break;
1647 }
1648 }
1649 // If there is no |internal_sender| then |selector| is either null or does not
1650 // belong to the PeerConnection (in Plan B, senders can be removed from the
1651 // PeerConnection). This means that "all the stats objects representing the
1652 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1653 // produces an empty stats report.
1654 stats_collector_->GetStatsReport(internal_sender, callback);
1655}
1656
1657void PeerConnection::GetStats(
1658 rtc::scoped_refptr<RtpReceiverInterface> selector,
1659 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1660 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1661 RTC_DCHECK(callback);
1662 RTC_DCHECK(stats_collector_);
1663 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1664 if (selector) {
1665 for (const auto& proxy_transceiver : transceivers_) {
1666 for (const auto& proxy_receiver :
1667 proxy_transceiver->internal()->receivers()) {
1668 if (proxy_receiver == selector) {
1669 internal_receiver = proxy_receiver->internal();
1670 break;
1671 }
1672 }
1673 if (internal_receiver)
1674 break;
1675 }
1676 }
1677 // If there is no |internal_receiver| then |selector| is either null or does
1678 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1679 // the PeerConnection). This means that "all the stats objects representing
1680 // the selector" is an empty set. Invoking GetStatsReport() with a null
1681 // selector produces an empty stats report.
1682 stats_collector_->GetStatsReport(internal_receiver, callback);
1683}
1684
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001685PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1686 return signaling_state_;
1687}
1688
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001689PeerConnectionInterface::IceConnectionState
1690PeerConnection::ice_connection_state() {
1691 return ice_connection_state_;
1692}
1693
1694PeerConnectionInterface::IceGatheringState
1695PeerConnection::ice_gathering_state() {
1696 return ice_gathering_state_;
1697}
1698
Yves Gerey665174f2018-06-19 15:03:05 +02001699rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001700 const std::string& label,
1701 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001702 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001703
deadbeefab9b2d12015-10-14 11:33:11 -07001704 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001705
kwibergd1fe2812016-04-27 06:47:29 -07001706 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001707 if (config) {
1708 internal_config.reset(new InternalDataChannelInit(*config));
1709 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001710 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001711 InternalCreateDataChannel(label, internal_config.get()));
1712 if (!channel.get()) {
1713 return nullptr;
1714 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001715
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001716 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1717 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001718 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001719 observer_->OnRenegotiationNeeded();
1720 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001721 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722 return DataChannelProxy::Create(signaling_thread(), channel.get());
1723}
1724
1725void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1726 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001727 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001728
zhihuang1c378ed2017-08-17 14:10:50 -07001729 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1730 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1731 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1732 // compares the mandatory fields parsed with the mandatory fields added in the
1733 // |constraints| and some downstream applications might create offers with
1734 // mandatory fields which would not be parsed in the helper method. For
1735 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1736 // |constraints| as a mandatory field but it is not parsed.
1737 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001738
zhihuang1c378ed2017-08-17 14:10:50 -07001739 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001740}
1741
1742void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1743 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001744 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001745
nisse7ce109a2017-01-31 00:57:56 -08001746 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001747 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001748 return;
1749 }
deadbeefab9b2d12015-10-14 11:33:11 -07001750
Steve Anton8d3444d2017-10-20 15:30:51 -07001751 if (IsClosed()) {
1752 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001753 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001754 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001755 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001756 return;
1757 }
1758
zhihuang1c378ed2017-08-17 14:10:50 -07001759 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001760 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001761 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001762 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001763 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001764 return;
1765 }
1766
Steve Anton22da89f2018-01-25 13:58:07 -08001767 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1768 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1769 if (IsUnifiedPlan()) {
1770 RTCError error = HandleLegacyOfferOptions(options);
1771 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001772 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001773 return;
1774 }
1775 }
1776
zhihuang1c378ed2017-08-17 14:10:50 -07001777 cricket::MediaSessionOptions session_options;
1778 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001779 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001780}
1781
Steve Anton22da89f2018-01-25 13:58:07 -08001782RTCError PeerConnection::HandleLegacyOfferOptions(
1783 const RTCOfferAnswerOptions& options) {
1784 RTC_DCHECK(IsUnifiedPlan());
1785
1786 if (options.offer_to_receive_audio == 0) {
1787 RemoveRecvDirectionFromReceivingTransceiversOfType(
1788 cricket::MEDIA_TYPE_AUDIO);
1789 } else if (options.offer_to_receive_audio == 1) {
1790 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1791 } else if (options.offer_to_receive_audio > 1) {
1792 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1793 "offer_to_receive_audio > 1 is not supported.");
1794 }
1795
1796 if (options.offer_to_receive_video == 0) {
1797 RemoveRecvDirectionFromReceivingTransceiversOfType(
1798 cricket::MEDIA_TYPE_VIDEO);
1799 } else if (options.offer_to_receive_video == 1) {
1800 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1801 } else if (options.offer_to_receive_video > 1) {
1802 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1803 "offer_to_receive_video > 1 is not supported.");
1804 }
1805
1806 return RTCError::OK();
1807}
1808
1809void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1810 cricket::MediaType media_type) {
1811 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001812 RtpTransceiverDirection new_direction =
1813 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1814 if (new_direction != transceiver->direction()) {
1815 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1816 << " transceiver (MID="
1817 << transceiver->mid().value_or("<not set>") << ") from "
1818 << RtpTransceiverDirectionToString(
1819 transceiver->direction())
1820 << " to "
1821 << RtpTransceiverDirectionToString(new_direction)
1822 << " since CreateOffer specified offer_to_receive=0";
1823 transceiver->internal()->set_direction(new_direction);
1824 }
Steve Anton22da89f2018-01-25 13:58:07 -08001825 }
1826}
1827
1828void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1829 cricket::MediaType media_type) {
1830 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001831 RTC_LOG(LS_INFO)
1832 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1833 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001834 RtpTransceiverInit init;
1835 init.direction = RtpTransceiverDirection::kRecvOnly;
1836 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1837 }
1838}
1839
1840std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1841PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1842 std::vector<
1843 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1844 receiving_transceivers;
1845 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001846 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001847 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1848 receiving_transceivers.push_back(transceiver);
1849 }
1850 }
1851 return receiving_transceivers;
1852}
1853
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854void PeerConnection::CreateAnswer(
1855 CreateSessionDescriptionObserver* observer,
1856 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001857 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001858
nisse7ce109a2017-01-31 00:57:56 -08001859 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001860 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861 return;
1862 }
deadbeefab9b2d12015-10-14 11:33:11 -07001863
zhihuang1c378ed2017-08-17 14:10:50 -07001864 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1865 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1866 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001867 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001868 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001869 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001870 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001871 return;
1872 }
1873
Steve Anton8d3444d2017-10-20 15:30:51 -07001874 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001875}
1876
1877void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1878 const RTCOfferAnswerOptions& options) {
1879 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001880 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001881 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001882 return;
1883 }
1884
Steve Antondffead82018-02-06 10:31:29 -08001885 if (!(signaling_state_ == kHaveRemoteOffer ||
1886 signaling_state_ == kHaveLocalPrAnswer)) {
1887 std::string error =
1888 "PeerConnection cannot create an answer in a state other than "
1889 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001890 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001891 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001892 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001893 return;
1894 }
1895
Steve Antondffead82018-02-06 10:31:29 -08001896 // The remote description should be set if we're in the right state.
1897 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001898
Steve Anton22da89f2018-01-25 13:58:07 -08001899 if (IsUnifiedPlan()) {
1900 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1901 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1902 "supported with Unified Plan semantics. Use the "
1903 "RtpTransceiver API instead.";
1904 }
1905 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1906 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1907 "supported with Unified Plan semantics. Use the "
1908 "RtpTransceiver API instead.";
1909 }
1910 }
1911
htaa2a49d92016-03-04 02:51:39 -08001912 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001913 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001914
Steve Antond25da372017-11-06 14:50:29 -08001915 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001916}
1917
1918void PeerConnection::SetLocalDescription(
1919 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001920 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001921 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001922
Steve Anton80dd7b52018-02-16 17:08:42 -08001923 // The SetLocalDescription contract is that we take ownership of the session
1924 // description regardless of the outcome, so wrap it in a unique_ptr right
1925 // away. Ideally, SetLocalDescription's signature will be changed to take the
1926 // description as a unique_ptr argument to formalize this agreement.
1927 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1928
nisse7ce109a2017-01-31 00:57:56 -08001929 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001930 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931 return;
1932 }
Steve Anton8a006912017-12-04 15:25:56 -08001933
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001935 PostSetSessionDescriptionFailure(
1936 observer,
1937 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001938 return;
1939 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001940
Steve Anton80dd7b52018-02-16 17:08:42 -08001941 // If a session error has occurred the PeerConnection is in a possibly
1942 // inconsistent state so fail right away.
1943 if (session_error() != SessionError::kNone) {
1944 std::string error_message = GetSessionErrorMsg();
1945 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001946 PostSetSessionDescriptionFailure(
1947 observer,
1948 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001949 return;
1950 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001951
Steve Anton80dd7b52018-02-16 17:08:42 -08001952 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1953 if (!error.ok()) {
1954 std::string error_message = GetSetDescriptionErrorMessage(
1955 cricket::CS_LOCAL, desc->GetType(), error);
1956 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001957 PostSetSessionDescriptionFailure(
1958 observer,
1959 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001960 return;
1961 }
1962
1963 // Grab the description type before moving ownership to ApplyLocalDescription,
1964 // which may destroy it before returning.
1965 const SdpType type = desc->GetType();
1966
1967 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001968 // |desc| may be destroyed at this point.
1969
1970 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001971 // If ApplyLocalDescription fails, the PeerConnection could be in an
1972 // inconsistent state, so act conservatively here and set the session error
1973 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1974 SetSessionError(SessionError::kContent, error.message());
1975 std::string error_message =
1976 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1977 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001978 PostSetSessionDescriptionFailure(
1979 observer,
1980 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001981 return;
1982 }
Steve Anton8a006912017-12-04 15:25:56 -08001983 RTC_DCHECK(local_description());
1984
1985 PostSetSessionDescriptionSuccess(observer);
1986
Steve Anton8a006912017-12-04 15:25:56 -08001987 // MaybeStartGathering needs to be called after posting
1988 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1989 // before signaling that SetLocalDescription completed.
1990 transport_controller_->MaybeStartGathering();
1991
Steve Antona3a92c22017-12-07 10:27:41 -08001992 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001993 // TODO(deadbeef): We already had to hop to the network thread for
1994 // MaybeStartGathering...
1995 network_thread()->Invoke<void>(
1996 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1997 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001998 // Make UMA notes about what was agreed to.
1999 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002000 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002001 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002002}
2003
2004RTCError PeerConnection::ApplyLocalDescription(
2005 std::unique_ptr<SessionDescriptionInterface> desc) {
2006 RTC_DCHECK_RUN_ON(signaling_thread());
2007 RTC_DCHECK(desc);
2008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 // Update stats here so that we have the most recent stats for tracks and
2010 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002011 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002012
Steve Antondcc3c022017-12-22 16:02:54 -08002013 // Take a reference to the old local description since it's used below to
2014 // compare against the new local description. When setting the new local
2015 // description, grab ownership of the replaced session description in case it
2016 // is the same as |old_local_description|, to keep it alive for the duration
2017 // of the method.
2018 const SessionDescriptionInterface* old_local_description =
2019 local_description();
2020 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002021 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002022 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002023 replaced_local_description = pending_local_description_
2024 ? std::move(pending_local_description_)
2025 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002026 current_local_description_ = std::move(desc);
2027 pending_local_description_ = nullptr;
2028 current_remote_description_ = std::move(pending_remote_description_);
2029 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002030 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002031 pending_local_description_ = std::move(desc);
2032 }
2033 // The session description to apply now must be accessed by
2034 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002035 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002036
Zhi Huange830e682018-03-30 10:48:35 -07002037 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2038 if (!error.ok()) {
2039 return error;
2040 }
2041
Steve Antondcc3c022017-12-22 16:02:54 -08002042 if (IsUnifiedPlan()) {
2043 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002044 cricket::CS_LOCAL, *local_description(), old_local_description,
2045 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002046 if (!error.ok()) {
2047 return error;
2048 }
Steve Antondcc3c022017-12-22 16:02:54 -08002049 for (auto transceiver : transceivers_) {
2050 const ContentInfo* content =
2051 FindMediaSectionForTransceiver(transceiver, local_description());
2052 if (!content) {
2053 continue;
2054 }
2055 const MediaContentDescription* media_desc = content->media_description();
2056 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2057 transceiver->internal()->set_current_direction(media_desc->direction());
2058 }
2059 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002060 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2061 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002062 transceiver->Stop();
2063 }
2064 }
2065 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002066 // Media channels will be created only when offer is set. These may use new
2067 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002068 if (type == SdpType::kOffer) {
2069 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2070 // description is applied. Restore back to old description.
2071 RTCError error = CreateChannels(*local_description()->description());
2072 if (!error.ok()) {
2073 return error;
2074 }
2075 }
Steve Antondcc3c022017-12-22 16:02:54 -08002076 // Remove unused channels if MediaContentDescription is rejected.
2077 RemoveUnusedChannels(local_description()->description());
2078 }
Steve Anton8a006912017-12-04 15:25:56 -08002079
Zhi Huange830e682018-03-30 10:48:35 -07002080 error = UpdateSessionState(type, cricket::CS_LOCAL,
2081 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002082 if (!error.ok()) {
2083 return error;
2084 }
Steve Antondcc3c022017-12-22 16:02:54 -08002085
Steve Anton8a006912017-12-04 15:25:56 -08002086 if (remote_description()) {
2087 // Now that we have a local description, we can push down remote candidates.
2088 UseCandidatesInSessionDescription(remote_description());
2089 }
2090
2091 pending_ice_restarts_.clear();
2092 if (session_error() != SessionError::kNone) {
2093 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2094 }
2095
deadbeefab9b2d12015-10-14 11:33:11 -07002096 // If setting the description decided our SSL role, allocate any necessary
2097 // SCTP sids.
2098 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002099 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002100 AllocateSctpSids(role);
2101 }
2102
Steve Antond3679212018-01-17 17:41:02 -08002103 if (IsUnifiedPlan()) {
2104 for (auto transceiver : transceivers_) {
2105 const ContentInfo* content =
2106 FindMediaSectionForTransceiver(transceiver, local_description());
2107 if (!content) {
2108 continue;
2109 }
Steve Anton74255ff2018-01-24 18:32:57 -08002110 const auto& streams = content->media_description()->streams();
2111 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002112 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002113 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002114 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002115 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002116 } else {
2117 // 0 is a special value meaning "this sender has no associated send
2118 // stream". Need to call this so the sender won't attempt to configure
2119 // a no longer existing stream and run into DCHECKs in the lower
2120 // layers.
2121 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002122 }
2123 }
2124 } else {
2125 // Plan B semantics.
2126
Steve Antondcc3c022017-12-22 16:02:54 -08002127 // Update state and SSRC of local MediaStreams and DataChannels based on the
2128 // local session description.
2129 const cricket::ContentInfo* audio_content =
2130 GetFirstAudioContent(local_description()->description());
2131 if (audio_content) {
2132 if (audio_content->rejected) {
2133 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2134 } else {
2135 const cricket::AudioContentDescription* audio_desc =
2136 audio_content->media_description()->as_audio();
2137 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2138 }
deadbeeffaac4972015-11-12 15:33:07 -08002139 }
deadbeefab9b2d12015-10-14 11:33:11 -07002140
Steve Antondcc3c022017-12-22 16:02:54 -08002141 const cricket::ContentInfo* video_content =
2142 GetFirstVideoContent(local_description()->description());
2143 if (video_content) {
2144 if (video_content->rejected) {
2145 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2146 } else {
2147 const cricket::VideoContentDescription* video_desc =
2148 video_content->media_description()->as_video();
2149 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2150 }
deadbeeffaac4972015-11-12 15:33:07 -08002151 }
deadbeefab9b2d12015-10-14 11:33:11 -07002152 }
2153
2154 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002155 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002156 if (data_content) {
2157 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002158 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002159 if (rtc::starts_with(data_desc->protocol().data(),
2160 cricket::kMediaProtocolRtpPrefix)) {
2161 UpdateLocalRtpDataChannels(data_desc->streams());
2162 }
2163 }
2164
Steve Anton8a006912017-12-04 15:25:56 -08002165 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166}
2167
2168void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002169 SetSessionDescriptionObserver* observer,
2170 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002171 SetRemoteDescription(
2172 std::unique_ptr<SessionDescriptionInterface>(desc),
2173 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2174 new SetRemoteDescriptionObserverAdapter(this, observer)));
2175}
2176
2177void PeerConnection::SetRemoteDescription(
2178 std::unique_ptr<SessionDescriptionInterface> desc,
2179 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002180 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002181
nisse7ce109a2017-01-31 00:57:56 -08002182 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002183 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184 return;
2185 }
Steve Anton8a006912017-12-04 15:25:56 -08002186
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002188 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002189 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002190 return;
2191 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002192
Steve Anton80dd7b52018-02-16 17:08:42 -08002193 // If a session error has occurred the PeerConnection is in a possibly
2194 // inconsistent state so fail right away.
2195 if (session_error() != SessionError::kNone) {
2196 std::string error_message = GetSessionErrorMsg();
2197 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2198 observer->OnSetRemoteDescriptionComplete(
2199 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2200 return;
2201 }
Steve Anton71439a62018-02-15 11:53:06 -08002202
Steve Antonba42e992018-04-09 14:10:01 -07002203 if (desc->GetType() == SdpType::kOffer) {
2204 // Report to UMA the format of the received offer.
2205 ReportSdpFormatReceived(*desc);
2206 }
2207
Steve Anton80dd7b52018-02-16 17:08:42 -08002208 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002209 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002210 std::string error_message = GetSetDescriptionErrorMessage(
2211 cricket::CS_REMOTE, desc->GetType(), error);
2212 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002213 observer->OnSetRemoteDescriptionComplete(
2214 RTCError(error.type(), std::move(error_message)));
2215 return;
2216 }
Steve Anton71439a62018-02-15 11:53:06 -08002217
Steve Anton80dd7b52018-02-16 17:08:42 -08002218 // Grab the description type before moving ownership to
2219 // ApplyRemoteDescription, which may destroy it before returning.
2220 const SdpType type = desc->GetType();
2221
2222 error = ApplyRemoteDescription(std::move(desc));
2223 // |desc| may be destroyed at this point.
2224
2225 if (!error.ok()) {
2226 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2227 // inconsistent state, so act conservatively here and set the session error
2228 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2229 SetSessionError(SessionError::kContent, error.message());
2230 std::string error_message =
2231 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2232 RTC_LOG(LS_ERROR) << error_message;
2233 observer->OnSetRemoteDescriptionComplete(
2234 RTCError(error.type(), std::move(error_message)));
2235 return;
2236 }
2237 RTC_DCHECK(remote_description());
2238
2239 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002240 // TODO(deadbeef): We already had to hop to the network thread for
2241 // MaybeStartGathering...
2242 network_thread()->Invoke<void>(
2243 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2244 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002245 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002246 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002247 }
2248
2249 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002250 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002251}
2252
2253RTCError PeerConnection::ApplyRemoteDescription(
2254 std::unique_ptr<SessionDescriptionInterface> desc) {
2255 RTC_DCHECK_RUN_ON(signaling_thread());
2256 RTC_DCHECK(desc);
2257
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002258 // Update stats here so that we have the most recent stats for tracks and
2259 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002260 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002261
Steve Antondcc3c022017-12-22 16:02:54 -08002262 // Take a reference to the old remote description since it's used below to
2263 // compare against the new remote description. When setting the new remote
2264 // description, grab ownership of the replaced session description in case it
2265 // is the same as |old_remote_description|, to keep it alive for the duration
2266 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002267 const SessionDescriptionInterface* old_remote_description =
2268 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002269 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002270 SdpType type = desc->GetType();
2271 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002272 replaced_remote_description = pending_remote_description_
2273 ? std::move(pending_remote_description_)
2274 : std::move(current_remote_description_);
2275 current_remote_description_ = std::move(desc);
2276 pending_remote_description_ = nullptr;
2277 current_local_description_ = std::move(pending_local_description_);
2278 } else {
2279 replaced_remote_description = std::move(pending_remote_description_);
2280 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002281 }
Steve Anton8a006912017-12-04 15:25:56 -08002282 // The session description to apply now must be accessed by
2283 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002284 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002285
Zhi Huange830e682018-03-30 10:48:35 -07002286 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2287 if (!error.ok()) {
2288 return error;
2289 }
Steve Anton8a006912017-12-04 15:25:56 -08002290 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002291 if (IsUnifiedPlan()) {
2292 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002293 cricket::CS_REMOTE, *remote_description(), local_description(),
2294 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002295 if (!error.ok()) {
2296 return error;
2297 }
Steve Antondcc3c022017-12-22 16:02:54 -08002298 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002299 // Media channels will be created only when offer is set. These may use new
2300 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002301 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002302 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002303 // description is applied. Restore back to old description.
2304 RTCError error = CreateChannels(*remote_description()->description());
2305 if (!error.ok()) {
2306 return error;
2307 }
2308 }
Steve Antondcc3c022017-12-22 16:02:54 -08002309 // Remove unused channels if MediaContentDescription is rejected.
2310 RemoveUnusedChannels(remote_description()->description());
2311 }
Steve Anton8a006912017-12-04 15:25:56 -08002312
Zhi Huange830e682018-03-30 10:48:35 -07002313 // NOTE: Candidates allocation will be initiated only when
2314 // SetLocalDescription is called.
2315 error = UpdateSessionState(type, cricket::CS_REMOTE,
2316 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002317 if (!error.ok()) {
2318 return error;
2319 }
2320
2321 if (local_description() &&
2322 !UseCandidatesInSessionDescription(remote_description())) {
2323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2324 }
2325
2326 if (old_remote_description) {
2327 for (const cricket::ContentInfo& content :
2328 old_remote_description->description()->contents()) {
2329 // Check if this new SessionDescription contains new ICE ufrag and
2330 // password that indicates the remote peer requests an ICE restart.
2331 // TODO(deadbeef): When we start storing both the current and pending
2332 // remote description, this should reset pending_ice_restarts and compare
2333 // against the current description.
2334 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2335 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002336 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002337 pending_ice_restarts_.insert(content.name);
2338 }
2339 } else {
2340 // We retain all received candidates only if ICE is not restarted.
2341 // When ICE is restarted, all previous candidates belong to an old
2342 // generation and should not be kept.
2343 // TODO(deadbeef): This goes against the W3C spec which says the remote
2344 // description should only contain candidates from the last set remote
2345 // description plus any candidates added since then. We should remove
2346 // this once we're sure it won't break anything.
2347 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2348 old_remote_description, content.name, mutable_remote_description());
2349 }
2350 }
2351 }
2352
2353 if (session_error() != SessionError::kNone) {
2354 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2355 }
2356
2357 // Set the the ICE connection state to connecting since the connection may
2358 // become writable with peer reflexive candidates before any remote candidate
2359 // is signaled.
2360 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2361 // is to have a new signal the indicates a change in checking state from the
2362 // transport and expose a new checking() member from transport that can be
2363 // read to determine the current checking state. The existing SignalConnecting
2364 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002365 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002366 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002367 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2368 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2369 }
2370
deadbeefab9b2d12015-10-14 11:33:11 -07002371 // If setting the description decided our SSL role, allocate any necessary
2372 // SCTP sids.
2373 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002374 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002375 AllocateSctpSids(role);
2376 }
2377
Steve Antondcc3c022017-12-22 16:02:54 -08002378 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002379 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002380 now_receiving_transceivers;
2381 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2382 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002383 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002384 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002385 for (auto transceiver : transceivers_) {
2386 const ContentInfo* content =
2387 FindMediaSectionForTransceiver(transceiver, remote_description());
2388 if (!content) {
2389 continue;
2390 }
2391 const MediaContentDescription* media_desc = content->media_description();
2392 RtpTransceiverDirection local_direction =
2393 RtpTransceiverDirectionReversed(media_desc->direction());
2394 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2395 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2396 // transceiver's current direction is neither sendrecv nor recvonly,
2397 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002398 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002399 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002400 // The remote description has signaled the stream IDs.
2401 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002402 }
Steve Antondcc3c022017-12-22 16:02:54 -08002403 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2404 (!transceiver->current_direction() ||
2405 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002406 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002407 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002408 << content->name << " (added to "
2409 << GetStreamIdsString(stream_ids) << ").";
2410
2411 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2412 for (const std::string& stream_id : stream_ids) {
2413 rtc::scoped_refptr<MediaStreamInterface> stream =
2414 remote_streams_->find(stream_id);
2415 if (!stream) {
2416 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2417 MediaStream::Create(stream_id));
2418 remote_streams_->AddStream(stream);
2419 added_streams.push_back(stream);
2420 }
2421 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002422 }
Steve Anton3172c032018-05-03 15:30:18 -07002423 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002424 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2425 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002426 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002427 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002428 }
2429 // If direction is sendonly or inactive, and transceiver's current
2430 // direction is neither sendonly nor inactive, process the removal of a
2431 // remote track for the media description.
2432 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002433 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002434 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002435 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2436 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002437 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2438 transceiver->internal()->receiver_internal()->streams();
2439 // This will remove the remote track from the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002440 transceiver->internal()->receiver_internal()->set_stream_ids({});
Steve Anton3172c032018-05-03 15:30:18 -07002441 no_longer_receiving_transceivers.push_back(transceiver);
2442 // Remove any streams that no longer have tracks.
Henrik Boström199e27b2018-07-04 20:51:53 +02002443 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2444 // of streams, see if the stream was removed by checking if this was the
2445 // last receiver with that stream ID.
Steve Anton3172c032018-05-03 15:30:18 -07002446 for (auto stream : media_streams) {
2447 if (stream->GetAudioTracks().empty() &&
2448 stream->GetVideoTracks().empty()) {
2449 remote_streams_->RemoveStream(stream);
2450 removed_streams.push_back(stream);
2451 }
2452 }
Steve Antondcc3c022017-12-22 16:02:54 -08002453 }
2454 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2455 transceiver->internal()->set_current_direction(local_direction);
2456 }
2457 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002458 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2459 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002460 transceiver->Stop();
2461 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002462 if (!content->rejected &&
2463 RtpTransceiverDirectionHasRecv(local_direction)) {
2464 // Set ssrc to 0 in the case of an unsignalled ssrc.
2465 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002466 if (!media_desc->streams().empty() &&
2467 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002468 ssrc = media_desc->streams()[0].first_ssrc();
2469 }
2470 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002471 }
Steve Antondcc3c022017-12-22 16:02:54 -08002472 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002473 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002474 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002475 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002476 observer_->OnTrack(transceiver);
2477 observer_->OnAddTrack(transceiver->receiver(),
2478 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002479 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002480 for (auto stream : added_streams) {
2481 observer_->OnAddStream(stream);
2482 }
Steve Anton3172c032018-05-03 15:30:18 -07002483 for (auto transceiver : no_longer_receiving_transceivers) {
2484 observer_->OnRemoveTrack(transceiver->receiver());
2485 }
2486 for (auto stream : removed_streams) {
2487 observer_->OnRemoveStream(stream);
2488 }
Steve Antondcc3c022017-12-22 16:02:54 -08002489 }
2490
Henrik Boströmfdb92012017-11-09 19:55:44 +01002491 const cricket::ContentInfo* audio_content =
2492 GetFirstAudioContent(remote_description()->description());
2493 const cricket::ContentInfo* video_content =
2494 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002495 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002496 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002497 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002498 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002499 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002500 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002501
2502 // Check if the descriptions include streams, just in case the peer supports
2503 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002504 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002505 (audio_desc && !audio_desc->streams().empty()) ||
2506 (video_desc && !video_desc->streams().empty())) {
2507 remote_peer_supports_msid_ = true;
2508 }
deadbeefab9b2d12015-10-14 11:33:11 -07002509
2510 // We wait to signal new streams until we finish processing the description,
2511 // since only at that point will new streams have all their tracks.
2512 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2513
Steve Antondcc3c022017-12-22 16:02:54 -08002514 if (!IsUnifiedPlan()) {
2515 // TODO(steveanton): When removing RTP senders/receivers in response to a
2516 // rejected media section, there is some cleanup logic that expects the
2517 // voice/ video channel to still be set. But in this method the voice/video
2518 // channel would have been destroyed by the SetRemoteDescription caller
2519 // above so the cleanup that relies on them fails to run. The RemoveSenders
2520 // calls should be moved to right before the DestroyChannel calls to fix
2521 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002522
Steve Antondcc3c022017-12-22 16:02:54 -08002523 // Find all audio rtp streams and create corresponding remote AudioTracks
2524 // and MediaStreams.
2525 if (audio_content) {
2526 if (audio_content->rejected) {
2527 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2528 } else {
2529 bool default_audio_track_needed =
2530 !remote_peer_supports_msid_ &&
2531 RtpTransceiverDirectionHasSend(audio_desc->direction());
2532 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2533 default_audio_track_needed, audio_desc->type(),
2534 new_streams);
2535 }
deadbeeffaac4972015-11-12 15:33:07 -08002536 }
deadbeefab9b2d12015-10-14 11:33:11 -07002537
Steve Antondcc3c022017-12-22 16:02:54 -08002538 // Find all video rtp streams and create corresponding remote VideoTracks
2539 // and MediaStreams.
2540 if (video_content) {
2541 if (video_content->rejected) {
2542 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2543 } else {
2544 bool default_video_track_needed =
2545 !remote_peer_supports_msid_ &&
2546 RtpTransceiverDirectionHasSend(video_desc->direction());
2547 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2548 default_video_track_needed, video_desc->type(),
2549 new_streams);
2550 }
deadbeeffaac4972015-11-12 15:33:07 -08002551 }
deadbeefab9b2d12015-10-14 11:33:11 -07002552
Steve Antondcc3c022017-12-22 16:02:54 -08002553 // Update the DataChannels with the information from the remote peer.
2554 if (data_desc) {
2555 if (rtc::starts_with(data_desc->protocol().data(),
2556 cricket::kMediaProtocolRtpPrefix)) {
2557 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2558 }
deadbeefab9b2d12015-10-14 11:33:11 -07002559 }
deadbeefab9b2d12015-10-14 11:33:11 -07002560
Steve Antondcc3c022017-12-22 16:02:54 -08002561 // Iterate new_streams and notify the observer about new MediaStreams.
2562 for (size_t i = 0; i < new_streams->count(); ++i) {
2563 MediaStreamInterface* new_stream = new_streams->at(i);
2564 stats_->AddStream(new_stream);
2565 observer_->OnAddStream(
2566 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2567 }
deadbeefab9b2d12015-10-14 11:33:11 -07002568
Steve Antondcc3c022017-12-22 16:02:54 -08002569 UpdateEndedRemoteMediaStreams();
2570 }
deadbeefab9b2d12015-10-14 11:33:11 -07002571
Steve Anton8a006912017-12-04 15:25:56 -08002572 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002573}
2574
Steve Antondcc3c022017-12-22 16:02:54 -08002575RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2576 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002577 const SessionDescriptionInterface& new_session,
2578 const SessionDescriptionInterface* old_local_description,
2579 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002580 RTC_DCHECK(IsUnifiedPlan());
2581
Steve Anton7464fca2018-01-19 11:10:37 -08002582 const cricket::ContentGroup* bundle_group = nullptr;
2583 if (new_session.GetType() == SdpType::kOffer) {
2584 auto bundle_group_or_error =
2585 GetEarlyBundleGroup(*new_session.description());
2586 if (!bundle_group_or_error.ok()) {
2587 return bundle_group_or_error.MoveError();
2588 }
2589 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002590 }
Steve Antondcc3c022017-12-22 16:02:54 -08002591
Steve Antondcc3c022017-12-22 16:02:54 -08002592 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002593 for (size_t i = 0; i < new_contents.size(); ++i) {
2594 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002595 cricket::MediaType media_type = new_content.media_description()->type();
2596 seen_mids_.insert(new_content.name);
2597 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2598 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002599 const cricket::ContentInfo* old_local_content = nullptr;
2600 if (old_local_description &&
2601 i < old_local_description->description()->contents().size()) {
2602 old_local_content =
2603 &old_local_description->description()->contents()[i];
2604 }
2605 const cricket::ContentInfo* old_remote_content = nullptr;
2606 if (old_remote_description &&
2607 i < old_remote_description->description()->contents().size()) {
2608 old_remote_content =
2609 &old_remote_description->description()->contents()[i];
2610 }
Steve Antondcc3c022017-12-22 16:02:54 -08002611 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002612 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2613 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002614 if (!transceiver_or_error.ok()) {
2615 return transceiver_or_error.MoveError();
2616 }
2617 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002618 RTCError error =
2619 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2620 if (!error.ok()) {
2621 return error;
2622 }
2623 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002624 if (GetDataMid() && new_content.name != *GetDataMid()) {
2625 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002626 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2627 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002628 continue;
2629 }
2630 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2631 if (!error.ok()) {
2632 return error;
2633 }
Steve Antondcc3c022017-12-22 16:02:54 -08002634 } else {
2635 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2636 "Unknown section type.");
2637 }
2638 }
2639
2640 return RTCError::OK();
2641}
2642
2643RTCError PeerConnection::UpdateTransceiverChannel(
2644 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2645 transceiver,
2646 const cricket::ContentInfo& content,
2647 const cricket::ContentGroup* bundle_group) {
2648 RTC_DCHECK(IsUnifiedPlan());
2649 RTC_DCHECK(transceiver);
2650 cricket::BaseChannel* channel = transceiver->internal()->channel();
2651 if (content.rejected) {
2652 if (channel) {
2653 transceiver->internal()->SetChannel(nullptr);
2654 DestroyBaseChannel(channel);
2655 }
2656 } else {
2657 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002658 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002659 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002660 } else {
Steve Anton69470252018-02-09 11:43:08 -08002661 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002662 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002663 }
2664 if (!channel) {
2665 LOG_AND_RETURN_ERROR(
2666 RTCErrorType::INTERNAL_ERROR,
2667 "Failed to create channel for mid=" + content.name);
2668 }
2669 transceiver->internal()->SetChannel(channel);
2670 }
2671 }
2672 return RTCError::OK();
2673}
2674
Steve Antonfa2260d2017-12-28 16:38:23 -08002675RTCError PeerConnection::UpdateDataChannel(
2676 cricket::ContentSource source,
2677 const cricket::ContentInfo& content,
2678 const cricket::ContentGroup* bundle_group) {
2679 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002680 // If data channels are disabled, ignore this media section. CreateAnswer
2681 // will take care of rejecting it.
2682 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002683 }
2684 if (content.rejected) {
2685 DestroyDataChannel();
2686 } else {
2687 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002688 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002689 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2690 "Failed to create data channel.");
2691 }
2692 }
2693 if (source == cricket::CS_REMOTE) {
2694 const MediaContentDescription* data_desc = content.media_description();
2695 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2696 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2697 }
2698 }
2699 }
2700 return RTCError::OK();
2701}
2702
Steve Antondcc3c022017-12-22 16:02:54 -08002703RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2704PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002705 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002706 size_t mline_index,
2707 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002708 const ContentInfo* old_local_content,
2709 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002710 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002711 // If this is an offer then the m= section might be recycled. If the m=
2712 // section is being recycled (defined as: rejected in the current local or
2713 // remote description and not rejected in new description), dissociate the
2714 // currently associated RtpTransceiver by setting its mid property to null,
2715 // and discard the mapping between the transceiver and its m= section index.
2716 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2717 old_remote_content)) {
2718 // We want to dissociate the transceiver that has the rejected mid.
2719 const std::string& old_mid =
2720 (old_local_content && old_local_content->rejected)
2721 ? old_local_content->name
2722 : old_remote_content->name;
2723 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002724 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002725 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2726 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002727 old_transceiver->internal()->set_mid(absl::nullopt);
2728 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002729 }
2730 }
2731 const MediaContentDescription* media_desc = content.media_description();
2732 auto transceiver = GetAssociatedTransceiver(content.name);
2733 if (source == cricket::CS_LOCAL) {
2734 // Find the RtpTransceiver that corresponds to this m= section, using the
2735 // mapping between transceivers and m= section indices established when
2736 // creating the offer.
2737 if (!transceiver) {
2738 transceiver = GetTransceiverByMLineIndex(mline_index);
2739 }
2740 if (!transceiver) {
2741 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2742 "Unknown transceiver");
2743 }
2744 } else {
2745 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2746 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2747 // of the same type...
2748 if (!transceiver &&
2749 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2750 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2751 }
2752 // If no RtpTransceiver was found in the previous step, create one with a
2753 // recvonly direction.
2754 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002755 RTC_LOG(LS_INFO) << "Adding "
2756 << cricket::MediaTypeToString(media_desc->type())
2757 << " transceiver for MID=" << content.name
2758 << " at i=" << mline_index
2759 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002760 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002761 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002762 std::string receiver_id;
2763 if (!media_desc->streams().empty()) {
2764 receiver_id = media_desc->streams()[0].id;
2765 } else {
2766 receiver_id = rtc::CreateRandomUuid();
2767 }
2768 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002769 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002770 transceiver->internal()->set_direction(
2771 RtpTransceiverDirection::kRecvOnly);
2772 }
2773 }
2774 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002775 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002776 LOG_AND_RETURN_ERROR(
2777 RTCErrorType::INVALID_PARAMETER,
2778 "Transceiver type does not match media description type.");
2779 }
2780 // Associate the found or created RtpTransceiver with the m= section by
2781 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2782 // section, and establish a mapping between the transceiver and the index of
2783 // the m= section.
2784 transceiver->internal()->set_mid(content.name);
2785 transceiver->internal()->set_mline_index(mline_index);
2786 return std::move(transceiver);
2787}
2788
2789rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2790PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2791 RTC_DCHECK(IsUnifiedPlan());
2792 for (auto transceiver : transceivers_) {
2793 if (transceiver->mid() == mid) {
2794 return transceiver;
2795 }
2796 }
2797 return nullptr;
2798}
2799
2800rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2801PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2802 RTC_DCHECK(IsUnifiedPlan());
2803 for (auto transceiver : transceivers_) {
2804 if (transceiver->internal()->mline_index() == mline_index) {
2805 return transceiver;
2806 }
2807 }
2808 return nullptr;
2809}
2810
2811rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2812PeerConnection::FindAvailableTransceiverToReceive(
2813 cricket::MediaType media_type) const {
2814 RTC_DCHECK(IsUnifiedPlan());
2815 // From JSEP section 5.10 (Applying a Remote Description):
2816 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2817 // the same type that were added to the PeerConnection by addTrack and are not
2818 // associated with any m= section and are not stopped, find the first such
2819 // RtpTransceiver.
2820 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002821 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002822 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2823 !transceiver->stopped()) {
2824 return transceiver;
2825 }
2826 }
2827 return nullptr;
2828}
2829
Steve Antoned10bd92017-12-05 10:52:59 -08002830const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2831 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2832 transceiver,
2833 const SessionDescriptionInterface* sdesc) const {
2834 RTC_DCHECK(transceiver);
2835 RTC_DCHECK(sdesc);
2836 if (IsUnifiedPlan()) {
2837 if (!transceiver->internal()->mid()) {
2838 // This transceiver is not associated with a media section yet.
2839 return nullptr;
2840 }
2841 return sdesc->description()->GetContentByName(
2842 *transceiver->internal()->mid());
2843 } else {
2844 // Plan B only allows at most one audio and one video section, so use the
2845 // first media section of that type.
2846 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002847 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002848 }
2849}
2850
deadbeef46c73892016-11-16 19:42:04 -08002851PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2852 return configuration_;
2853}
2854
deadbeef293e9262017-01-11 12:28:30 -08002855bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2856 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002857 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002858 if (IsClosed()) {
2859 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2860 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2861 }
2862
Qingsi Wanga2d60672018-04-11 16:57:45 -07002863 // According to JSEP, after setLocalDescription, changing the candidate pool
2864 // size is not allowed, and changing the set of ICE servers will not result
2865 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002866 if (local_description() && configuration.ice_candidate_pool_size !=
2867 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002868 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2869 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002870 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002871 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002872
deadbeef293e9262017-01-11 12:28:30 -08002873 // The simplest (and most future-compatible) way to tell if the config was
2874 // modified in an invalid way is to copy each property we do support
2875 // modifying, then use operator==. There are far more properties we don't
2876 // support modifying than those we do, and more could be added.
2877 RTCConfiguration modified_config = configuration_;
2878 modified_config.servers = configuration.servers;
2879 modified_config.type = configuration.type;
2880 modified_config.ice_candidate_pool_size =
2881 configuration.ice_candidate_pool_size;
2882 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002883 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002884 modified_config.ice_check_interval_strong_connectivity =
2885 configuration.ice_check_interval_strong_connectivity;
2886 modified_config.ice_check_interval_weak_connectivity =
2887 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002888 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2889 modified_config.ice_unwritable_min_checks =
2890 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002891 modified_config.stun_candidate_keepalive_interval =
2892 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002893 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002894 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002895 modified_config.active_reset_srtp_params =
2896 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002897 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002898 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002899 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2900 }
2901
Steve Anton038834f2017-07-14 15:59:59 -07002902 // Validate the modified configuration.
2903 RTCError validate_error = ValidateConfiguration(modified_config);
2904 if (!validate_error.ok()) {
2905 return SafeSetError(std::move(validate_error), error);
2906 }
2907
deadbeef293e9262017-01-11 12:28:30 -08002908 // Note that this isn't possible through chromium, since it's an unsigned
2909 // short in WebIDL.
2910 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002911 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002912 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2913 }
2914
2915 // Parse ICE servers before hopping to network thread.
2916 cricket::ServerAddresses stun_servers;
2917 std::vector<cricket::RelayServerConfig> turn_servers;
2918 RTCErrorType parse_error =
2919 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2920 if (parse_error != RTCErrorType::NONE) {
2921 return SafeSetError(parse_error, error);
2922 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002923 // Note if STUN or TURN servers were supplied.
2924 if (!stun_servers.empty()) {
2925 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2926 }
2927 if (!turn_servers.empty()) {
2928 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2929 }
deadbeef293e9262017-01-11 12:28:30 -08002930
2931 // In theory this shouldn't fail.
2932 if (!network_thread()->Invoke<bool>(
2933 RTC_FROM_HERE,
2934 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2935 stun_servers, turn_servers, modified_config.type,
2936 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002937 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002938 modified_config.turn_customizer,
2939 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002940 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002941 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2942 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002943
deadbeefd1a38b52016-12-10 13:15:33 -08002944 // As described in JSEP, calling setConfiguration with new ICE servers or
2945 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2946 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002947 if (modified_config.servers != configuration_.servers ||
2948 modified_config.type != configuration_.type ||
2949 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002950 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002951 }
skvladd1f5fda2017-02-03 16:54:05 -08002952
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002953 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002954
Zhi Huangb57e1692018-06-12 11:41:11 -07002955 if (configuration_.active_reset_srtp_params !=
2956 modified_config.active_reset_srtp_params) {
2957 transport_controller_->SetActiveResetSrtpParams(
2958 modified_config.active_reset_srtp_params);
2959 }
2960
deadbeef293e9262017-01-11 12:28:30 -08002961 configuration_ = modified_config;
2962 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002963}
2964
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002965bool PeerConnection::AddIceCandidate(
2966 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002967 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002968 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002969 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002970 return false;
2971 }
Steve Antond25da372017-11-06 14:50:29 -08002972
2973 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002974 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002975 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002976 return false;
2977 }
2978
2979 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002980 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002981 return false;
2982 }
2983
2984 bool valid = false;
2985 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2986 if (!valid) {
2987 return false;
2988 }
2989
2990 // Add this candidate to the remote session description.
2991 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002992 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002993 return false;
2994 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002995 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002996
2997 if (ready) {
2998 return UseCandidate(ice_candidate);
2999 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003000 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08003001 return true;
3002 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003003}
3004
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003005bool PeerConnection::RemoveIceCandidates(
3006 const std::vector<cricket::Candidate>& candidates) {
3007 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003008 if (IsClosed()) {
3009 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3010 return false;
3011 }
3012
Steve Antond25da372017-11-06 14:50:29 -08003013 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003014 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3015 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003016 return false;
3017 }
3018
3019 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003020 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003021 return false;
3022 }
3023
3024 size_t number_removed =
3025 mutable_remote_description()->RemoveCandidates(candidates);
3026 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003027 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003028 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003029 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003030 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003031 }
3032
3033 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003034 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3035 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003036 RTC_LOG(LS_ERROR)
3037 << "RemoveIceCandidates: Error when removing remote candidates: "
3038 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003039 }
3040 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003041}
3042
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003043void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003044 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003045 network_thread()->Invoke<void>(
3046 RTC_FROM_HERE,
3047 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
Qingsi Wang78fef762018-07-11 18:33:52 +00003048 // Send information about IPv4/IPv6 status.
3049 if (uma_observer_) {
3050 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3051 uma_observer_->IncrementEnumCounter(
3052 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3053 kPeerConnectionAddressFamilyCounter_Max);
3054 } else {
3055 uma_observer_->IncrementEnumCounter(
3056 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3057 kPeerConnectionAddressFamilyCounter_Max);
3058 }
3059 }
Qingsi Wanga2d60672018-04-11 16:57:45 -07003060}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003061
Qingsi Wanga2d60672018-04-11 16:57:45 -07003062void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3063 RTC_DCHECK(network_thread()->IsCurrent());
3064 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003065 if (transport_controller_) {
3066 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003067 }
3068
3069 for (auto transceiver : transceivers_) {
3070 auto* channel = transceiver->internal()->channel();
3071 if (channel) {
3072 channel->SetMetricsObserver(uma_observer_);
3073 }
3074 }
3075
deadbeef293e9262017-01-11 12:28:30 -08003076 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003077 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003078 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003079}
3080
Niels Möller0c4f7be2018-05-07 14:01:37 +02003081RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003082 if (!worker_thread()->IsCurrent()) {
3083 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003084 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003085 }
3086
Niels Möller0c4f7be2018-05-07 14:01:37 +02003087 const bool has_min = bitrate.min_bitrate_bps.has_value();
3088 const bool has_start = bitrate.start_bitrate_bps.has_value();
3089 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003090 if (has_min && *bitrate.min_bitrate_bps < 0) {
3091 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3092 "min_bitrate_bps <= 0");
3093 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003094 if (has_start) {
3095 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003096 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003097 "start_bitrate_bps < min_bitrate_bps");
3098 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003099 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3100 "curent_bitrate_bps < 0");
3101 }
3102 }
3103 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003104 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003105 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003106 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003107 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3108 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3109 "max_bitrate_bps < min_bitrate_bps");
3110 } else if (*bitrate.max_bitrate_bps < 0) {
3111 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3112 "max_bitrate_bps < 0");
3113 }
3114 }
3115
zstein4b979802017-06-02 14:37:37 -07003116 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003117 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003118
3119 return RTCError::OK();
3120}
3121
Alex Narest78609d52017-10-20 10:37:47 +02003122void PeerConnection::SetBitrateAllocationStrategy(
3123 std::unique_ptr<rtc::BitrateAllocationStrategy>
3124 bitrate_allocation_strategy) {
3125 rtc::Thread* worker_thread = factory_->worker_thread();
3126 if (!worker_thread->IsCurrent()) {
3127 rtc::BitrateAllocationStrategy* strategy_raw =
3128 bitrate_allocation_strategy.release();
3129 auto functor = [this, strategy_raw]() {
3130 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003131 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003132 };
3133 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3134 return;
3135 }
3136 RTC_DCHECK(call_.get());
3137 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3138}
3139
henrika5f6bf242017-11-01 11:06:56 +01003140void PeerConnection::SetAudioPlayout(bool playout) {
3141 if (!worker_thread()->IsCurrent()) {
3142 worker_thread()->Invoke<void>(
3143 RTC_FROM_HERE,
3144 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3145 return;
3146 }
3147 auto audio_state =
3148 factory_->channel_manager()->media_engine()->GetAudioState();
3149 audio_state->SetPlayout(playout);
3150}
3151
3152void PeerConnection::SetAudioRecording(bool recording) {
3153 if (!worker_thread()->IsCurrent()) {
3154 worker_thread()->Invoke<void>(
3155 RTC_FROM_HERE,
3156 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3157 return;
3158 }
3159 auto audio_state =
3160 factory_->channel_manager()->media_engine()->GetAudioState();
3161 audio_state->SetRecording(recording);
3162}
3163
Steve Anton8c0f7a72017-10-03 10:03:10 -07003164std::unique_ptr<rtc::SSLCertificate>
3165PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003166 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3167 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003168 return nullptr;
3169 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003170 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003171}
3172
Zhi Huang70b820f2018-01-27 14:16:15 -08003173std::unique_ptr<rtc::SSLCertChain>
3174PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003175 auto audio_transceiver = GetFirstAudioTransceiver();
3176 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003177 return nullptr;
3178 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003179 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003180 audio_transceiver->internal()->channel()->transport_name());
3181}
3182
3183rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3184PeerConnection::GetFirstAudioTransceiver() const {
3185 for (auto transceiver : transceivers_) {
3186 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3187 return transceiver;
3188 }
3189 }
3190 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003191}
3192
ivoc14d5dbe2016-07-04 07:06:55 -07003193bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3194 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003195 // TODO(eladalon): It would be better to not allow negative values into PC.
3196 const size_t max_size = (max_size_bytes < 0)
3197 ? RtcEventLog::kUnlimitedOutput
3198 : rtc::saturated_cast<size_t>(max_size_bytes);
3199 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003200 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003201 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003202}
3203
Bjorn Tereliusde939432017-11-20 17:38:14 +01003204bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3205 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003206 // TODO(eladalon): In C++14, this can be done with a lambda.
3207 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003208 bool operator()() {
3209 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3210 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003211 PeerConnection* const pc;
3212 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003213 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003214 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003215 return worker_thread()->Invoke<bool>(
3216 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003217}
3218
3219void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003220 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003221 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3222}
3223
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003225 return pending_local_description_ ? pending_local_description_.get()
3226 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003227}
3228
3229const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003230 return pending_remote_description_ ? pending_remote_description_.get()
3231 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003232}
3233
deadbeeffe4a8a42016-12-20 17:56:17 -08003234const SessionDescriptionInterface* PeerConnection::current_local_description()
3235 const {
Steve Anton75737c02017-11-06 10:37:17 -08003236 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003237}
3238
3239const SessionDescriptionInterface* PeerConnection::current_remote_description()
3240 const {
Steve Anton75737c02017-11-06 10:37:17 -08003241 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003242}
3243
3244const SessionDescriptionInterface* PeerConnection::pending_local_description()
3245 const {
Steve Anton75737c02017-11-06 10:37:17 -08003246 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003247}
3248
3249const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3250 const {
Steve Anton75737c02017-11-06 10:37:17 -08003251 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003252}
3253
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003254void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003255 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003256 // Update stats here so that we have the most recent stats for tracks and
3257 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003258 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003259
Steve Anton75737c02017-11-06 10:37:17 -08003260 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003261 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003262
Steve Anton8af21862017-12-15 11:20:13 -08003263 for (auto transceiver : transceivers_) {
3264 transceiver->Stop();
3265 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003266
3267 // Ensure that all asynchronous stats requests are completed before destroying
3268 // the transport controller below.
3269 if (stats_collector_) {
3270 stats_collector_->WaitForPendingRequest();
3271 }
3272
3273 // Don't destroy BaseChannels until after stats has been cleaned up so that
3274 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003275 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003276
Qingsi Wang93a84392018-01-30 17:13:09 -08003277 // The event log is used in the transport controller, which must be outlived
3278 // by the former. CreateOffer by the peer connection is implemented
3279 // asynchronously and if the peer connection is closed without resetting the
3280 // WebRTC session description factory, the session description factory would
3281 // call the transport controller.
3282 webrtc_session_desc_factory_.reset();
3283 transport_controller_.reset();
3284
deadbeef42a42632017-03-10 15:18:00 -08003285 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003286 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3287 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003288
Steve Anton978b8762017-09-29 12:15:02 -07003289 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003290 call_.reset();
3291 // The event log must outlive call (and any other object that uses it).
3292 event_log_.reset();
3293 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003294 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003295}
3296
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003297void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003298 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3300 SetSessionDescriptionMsg* param =
3301 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3302 param->observer->OnSuccess();
3303 delete param;
3304 break;
3305 }
3306 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3307 SetSessionDescriptionMsg* param =
3308 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003309 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003310 delete param;
3311 break;
3312 }
deadbeefab9b2d12015-10-14 11:33:11 -07003313 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3314 CreateSessionDescriptionMsg* param =
3315 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003316 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003317 delete param;
3318 break;
3319 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003320 case MSG_GETSTATS: {
3321 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003322 StatsReports reports;
3323 stats_->GetStats(param->track, &reports);
3324 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003325 delete param;
3326 break;
3327 }
deadbeefbd292462015-12-14 18:15:29 -08003328 case MSG_FREE_DATACHANNELS: {
3329 sctp_data_channels_to_free_.clear();
3330 break;
3331 }
Harald Alvestrand19793842018-06-25 12:03:50 +02003332 case MSG_REPORT_USAGE_PATTERN: {
3333 ReportUsagePattern();
3334 break;
3335 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003336 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003337 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003338 break;
3339 }
3340}
3341
Steve Antonafb0bb72018-02-20 11:35:37 -08003342cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3343 RTC_DCHECK(!IsUnifiedPlan());
3344 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3345 GetAudioTransceiver()->internal()->channel());
3346 if (voice_channel) {
3347 return voice_channel->media_channel();
3348 } else {
3349 return nullptr;
3350 }
3351}
3352
3353cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3354 RTC_DCHECK(!IsUnifiedPlan());
3355 auto* video_channel = static_cast<cricket::VideoChannel*>(
3356 GetVideoTransceiver()->internal()->channel());
3357 if (video_channel) {
3358 return video_channel->media_channel();
3359 } else {
3360 return nullptr;
3361 }
3362}
3363
Steve Anton4171afb2017-11-20 10:20:22 -08003364void PeerConnection::CreateAudioReceiver(
3365 MediaStreamInterface* stream,
3366 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003367 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3368 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003369 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3370 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003371 auto* audio_receiver = new AudioRtpReceiver(
3372 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003373 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003374 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3375 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3376 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003377 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003378 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003379 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003380}
3381
Steve Anton4171afb2017-11-20 10:20:22 -08003382void PeerConnection::CreateVideoReceiver(
3383 MediaStreamInterface* stream,
3384 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003385 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3386 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003387 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3388 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003389 auto* video_receiver = new VideoRtpReceiver(
3390 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003391 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003392 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3393 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3394 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003395 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003396 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003397 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003398}
3399
deadbeef70ab1a12015-09-28 16:53:55 -07003400// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3401// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003402rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003403 const RtpSenderInfo& remote_sender_info) {
3404 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3405 if (!receiver) {
3406 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3407 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003408 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003409 }
Steve Anton4171afb2017-11-20 10:20:22 -08003410 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3411 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3412 } else {
3413 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3414 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003415 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003416}
3417
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003418void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3419 MediaStreamInterface* stream) {
3420 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003421 RTC_DCHECK(track);
3422 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003423 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003424 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003425 // We already have a sender for this track, so just change the stream_id
3426 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003427 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003428 return;
3429 }
3430
3431 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003432 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3433 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003434 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003435 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003436 // If the sender has already been configured in SDP, we call SetSsrc,
3437 // which will connect the sender to the underlying transport. This can
3438 // occur if a local session description that contains the ID of the sender
3439 // is set before AddStream is called. It can also occur if the local
3440 // session description is not changed and RemoveStream is called, and
3441 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003442 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003443 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003444 if (sender_info) {
3445 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003446 }
3447}
3448
3449// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3450// indefinitely, when we have unified plan SDP.
3451void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3452 MediaStreamInterface* stream) {
3453 RTC_DCHECK(!IsClosed());
3454 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003455 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003456 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3457 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003458 return;
3459 }
Steve Anton4171afb2017-11-20 10:20:22 -08003460 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003461}
3462
3463void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3464 MediaStreamInterface* stream) {
3465 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003466 RTC_DCHECK(track);
3467 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003468 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003469 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003470 // We already have a sender for this track, so just change the stream_id
3471 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003472 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003473 return;
3474 }
3475
3476 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003477 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3478 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003479 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003480 GetVideoTransceiver()->internal()->AddSender(new_sender);
3481 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003482 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003483 if (sender_info) {
3484 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003485 }
3486}
3487
3488void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3489 MediaStreamInterface* stream) {
3490 RTC_DCHECK(!IsClosed());
3491 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003492 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003493 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3494 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003495 return;
3496 }
Steve Anton4171afb2017-11-20 10:20:22 -08003497 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003498}
3499
Steve Antonba818672017-11-06 10:21:57 -08003500void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003501 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003502 if (ice_connection_state_ == new_state) {
3503 return;
3504 }
3505
deadbeefcbecd352015-09-23 11:50:27 -07003506 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003507 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003508 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003509 return;
3510 }
Steve Antonba818672017-11-06 10:21:57 -08003511
Mirko Bonadei675513b2017-11-09 11:09:25 +01003512 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3513 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003514 RTC_DCHECK(ice_connection_state_ !=
3515 PeerConnectionInterface::kIceConnectionClosed);
3516
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003517 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003518 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003519}
3520
3521void PeerConnection::OnIceGatheringChange(
3522 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003523 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003524 if (IsClosed()) {
3525 return;
3526 }
3527 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003528 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003529}
3530
jbauch81bf7b02017-03-25 08:31:12 -07003531void PeerConnection::OnIceCandidate(
3532 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003533 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003534 if (IsClosed()) {
3535 return;
3536 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003537 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003538 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003539}
3540
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003541void PeerConnection::OnIceCandidatesRemoved(
3542 const std::vector<cricket::Candidate>& candidates) {
3543 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003544 if (IsClosed()) {
3545 return;
3546 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003547 observer_->OnIceCandidatesRemoved(candidates);
3548}
3549
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003550void PeerConnection::ChangeSignalingState(
3551 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003552 RTC_DCHECK(signaling_thread()->IsCurrent());
3553 if (signaling_state_ == signaling_state) {
3554 return;
3555 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003556 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3557 << GetSignalingStateString(signaling_state_)
3558 << " New state: "
3559 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003560 signaling_state_ = signaling_state;
3561 if (signaling_state == kClosed) {
3562 ice_connection_state_ = kIceConnectionClosed;
3563 observer_->OnIceConnectionChange(ice_connection_state_);
3564 if (ice_gathering_state_ != kIceGatheringComplete) {
3565 ice_gathering_state_ = kIceGatheringComplete;
3566 observer_->OnIceGatheringChange(ice_gathering_state_);
3567 }
3568 }
3569 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003570}
3571
deadbeefeb459812015-12-15 19:24:43 -08003572void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3573 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003574 if (IsClosed()) {
3575 return;
3576 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003577 AddAudioTrack(track, stream);
3578 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003579}
3580
deadbeefeb459812015-12-15 19:24:43 -08003581void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3582 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003583 if (IsClosed()) {
3584 return;
3585 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003586 RemoveAudioTrack(track, stream);
3587 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003588}
3589
3590void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3591 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003592 if (IsClosed()) {
3593 return;
3594 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003595 AddVideoTrack(track, stream);
3596 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003597}
3598
3599void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3600 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003601 if (IsClosed()) {
3602 return;
3603 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003604 RemoveVideoTrack(track, stream);
3605 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003606}
3607
Henrik Boström31638672017-11-23 17:48:32 +01003608void PeerConnection::PostSetSessionDescriptionSuccess(
3609 SetSessionDescriptionObserver* observer) {
3610 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3611 signaling_thread()->Post(RTC_FROM_HERE, this,
3612 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3613}
3614
deadbeefab9b2d12015-10-14 11:33:11 -07003615void PeerConnection::PostSetSessionDescriptionFailure(
3616 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003617 RTCError&& error) {
3618 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003619 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003620 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003621 signaling_thread()->Post(RTC_FROM_HERE, this,
3622 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003623}
3624
3625void PeerConnection::PostCreateSessionDescriptionFailure(
3626 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003627 RTCError error) {
3628 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003629 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003630 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003631 signaling_thread()->Post(RTC_FROM_HERE, this,
3632 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003633}
3634
zhihuang1c378ed2017-08-17 14:10:50 -07003635void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003636 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003637 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003638 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003639
Steve Antondcc3c022017-12-22 16:02:54 -08003640 if (IsUnifiedPlan()) {
3641 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3642 } else {
3643 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3644 }
3645
Steve Antonfa2260d2017-12-28 16:38:23 -08003646 // Intentionally unset the data channel type for RTP data channel with the
3647 // second condition. Otherwise the RTP data channels would be successfully
3648 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3649 // when building with chromium. We want to leave RTP data channels broken, so
3650 // people won't try to use them.
3651 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3652 session_options->data_channel_type = data_channel_type();
3653 }
3654
Steve Antondcc3c022017-12-22 16:02:54 -08003655 // Apply ICE restart flag and renomination flag.
3656 for (auto& options : session_options->media_description_options) {
3657 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3658 options.transport_options.enable_ice_renomination =
3659 configuration_.enable_ice_renomination;
3660 }
3661
3662 session_options->rtcp_cname = rtcp_cname_;
3663 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003664 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003665}
3666
3667void PeerConnection::GetOptionsForPlanBOffer(
3668 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3669 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003670 // Figure out transceiver directional preferences.
3671 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3672 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3673
3674 // By default, generate sendrecv/recvonly m= sections.
3675 bool recv_audio = true;
3676 bool recv_video = true;
3677
3678 // By default, only offer a new m= section if we have media to send with it.
3679 bool offer_new_audio_description = send_audio;
3680 bool offer_new_video_description = send_video;
3681 bool offer_new_data_description = HasDataChannels();
3682
3683 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003684 if (offer_answer_options.offer_to_receive_audio !=
3685 RTCOfferAnswerOptions::kUndefined) {
3686 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003687 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003688 offer_new_audio_description ||
3689 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003690 }
Steve Antondcc3c022017-12-22 16:02:54 -08003691 if (offer_answer_options.offer_to_receive_video !=
3692 RTCOfferAnswerOptions::kUndefined) {
3693 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003694 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003695 offer_new_video_description ||
3696 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003697 }
3698
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003699 absl::optional<size_t> audio_index;
3700 absl::optional<size_t> video_index;
3701 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003702 // If a current description exists, generate m= sections in the same order,
3703 // using the first audio/video/data section that appears and rejecting
3704 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003705 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003706 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003707 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003708 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3709 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3710 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003711 }
3712
zhihuang1c378ed2017-08-17 14:10:50 -07003713 // Add audio/video/data m= sections to the end if needed.
3714 if (!audio_index && offer_new_audio_description) {
3715 session_options->media_description_options.push_back(
3716 cricket::MediaDescriptionOptions(
3717 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003718 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3719 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003720 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003721 }
zhihuang1c378ed2017-08-17 14:10:50 -07003722 if (!video_index && offer_new_video_description) {
3723 session_options->media_description_options.push_back(
3724 cricket::MediaDescriptionOptions(
3725 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003726 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3727 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003728 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003729 }
zhihuang1c378ed2017-08-17 14:10:50 -07003730 if (!data_index && offer_new_data_description) {
3731 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003732 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003733 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003734 }
3735
3736 cricket::MediaDescriptionOptions* audio_media_description_options =
3737 !audio_index ? nullptr
3738 : &session_options->media_description_options[*audio_index];
3739 cricket::MediaDescriptionOptions* video_media_description_options =
3740 !video_index ? nullptr
3741 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003742
Steve Anton4171afb2017-11-20 10:20:22 -08003743 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003744 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003745}
3746
3747// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3748// and return a reference to it.
3749// Generated MIDs should be no more than 3 bytes long to take up less space in
3750// the RTP packet.
3751static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3752 RTC_DCHECK(used_mids);
3753 // We're boring: just generate MIDs 0, 1, 2, ...
3754 size_t i = 0;
3755 std::set<std::string>::iterator it;
3756 bool inserted;
3757 do {
3758 std::string mid = rtc::ToString(i++);
3759 auto insert_result = used_mids->insert(mid);
3760 it = insert_result.first;
3761 inserted = insert_result.second;
3762 } while (!inserted);
3763 return *it;
3764}
3765
3766static cricket::MediaDescriptionOptions
3767GetMediaDescriptionOptionsForTransceiver(
3768 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3769 transceiver,
3770 const std::string& mid) {
3771 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003772 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003773 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003774 // This behavior is specified in JSEP. The gist is that:
3775 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3776 // sendrecv.
3777 // 2. If the MSID is included, then it must be included in any subsequent
3778 // offer/answer exactly the same until the RtpTransceiver is stopped.
3779 if (!transceiver->stopped() &&
3780 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3781 transceiver->internal()->has_ever_been_used_to_send())) {
3782 cricket::SenderOptions sender_options;
3783 sender_options.track_id = transceiver->sender()->id();
3784 sender_options.stream_ids = transceiver->sender()->stream_ids();
3785 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3786 // set in the RTP parameters when the transceiver was added.
3787 sender_options.num_sim_layers = 1;
3788 media_description_options.sender_options.push_back(sender_options);
3789 }
Steve Antondcc3c022017-12-22 16:02:54 -08003790 return media_description_options;
3791}
3792
3793void PeerConnection::GetOptionsForUnifiedPlanOffer(
3794 const RTCOfferAnswerOptions& offer_answer_options,
3795 cricket::MediaSessionOptions* session_options) {
3796 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3797 // Offers) and 5.2.2 (Subsequent Offers).
3798 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3799 const ContentInfos& local_contents =
3800 (local_description() ? local_description()->description()->contents()
3801 : ContentInfos());
3802 const ContentInfos& remote_contents =
3803 (remote_description() ? remote_description()->description()->contents()
3804 : ContentInfos());
3805 // The mline indices that can be recycled. New transceivers should reuse these
3806 // slots first.
3807 std::queue<size_t> recycleable_mline_indices;
3808 // Track the MIDs used in previous offer/answer exchanges and the current
3809 // offer so that new, unique MIDs are generated.
3810 std::set<std::string> used_mids = seen_mids_;
3811 // First, go through each media section that exists in either the local or
3812 // remote description and generate a media section in this offer for the
3813 // associated transceiver. If a media section can be recycled, generate a
3814 // default, rejected media section here that can be later overwritten.
3815 for (size_t i = 0;
3816 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3817 // Either |local_content| or |remote_content| is non-null.
3818 const ContentInfo* local_content =
3819 (i < local_contents.size() ? &local_contents[i] : nullptr);
3820 const ContentInfo* remote_content =
3821 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3822 bool had_been_rejected = (local_content && local_content->rejected) ||
3823 (remote_content && remote_content->rejected);
3824 const std::string& mid =
3825 (local_content ? local_content->name : remote_content->name);
3826 cricket::MediaType media_type =
3827 (local_content ? local_content->media_description()->type()
3828 : remote_content->media_description()->type());
3829 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3830 media_type == cricket::MEDIA_TYPE_VIDEO) {
3831 auto transceiver = GetAssociatedTransceiver(mid);
3832 RTC_CHECK(transceiver);
3833 // A media section is considered eligible for recycling if it is marked as
3834 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003835 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003836 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003837 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3838 RtpTransceiverDirection::kInactive,
3839 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003840 recycleable_mline_indices.push(i);
3841 } else {
3842 session_options->media_description_options.push_back(
3843 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3844 // CreateOffer shouldn't really cause any state changes in
3845 // PeerConnection, but we need a way to match new transceivers to new
3846 // media sections in SetLocalDescription and JSEP specifies this is done
3847 // by recording the index of the media section generated for the
3848 // transceiver in the offer.
3849 transceiver->internal()->set_mline_index(i);
3850 }
3851 } else {
3852 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003853 RTC_CHECK(GetDataMid());
3854 if (had_been_rejected || mid != *GetDataMid()) {
3855 session_options->media_description_options.push_back(
3856 GetMediaDescriptionOptionsForRejectedData(mid));
3857 } else {
3858 session_options->media_description_options.push_back(
3859 GetMediaDescriptionOptionsForActiveData(mid));
3860 }
Steve Antondcc3c022017-12-22 16:02:54 -08003861 }
3862 }
3863 // Next, look for transceivers that are newly added (that is, are not stopped
3864 // and not associated). Reuse media sections marked as recyclable first,
3865 // otherwise append to the end of the offer. New media sections should be
3866 // added in the order they were added to the PeerConnection.
3867 for (auto transceiver : transceivers_) {
3868 if (transceiver->mid() || transceiver->stopped()) {
3869 continue;
3870 }
3871 size_t mline_index;
3872 if (!recycleable_mline_indices.empty()) {
3873 mline_index = recycleable_mline_indices.front();
3874 recycleable_mline_indices.pop();
3875 session_options->media_description_options[mline_index] =
3876 GetMediaDescriptionOptionsForTransceiver(transceiver,
3877 AllocateMid(&used_mids));
3878 } else {
3879 mline_index = session_options->media_description_options.size();
3880 session_options->media_description_options.push_back(
3881 GetMediaDescriptionOptionsForTransceiver(transceiver,
3882 AllocateMid(&used_mids)));
3883 }
3884 // See comment above for why CreateOffer changes the transceiver's state.
3885 transceiver->internal()->set_mline_index(mline_index);
3886 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003887 // Lastly, add a m-section if we have local data channels and an m section
3888 // does not already exist.
3889 if (!GetDataMid() && HasDataChannels()) {
3890 session_options->media_description_options.push_back(
3891 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3892 }
Steve Antondcc3c022017-12-22 16:02:54 -08003893}
3894
3895void PeerConnection::GetOptionsForAnswer(
3896 const RTCOfferAnswerOptions& offer_answer_options,
3897 cricket::MediaSessionOptions* session_options) {
3898 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3899
3900 if (IsUnifiedPlan()) {
3901 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3902 } else {
3903 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3904 }
3905
Steve Antonfa2260d2017-12-28 16:38:23 -08003906 // Intentionally unset the data channel type for RTP data channel. Otherwise
3907 // the RTP data channels would be successfully negotiated by default and the
3908 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3909 // We want to leave RTP data channels broken, so people won't try to use them.
3910 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3911 session_options->data_channel_type = data_channel_type();
3912 }
3913
Steve Antondcc3c022017-12-22 16:02:54 -08003914 // Apply ICE renomination flag.
3915 for (auto& options : session_options->media_description_options) {
3916 options.transport_options.enable_ice_renomination =
3917 configuration_.enable_ice_renomination;
3918 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003919
3920 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003921 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003922 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003923}
3924
Steve Antondcc3c022017-12-22 16:02:54 -08003925void PeerConnection::GetOptionsForPlanBAnswer(
3926 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003927 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003928 // Figure out transceiver directional preferences.
3929 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3930 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3931
3932 // By default, generate sendrecv/recvonly m= sections. The direction is also
3933 // restricted by the direction in the offer.
3934 bool recv_audio = true;
3935 bool recv_video = true;
3936
3937 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003938 if (offer_answer_options.offer_to_receive_audio !=
3939 RTCOfferAnswerOptions::kUndefined) {
3940 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003941 }
Steve Antondcc3c022017-12-22 16:02:54 -08003942 if (offer_answer_options.offer_to_receive_video !=
3943 RTCOfferAnswerOptions::kUndefined) {
3944 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003945 }
3946
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003947 absl::optional<size_t> audio_index;
3948 absl::optional<size_t> video_index;
3949 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003950
3951 // Generate m= sections that match those in the offer.
3952 // Note that mediasession.cc will handle intersection our preferred
3953 // direction with the offered direction.
3954 GenerateMediaDescriptionOptions(
3955 remote_description(),
3956 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3957 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3958 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003959
3960 cricket::MediaDescriptionOptions* audio_media_description_options =
3961 !audio_index ? nullptr
3962 : &session_options->media_description_options[*audio_index];
3963 cricket::MediaDescriptionOptions* video_media_description_options =
3964 !video_index ? nullptr
3965 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003966
Steve Anton4171afb2017-11-20 10:20:22 -08003967 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003968 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003969}
zhihuangaf388472016-11-02 16:49:48 -07003970
Steve Antondcc3c022017-12-22 16:02:54 -08003971void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3972 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3973 cricket::MediaSessionOptions* session_options) {
3974 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3975 // Answers) and 5.3.2 (Subsequent Answers).
3976 RTC_DCHECK(remote_description());
3977 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3978 for (const ContentInfo& content :
3979 remote_description()->description()->contents()) {
3980 cricket::MediaType media_type = content.media_description()->type();
3981 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3982 media_type == cricket::MEDIA_TYPE_VIDEO) {
3983 auto transceiver = GetAssociatedTransceiver(content.name);
3984 RTC_CHECK(transceiver);
3985 session_options->media_description_options.push_back(
3986 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3987 } else {
3988 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003989 // Reject all data sections if data channels are disabled.
3990 // Reject a data section if it has already been rejected.
3991 // Reject all data sections except for the first one.
3992 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3993 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003994 session_options->media_description_options.push_back(
3995 GetMediaDescriptionOptionsForRejectedData(content.name));
3996 } else {
3997 session_options->media_description_options.push_back(
3998 GetMediaDescriptionOptionsForActiveData(content.name));
3999 }
Steve Antondcc3c022017-12-22 16:02:54 -08004000 }
4001 }
htaa2a49d92016-03-04 02:51:39 -08004002}
4003
zhihuang1c378ed2017-08-17 14:10:50 -07004004void PeerConnection::GenerateMediaDescriptionOptions(
4005 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004006 RtpTransceiverDirection audio_direction,
4007 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004008 absl::optional<size_t>* audio_index,
4009 absl::optional<size_t>* video_index,
4010 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004011 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004012 for (const cricket::ContentInfo& content :
4013 session_desc->description()->contents()) {
4014 if (IsAudioContent(&content)) {
4015 // If we already have an audio m= section, reject this extra one.
4016 if (*audio_index) {
4017 session_options->media_description_options.push_back(
4018 cricket::MediaDescriptionOptions(
4019 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004020 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004021 } else {
4022 session_options->media_description_options.push_back(
4023 cricket::MediaDescriptionOptions(
4024 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004025 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004026 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004027 }
4028 } else if (IsVideoContent(&content)) {
4029 // If we already have an video m= section, reject this extra one.
4030 if (*video_index) {
4031 session_options->media_description_options.push_back(
4032 cricket::MediaDescriptionOptions(
4033 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004034 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004035 } else {
4036 session_options->media_description_options.push_back(
4037 cricket::MediaDescriptionOptions(
4038 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004039 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004040 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004041 }
4042 } else {
4043 RTC_DCHECK(IsDataContent(&content));
4044 // If we already have an data m= section, reject this extra one.
4045 if (*data_index) {
4046 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004047 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004048 } else {
4049 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004050 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004051 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004052 }
4053 }
htaa2a49d92016-03-04 02:51:39 -08004054 }
deadbeefab9b2d12015-10-14 11:33:11 -07004055}
4056
Steve Antonfa2260d2017-12-28 16:38:23 -08004057cricket::MediaDescriptionOptions
4058PeerConnection::GetMediaDescriptionOptionsForActiveData(
4059 const std::string& mid) const {
4060 // Direction for data sections is meaningless, but legacy endpoints might
4061 // expect sendrecv.
4062 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4063 RtpTransceiverDirection::kSendRecv,
4064 /*stopped=*/false);
4065 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4066 return options;
4067}
4068
4069cricket::MediaDescriptionOptions
4070PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4071 const std::string& mid) const {
4072 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4073 RtpTransceiverDirection::kInactive,
4074 /*stopped=*/true);
4075 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4076 return options;
4077}
4078
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004079absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004080 switch (data_channel_type_) {
4081 case cricket::DCT_RTP:
4082 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004083 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004084 }
4085 return rtp_data_channel_->content_name();
4086 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004087 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004088 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004089 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004090 }
4091}
4092
Steve Anton4171afb2017-11-20 10:20:22 -08004093void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4094 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4095 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004096 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004097}
4098
Steve Anton4171afb2017-11-20 10:20:22 -08004099void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004100 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004101 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004102 cricket::MediaType media_type,
4103 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004104 RTC_DCHECK(!IsUnifiedPlan());
4105
Steve Anton4171afb2017-11-20 10:20:22 -08004106 std::vector<RtpSenderInfo>* current_senders =
4107 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004108
Steve Anton4171afb2017-11-20 10:20:22 -08004109 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004110 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004111 for (auto sender_it = current_senders->begin();
4112 sender_it != current_senders->end();
4113 /* incremented manually */) {
4114 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004115 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004116 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004117 std::string params_stream_id;
4118 if (params) {
4119 params_stream_id =
4120 (!params->first_stream_id().empty() ? params->first_stream_id()
4121 : kDefaultStreamId);
4122 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004123 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004124 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004125 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004126 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004127 sender_exists) {
4128 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004129 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004130 OnRemoteSenderRemoved(info, media_type);
4131 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004132 }
4133 }
4134
Steve Anton4171afb2017-11-20 10:20:22 -08004135 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004136 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004137 if (!params.has_ssrcs()) {
4138 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4139 // sender, this means it is coming from a Unified Plan endpoint,so we just
4140 // create a default.
4141 default_sender_needed = true;
4142 break;
4143 }
4144
Seth Hampson845e8782018-03-02 11:34:10 -08004145 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004146 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004147 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4148 // not supported in Plan B, we just take the first here and create the
4149 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004150 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004151 (!params.first_stream_id().empty() ? params.first_stream_id()
4152 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004153 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004154 uint32_t ssrc = params.first_ssrc();
4155
4156 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004157 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004158 if (!stream) {
4159 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004160 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004161 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004162 remote_streams_->AddStream(stream);
4163 new_streams->AddStream(stream);
4164 }
4165
Steve Anton4171afb2017-11-20 10:20:22 -08004166 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004167 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004168 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004169 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004170 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004171 }
4172 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004173
Steve Anton4171afb2017-11-20 10:20:22 -08004174 // Add default sender if necessary.
4175 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004176 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004177 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004178 if (!default_stream) {
4179 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004180 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004181 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004182 remote_streams_->AddStream(default_stream);
4183 new_streams->AddStream(default_stream);
4184 }
Steve Anton4171afb2017-11-20 10:20:22 -08004185 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4186 ? kDefaultAudioSenderId
4187 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004188 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004189 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004190 if (!default_sender_info) {
4191 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004192 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004193 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004194 }
4195 }
deadbeefab9b2d12015-10-14 11:33:11 -07004196}
4197
Steve Anton4171afb2017-11-20 10:20:22 -08004198void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4199 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004200 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4201 << " receiver for track_id=" << sender_info.sender_id
4202 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004203
Steve Anton3d954a62018-04-02 11:27:23 -07004204 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004205 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004206 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004207 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004208 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004209 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004210 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004211 }
4212}
4213
Steve Anton4171afb2017-11-20 10:20:22 -08004214void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4215 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004216 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4217 << " receiver for track_id=" << sender_info.sender_id
4218 << " and stream_id=" << sender_info.stream_id;
4219
Seth Hampson845e8782018-03-02 11:34:10 -08004220 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004221
Henrik Boström933d8b02017-10-10 10:05:16 -07004222 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004223 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004224 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4225 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004226 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004227 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004228 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004229 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004230 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004231 }
4232 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004233 // Stopping or destroying a VideoRtpReceiver will end the
4234 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004235 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004236 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004237 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004238 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004239 // There's no guarantee the track is still available, e.g. the track may
4240 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004241 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004242 }
4243 } else {
nisseede5da42017-01-12 05:15:36 -08004244 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004245 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004246 if (receiver) {
4247 observer_->OnRemoveTrack(receiver);
4248 }
deadbeefab9b2d12015-10-14 11:33:11 -07004249}
4250
4251void PeerConnection::UpdateEndedRemoteMediaStreams() {
4252 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4253 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4254 MediaStreamInterface* stream = remote_streams_->at(i);
4255 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4256 streams_to_remove.push_back(stream);
4257 }
4258 }
4259
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004260 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004261 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004262 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004263 }
4264}
4265
Steve Anton4171afb2017-11-20 10:20:22 -08004266void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004267 const std::vector<cricket::StreamParams>& streams,
4268 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004269 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004270
Seth Hampson845e8782018-03-02 11:34:10 -08004271 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004272 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004273 for (auto sender_it = current_senders->begin();
4274 sender_it != current_senders->end();
4275 /* incremented manually */) {
4276 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004277 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004278 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4279 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004280 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004281 OnLocalSenderRemoved(info, media_type);
4282 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004283 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004284 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004285 }
4286 }
4287
Steve Anton4171afb2017-11-20 10:20:22 -08004288 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004289 for (const cricket::StreamParams& params : streams) {
4290 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004291 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004292 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004293 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004294 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004295 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004296 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004297 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004298 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004299 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004300 }
4301 }
4302}
4303
Steve Anton4171afb2017-11-20 10:20:22 -08004304void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4305 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004306 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004307 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004308 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004309 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4310 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004311 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004312 return;
4313 }
4314
deadbeeffac06552015-11-25 11:26:01 -08004315 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004316 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004317 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004318 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004319 }
deadbeeffac06552015-11-25 11:26:01 -08004320
Seth Hampson5b4f0752018-04-02 16:31:36 -07004321 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004322 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004323}
4324
Steve Anton4171afb2017-11-20 10:20:22 -08004325void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4326 cricket::MediaType media_type) {
4327 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004328 if (!sender) {
4329 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004330 // SessionDescriptions has been renegotiated.
4331 return;
4332 }
deadbeeffac06552015-11-25 11:26:01 -08004333
4334 // A sender has been removed from the SessionDescription but it's still
4335 // associated with the PeerConnection. This only occurs if the SDP doesn't
4336 // match with the calls to CreateSender, AddStream and RemoveStream.
4337 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004338 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004339 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004340 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004341 }
deadbeeffac06552015-11-25 11:26:01 -08004342
Steve Anton4171afb2017-11-20 10:20:22 -08004343 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004344}
4345
4346void PeerConnection::UpdateLocalRtpDataChannels(
4347 const cricket::StreamParamsVec& streams) {
4348 std::vector<std::string> existing_channels;
4349
4350 // Find new and active data channels.
4351 for (const cricket::StreamParams& params : streams) {
4352 // |it->sync_label| is actually the data channel label. The reason is that
4353 // we use the same naming of data channels as we do for
4354 // MediaStreams and Tracks.
4355 // For MediaStreams, the sync_label is the MediaStream label and the
4356 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004357 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004358 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004359 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004360 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004361 continue;
4362 }
4363 // Set the SSRC the data channel should use for sending.
4364 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4365 existing_channels.push_back(data_channel_it->first);
4366 }
4367
4368 UpdateClosingRtpDataChannels(existing_channels, true);
4369}
4370
4371void PeerConnection::UpdateRemoteRtpDataChannels(
4372 const cricket::StreamParamsVec& streams) {
4373 std::vector<std::string> existing_channels;
4374
4375 // Find new and active data channels.
4376 for (const cricket::StreamParams& params : streams) {
4377 // The data channel label is either the mslabel or the SSRC if the mslabel
4378 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004379 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004380 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004381 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004382 auto data_channel_it = rtp_data_channels_.find(label);
4383 if (data_channel_it == rtp_data_channels_.end()) {
4384 // This is a new data channel.
4385 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4386 } else {
4387 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4388 }
4389 existing_channels.push_back(label);
4390 }
4391
4392 UpdateClosingRtpDataChannels(existing_channels, false);
4393}
4394
4395void PeerConnection::UpdateClosingRtpDataChannels(
4396 const std::vector<std::string>& active_channels,
4397 bool is_local_update) {
4398 auto it = rtp_data_channels_.begin();
4399 while (it != rtp_data_channels_.end()) {
4400 DataChannel* data_channel = it->second;
4401 if (std::find(active_channels.begin(), active_channels.end(),
4402 data_channel->label()) != active_channels.end()) {
4403 ++it;
4404 continue;
4405 }
4406
4407 if (is_local_update) {
4408 data_channel->SetSendSsrc(0);
4409 } else {
4410 data_channel->RemotePeerRequestClose();
4411 }
4412
4413 if (data_channel->state() == DataChannel::kClosed) {
4414 rtp_data_channels_.erase(it);
4415 it = rtp_data_channels_.begin();
4416 } else {
4417 ++it;
4418 }
4419 }
4420}
4421
4422void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4423 uint32_t remote_ssrc) {
4424 rtc::scoped_refptr<DataChannel> channel(
4425 InternalCreateDataChannel(label, nullptr));
4426 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004427 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004428 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004429 return;
4430 }
4431 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004432 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4433 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004434 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004435}
4436
4437rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4438 const std::string& label,
4439 const InternalDataChannelInit* config) {
4440 if (IsClosed()) {
4441 return nullptr;
4442 }
Steve Anton75737c02017-11-06 10:37:17 -08004443 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004444 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004445 << "InternalCreateDataChannel: Data is not supported in this call.";
4446 return nullptr;
4447 }
4448 InternalDataChannelInit new_config =
4449 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004450 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004451 if (new_config.id < 0) {
4452 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004453 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004454 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004455 RTC_LOG(LS_ERROR)
4456 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004457 return nullptr;
4458 }
4459 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004460 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004461 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004462 return nullptr;
4463 }
4464 }
4465
Steve Anton75737c02017-11-06 10:37:17 -08004466 rtc::scoped_refptr<DataChannel> channel(
4467 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004468 if (!channel) {
4469 sid_allocator_.ReleaseSid(new_config.id);
4470 return nullptr;
4471 }
4472
4473 if (channel->data_channel_type() == cricket::DCT_RTP) {
4474 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004475 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4476 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004477 return nullptr;
4478 }
4479 rtp_data_channels_[channel->label()] = channel;
4480 } else {
4481 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4482 sctp_data_channels_.push_back(channel);
4483 channel->SignalClosed.connect(this,
4484 &PeerConnection::OnSctpDataChannelClosed);
4485 }
4486
Steve Anton2d8609c2018-01-23 16:38:46 -08004487 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004488 return channel;
4489}
4490
4491bool PeerConnection::HasDataChannels() const {
4492 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4493}
4494
4495void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4496 for (const auto& channel : sctp_data_channels_) {
4497 if (channel->id() < 0) {
4498 int sid;
4499 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004500 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004501 continue;
4502 }
4503 channel->SetSctpSid(sid);
4504 }
4505 }
4506}
4507
4508void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004509 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004510 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4511 ++it) {
4512 if (it->get() == channel) {
4513 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004514 // After the closing procedure is done, it's safe to use this ID for
4515 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004516 sid_allocator_.ReleaseSid(channel->id());
4517 }
deadbeefbd292462015-12-14 18:15:29 -08004518 // Since this method is triggered by a signal from the DataChannel,
4519 // we can't free it directly here; we need to free it asynchronously.
4520 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004521 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004522 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4523 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004524 return;
4525 }
4526 }
4527}
4528
deadbeefab9b2d12015-10-14 11:33:11 -07004529void PeerConnection::OnDataChannelDestroyed() {
4530 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4531 // DataChannel may callback to us and try to modify the list.
4532 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4533 temp_rtp_dcs.swap(rtp_data_channels_);
4534 for (const auto& kv : temp_rtp_dcs) {
4535 kv.second->OnTransportChannelDestroyed();
4536 }
4537
4538 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4539 temp_sctp_dcs.swap(sctp_data_channels_);
4540 for (const auto& channel : temp_sctp_dcs) {
4541 channel->OnTransportChannelDestroyed();
4542 }
4543}
4544
4545void PeerConnection::OnDataChannelOpenMessage(
4546 const std::string& label,
4547 const InternalDataChannelInit& config) {
4548 rtc::scoped_refptr<DataChannel> channel(
4549 InternalCreateDataChannel(label, &config));
4550 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004551 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004552 return;
4553 }
4554
deadbeefa601f5c2016-06-06 14:27:39 -07004555 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4556 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004557 observer_->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004558 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004559}
4560
Steve Anton4171afb2017-11-20 10:20:22 -08004561rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4562PeerConnection::GetAudioTransceiver() const {
4563 // This method only works with Plan B SDP, where there is a single
4564 // audio/video transceiver.
4565 RTC_DCHECK(!IsUnifiedPlan());
4566 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004567 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004568 return transceiver;
4569 }
4570 }
4571 RTC_NOTREACHED();
4572 return nullptr;
4573}
4574
4575rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4576PeerConnection::GetVideoTransceiver() const {
4577 // This method only works with Plan B SDP, where there is a single
4578 // audio/video transceiver.
4579 RTC_DCHECK(!IsUnifiedPlan());
4580 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004581 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004582 return transceiver;
4583 }
4584 }
4585 RTC_NOTREACHED();
4586 return nullptr;
4587}
4588
4589// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4590// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004591bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004592 switch (type) {
4593 case cricket::MEDIA_TYPE_AUDIO:
4594 return !GetAudioTransceiver()->internal()->senders().empty();
4595 case cricket::MEDIA_TYPE_VIDEO:
4596 return !GetVideoTransceiver()->internal()->senders().empty();
4597 case cricket::MEDIA_TYPE_DATA:
4598 return false;
4599 }
4600 RTC_NOTREACHED();
4601 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004602}
4603
Steve Anton4171afb2017-11-20 10:20:22 -08004604rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4605PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4606 for (auto transceiver : transceivers_) {
4607 for (auto sender : transceiver->internal()->senders()) {
4608 if (sender->track() == track) {
4609 return sender;
4610 }
4611 }
4612 }
4613 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004614}
4615
Steve Anton4171afb2017-11-20 10:20:22 -08004616rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4617PeerConnection::FindSenderById(const std::string& sender_id) const {
4618 for (auto transceiver : transceivers_) {
4619 for (auto sender : transceiver->internal()->senders()) {
4620 if (sender->id() == sender_id) {
4621 return sender;
4622 }
4623 }
4624 }
4625 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004626}
4627
Steve Anton4171afb2017-11-20 10:20:22 -08004628rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4629PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4630 for (auto transceiver : transceivers_) {
4631 for (auto receiver : transceiver->internal()->receivers()) {
4632 if (receiver->id() == receiver_id) {
4633 return receiver;
4634 }
4635 }
4636 }
4637 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004638}
4639
Steve Anton4171afb2017-11-20 10:20:22 -08004640std::vector<PeerConnection::RtpSenderInfo>*
4641PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4642 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4643 media_type == cricket::MEDIA_TYPE_VIDEO);
4644 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4645 ? &remote_audio_sender_infos_
4646 : &remote_video_sender_infos_;
4647}
4648
4649std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004650 cricket::MediaType media_type) {
4651 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4652 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004653 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4654 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004655}
4656
Steve Anton4171afb2017-11-20 10:20:22 -08004657const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4658 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004659 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004660 const std::string sender_id) const {
4661 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004662 if (sender_info.stream_id == stream_id &&
4663 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004664 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004665 }
4666 }
4667 return nullptr;
4668}
4669
4670DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4671 for (const auto& channel : sctp_data_channels_) {
4672 if (channel->id() == sid) {
4673 return channel;
4674 }
4675 }
4676 return nullptr;
4677}
4678
deadbeef91dd5672016-05-18 16:55:30 -07004679bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004680 const cricket::ServerAddresses& stun_servers,
4681 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004682 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004683 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004684 // To handle both internal and externally created port allocator, we will
4685 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004686 port_allocator_flags_ = port_allocator_->flags();
4687 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4688 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4689 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004690 // If the disable-IPv6 flag was specified, we'll not override it
4691 // by experiment.
4692 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004693 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004694 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4695 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004696 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004697 }
4698
zhihuangb09b3f92017-03-07 14:40:51 -08004699 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004700 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004701 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004702 }
4703
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004704 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004705 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004706 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004707 }
4708
honghaiz60347052016-05-31 18:29:12 -07004709 if (configuration.candidate_network_policy ==
4710 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004711 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004712 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004713 }
4714
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004715 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004716 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004717 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4718 }
4719
Qingsi Wanga2d60672018-04-11 16:57:45 -07004720 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004721 // No step delay is used while allocating ports.
4722 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4723 port_allocator_->set_candidate_filter(
4724 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004725 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004726
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004727 auto turn_servers_copy = turn_servers;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004728 if (tls_cert_verifier_ != nullptr) {
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004729 for (auto& turn_server : turn_servers_copy) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004730 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4731 }
4732 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004733 // Call this last since it may create pooled allocator sessions using the
4734 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004735 port_allocator_->SetConfiguration(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004736 stun_servers, turn_servers_copy, configuration.ice_candidate_pool_size,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004737 configuration.prune_turn_ports, configuration.turn_customizer,
4738 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004739 return true;
4740}
4741
deadbeef91dd5672016-05-18 16:55:30 -07004742bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004743 const cricket::ServerAddresses& stun_servers,
4744 const std::vector<cricket::RelayServerConfig>& turn_servers,
4745 IceTransportsType type,
4746 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004747 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004748 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004749 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004750 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004751 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004752 // According to JSEP, after setLocalDescription, changing the candidate pool
4753 // size is not allowed, and changing the set of ICE servers will not result
4754 // in new candidates being gathered.
4755 if (local_description()) {
4756 port_allocator_->FreezeCandidatePool();
4757 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004758 // Call this last since it may create pooled allocator sessions using the
4759 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004760 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004761 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004762 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004763}
4764
Steve Antonba818672017-11-06 10:21:57 -08004765cricket::ChannelManager* PeerConnection::channel_manager() const {
4766 return factory_->channel_manager();
4767}
4768
4769MetricsObserverInterface* PeerConnection::metrics_observer() const {
4770 return uma_observer_;
4771}
4772
Elad Alon99c3fe52017-10-13 16:29:40 +02004773bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004774 std::unique_ptr<RtcEventLogOutput> output,
4775 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004776 if (!event_log_) {
4777 return false;
4778 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004779 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004780}
4781
4782void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004783 if (event_log_) {
4784 event_log_->StopLogging();
4785 }
ivoc14d5dbe2016-07-04 07:06:55 -07004786}
nisseeaabdf62017-05-05 02:23:02 -07004787
Steve Anton75737c02017-11-06 10:37:17 -08004788cricket::BaseChannel* PeerConnection::GetChannel(
4789 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004790 for (auto transceiver : transceivers_) {
4791 cricket::BaseChannel* channel = transceiver->internal()->channel();
4792 if (channel && channel->content_name() == content_name) {
4793 return channel;
4794 }
Steve Anton75737c02017-11-06 10:37:17 -08004795 }
4796 if (rtp_data_channel() &&
4797 rtp_data_channel()->content_name() == content_name) {
4798 return rtp_data_channel();
4799 }
4800 return nullptr;
4801}
4802
4803bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4804 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004805 RTC_LOG(LS_INFO)
4806 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004807 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004808 return false;
4809 }
4810 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004811 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004812 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004813 return false;
4814 }
4815
Zhi Huange830e682018-03-30 10:48:35 -07004816 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4817 if (dtls_role) {
4818 *role = *dtls_role;
4819 return true;
4820 }
4821 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004822}
4823
4824bool PeerConnection::GetSslRole(const std::string& content_name,
4825 rtc::SSLRole* role) {
4826 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004827 RTC_LOG(LS_INFO)
4828 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004829 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004830 return false;
4831 }
4832
Zhi Huange830e682018-03-30 10:48:35 -07004833 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4834 if (dtls_role) {
4835 *role = *dtls_role;
4836 return true;
4837 }
4838 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004839}
4840
Steve Antonf8470812017-12-04 10:46:21 -08004841void PeerConnection::SetSessionError(SessionError error,
4842 const std::string& error_desc) {
4843 RTC_DCHECK_RUN_ON(signaling_thread());
4844 if (error != session_error_) {
4845 session_error_ = error;
4846 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004847 }
4848}
4849
Zhi Huange830e682018-03-30 10:48:35 -07004850RTCError PeerConnection::UpdateSessionState(
4851 SdpType type,
4852 cricket::ContentSource source,
4853 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004854 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004855
4856 // If there's already a pending error then no state transition should happen.
4857 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004858 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004859
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004860 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004861 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004862 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004863 }
4864
4865 // Update the signaling state according to the specified state machine (see
4866 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004867 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004868 ChangeSignalingState(source == cricket::CS_LOCAL
4869 ? PeerConnectionInterface::kHaveLocalOffer
4870 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004871 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004872 ChangeSignalingState(source == cricket::CS_LOCAL
4873 ? PeerConnectionInterface::kHaveLocalPrAnswer
4874 : PeerConnectionInterface::kHaveRemotePrAnswer);
4875 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004876 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004877 ChangeSignalingState(PeerConnectionInterface::kStable);
4878 }
4879
4880 // Update internal objects according to the session description's media
4881 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004882 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004883 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004884 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004885 }
4886
Steve Anton8a006912017-12-04 15:25:56 -08004887 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004888}
4889
Steve Anton8a006912017-12-04 15:25:56 -08004890RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004891 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004892 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004893 const SessionDescriptionInterface* sdesc =
4894 (source == cricket::CS_LOCAL ? local_description()
4895 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004896 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004897
4898 // Push down the new SDP media section for each audio/video transceiver.
4899 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004900 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004901 FindMediaSectionForTransceiver(transceiver, sdesc);
4902 cricket::BaseChannel* channel = transceiver->internal()->channel();
4903 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004904 continue;
4905 }
4906 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004907 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004908 if (!content_desc) {
4909 continue;
4910 }
4911 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004912 bool success = (source == cricket::CS_LOCAL)
4913 ? channel->SetLocalContent(content_desc, type, &error)
4914 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004915 if (!success) {
4916 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4917 }
4918 }
4919
4920 // If using the RtpDataChannel, push down the new SDP section for it too.
4921 if (rtp_data_channel_) {
4922 const ContentInfo* data_content =
4923 cricket::GetFirstDataContent(sdesc->description());
4924 if (data_content && !data_content->rejected) {
4925 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004926 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004927 if (data_desc) {
4928 std::string error;
4929 bool success =
4930 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004931 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004932 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004933 if (!success) {
4934 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4935 std::move(error));
4936 }
Steve Anton75737c02017-11-06 10:37:17 -08004937 }
4938 }
4939 }
Steve Antoned10bd92017-12-05 10:52:59 -08004940
Steve Anton75737c02017-11-06 10:37:17 -08004941 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4942 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4943 if (sctp_transport_ && local_description() && remote_description() &&
4944 cricket::GetFirstDataContent(local_description()->description()) &&
4945 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004946 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004947 RTC_FROM_HERE,
4948 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004949 if (!success) {
4950 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4951 "Failed to push down SCTP parameters.");
4952 }
Steve Anton75737c02017-11-06 10:37:17 -08004953 }
Steve Antoned10bd92017-12-05 10:52:59 -08004954
Steve Anton8a006912017-12-04 15:25:56 -08004955 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004956}
4957
4958bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4959 RTC_DCHECK(network_thread()->IsCurrent());
4960 RTC_DCHECK(local_description());
4961 RTC_DCHECK(remote_description());
4962 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4963 // When we support "max-message-size", that would also be pushed down here.
4964 return sctp_transport_->Start(
4965 GetSctpPort(local_description()->description()),
4966 GetSctpPort(remote_description()->description()));
4967}
4968
Steve Anton8a006912017-12-04 15:25:56 -08004969RTCError PeerConnection::PushdownTransportDescription(
4970 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004971 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004972 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004973
Zhi Huange830e682018-03-30 10:48:35 -07004974 if (source == cricket::CS_LOCAL) {
4975 const SessionDescriptionInterface* sdesc = local_description();
4976 RTC_DCHECK(sdesc);
4977 return transport_controller_->SetLocalDescription(type,
4978 sdesc->description());
4979 } else {
4980 const SessionDescriptionInterface* sdesc = remote_description();
4981 RTC_DCHECK(sdesc);
4982 return transport_controller_->SetRemoteDescription(type,
4983 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004984 }
Steve Anton75737c02017-11-06 10:37:17 -08004985}
4986
4987bool PeerConnection::GetTransportDescription(
4988 const SessionDescription* description,
4989 const std::string& content_name,
4990 cricket::TransportDescription* tdesc) {
4991 if (!description || !tdesc) {
4992 return false;
4993 }
4994 const TransportInfo* transport_info =
4995 description->GetTransportInfoByName(content_name);
4996 if (!transport_info) {
4997 return false;
4998 }
4999 *tdesc = transport_info->description;
5000 return true;
5001}
5002
Steve Anton75737c02017-11-06 10:37:17 -08005003cricket::IceConfig PeerConnection::ParseIceConfig(
5004 const PeerConnectionInterface::RTCConfiguration& config) const {
5005 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005006 switch (config.continual_gathering_policy) {
5007 case PeerConnectionInterface::GATHER_ONCE:
5008 gathering_policy = cricket::GATHER_ONCE;
5009 break;
5010 case PeerConnectionInterface::GATHER_CONTINUALLY:
5011 gathering_policy = cricket::GATHER_CONTINUALLY;
5012 break;
5013 default:
5014 RTC_NOTREACHED();
5015 gathering_policy = cricket::GATHER_ONCE;
5016 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005017
Steve Anton75737c02017-11-06 10:37:17 -08005018 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005019 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5020 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005021 ice_config.prioritize_most_likely_candidate_pairs =
5022 config.prioritize_most_likely_ice_candidate_pairs;
5023 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005024 RTCConfigurationToIceConfigOptionalInt(
5025 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005026 ice_config.continual_gathering_policy = gathering_policy;
5027 ice_config.presume_writable_when_fully_relayed =
5028 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005029 ice_config.ice_check_interval_strong_connectivity =
5030 config.ice_check_interval_strong_connectivity;
5031 ice_config.ice_check_interval_weak_connectivity =
5032 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005033 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005034 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005035 ice_config.regather_all_networks_interval_range =
5036 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005037 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005038 return ice_config;
5039}
5040
Steve Anton75737c02017-11-06 10:37:17 -08005041bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5042 std::string* track_id) {
5043 if (!local_description()) {
5044 return false;
5045 }
5046 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5047 track_id);
5048}
5049
5050bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5051 std::string* track_id) {
5052 if (!remote_description()) {
5053 return false;
5054 }
5055 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5056 track_id);
5057}
5058
5059bool PeerConnection::SendData(const cricket::SendDataParams& params,
5060 const rtc::CopyOnWriteBuffer& payload,
5061 cricket::SendDataResult* result) {
5062 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005063 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005064 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005065 return false;
5066 }
5067 return rtp_data_channel_
5068 ? rtp_data_channel_->SendData(params, payload, result)
5069 : network_thread()->Invoke<bool>(
5070 RTC_FROM_HERE,
5071 Bind(&cricket::SctpTransportInternal::SendData,
5072 sctp_transport_.get(), params, payload, result));
5073}
5074
5075bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5076 if (!rtp_data_channel_ && !sctp_transport_) {
5077 // Don't log an error here, because DataChannels are expected to call
5078 // ConnectDataChannel in this state. It's the only way to initially tell
5079 // whether or not the underlying transport is ready.
5080 return false;
5081 }
5082 if (rtp_data_channel_) {
5083 rtp_data_channel_->SignalReadyToSendData.connect(
5084 webrtc_data_channel, &DataChannel::OnChannelReady);
5085 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5086 &DataChannel::OnDataReceived);
5087 } else {
5088 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5089 &DataChannel::OnChannelReady);
5090 SignalSctpDataReceived.connect(webrtc_data_channel,
5091 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005092 SignalSctpClosingProcedureStartedRemotely.connect(
5093 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5094 SignalSctpClosingProcedureComplete.connect(
5095 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005096 }
5097 return true;
5098}
5099
5100void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5101 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005102 RTC_LOG(LS_ERROR)
5103 << "DisconnectDataChannel called when rtp_data_channel_ and "
5104 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005105 return;
5106 }
5107 if (rtp_data_channel_) {
5108 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5109 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5110 } else {
5111 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5112 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005113 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5114 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005115 }
5116}
5117
5118void PeerConnection::AddSctpDataStream(int sid) {
5119 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005120 RTC_LOG(LS_ERROR)
5121 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005122 return;
5123 }
5124 network_thread()->Invoke<void>(
5125 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5126 sctp_transport_.get(), sid));
5127}
5128
5129void PeerConnection::RemoveSctpDataStream(int sid) {
5130 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005131 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005132 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005133 return;
5134 }
5135 network_thread()->Invoke<void>(
5136 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5137 sctp_transport_.get(), sid));
5138}
5139
5140bool PeerConnection::ReadyToSendData() const {
5141 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5142 sctp_ready_to_send_data_;
5143}
5144
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005145absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005146 if (sctp_mid_ && transport_controller_) {
5147 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5148 if (dtls_transport) {
5149 return dtls_transport->transport_name();
5150 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005151 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005152 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005153 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005154}
5155
Qingsi Wang72a43a12018-02-20 16:03:18 -08005156cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5157 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005158 network_thread()->Invoke<void>(
5159 RTC_FROM_HERE,
5160 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5161 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005162 return candidate_states_list;
5163}
5164
Steve Anton5dfde182018-02-06 10:34:40 -08005165std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5166 const {
5167 std::map<std::string, std::string> transport_names_by_mid;
5168 for (auto transceiver : transceivers_) {
5169 cricket::BaseChannel* channel = transceiver->internal()->channel();
5170 if (channel) {
5171 transport_names_by_mid[channel->content_name()] =
5172 channel->transport_name();
5173 }
Steve Anton75737c02017-11-06 10:37:17 -08005174 }
Steve Anton5dfde182018-02-06 10:34:40 -08005175 if (rtp_data_channel_) {
5176 transport_names_by_mid[rtp_data_channel_->content_name()] =
5177 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005178 }
5179 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005180 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005181 RTC_DCHECK(transport_name);
5182 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005183 }
Steve Anton5dfde182018-02-06 10:34:40 -08005184 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005185}
5186
Steve Anton5dfde182018-02-06 10:34:40 -08005187std::map<std::string, cricket::TransportStats>
5188PeerConnection::GetTransportStatsByNames(
5189 const std::set<std::string>& transport_names) {
5190 if (!network_thread()->IsCurrent()) {
5191 return network_thread()
5192 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5193 RTC_FROM_HERE,
5194 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005195 }
Steve Anton5dfde182018-02-06 10:34:40 -08005196 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5197 for (const std::string& transport_name : transport_names) {
5198 cricket::TransportStats transport_stats;
5199 bool success =
5200 transport_controller_->GetStats(transport_name, &transport_stats);
5201 if (success) {
5202 transport_stats_by_name[transport_name] = std::move(transport_stats);
5203 } else {
5204 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5205 << transport_name;
5206 }
5207 }
5208 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005209}
5210
5211bool PeerConnection::GetLocalCertificate(
5212 const std::string& transport_name,
5213 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005214 if (!certificate) {
5215 return false;
5216 }
5217 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5218 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005219}
5220
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005221std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005222 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005223 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005224}
5225
5226cricket::DataChannelType PeerConnection::data_channel_type() const {
5227 return data_channel_type_;
5228}
5229
5230bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5231 return pending_ice_restarts_.find(content_name) !=
5232 pending_ice_restarts_.end();
5233}
5234
Steve Anton75737c02017-11-06 10:37:17 -08005235bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5236 return transport_controller_->NeedsIceRestart(content_name);
5237}
5238
5239void PeerConnection::OnCertificateReady(
5240 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5241 transport_controller_->SetLocalCertificate(certificate);
5242}
5243
5244void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005245 SetSessionError(SessionError::kTransport,
5246 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005247}
5248
5249void PeerConnection::OnTransportControllerConnectionState(
5250 cricket::IceConnectionState state) {
5251 switch (state) {
5252 case cricket::kIceConnectionConnecting:
5253 // If the current state is Connected or Completed, then there were
5254 // writable channels but now there are not, so the next state must
5255 // be Disconnected.
5256 // kIceConnectionConnecting is currently used as the default,
5257 // un-connected state by the TransportController, so its only use is
5258 // detecting disconnections.
5259 if (ice_connection_state_ ==
5260 PeerConnectionInterface::kIceConnectionConnected ||
5261 ice_connection_state_ ==
5262 PeerConnectionInterface::kIceConnectionCompleted) {
5263 SetIceConnectionState(
5264 PeerConnectionInterface::kIceConnectionDisconnected);
5265 }
5266 break;
5267 case cricket::kIceConnectionFailed:
5268 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5269 break;
5270 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005271 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005272 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005273 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005274 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005275 break;
5276 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005277 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005278 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005279 if (ice_connection_state_ !=
5280 PeerConnectionInterface::kIceConnectionConnected) {
5281 // If jumping directly from "checking" to "connected",
5282 // signal "connected" first.
5283 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5284 }
5285 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005286 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang78fef762018-07-11 18:33:52 +00005287 if (metrics_observer()) {
5288 ReportTransportStats();
5289 }
Steve Anton75737c02017-11-06 10:37:17 -08005290 break;
5291 default:
5292 RTC_NOTREACHED();
5293 }
5294}
5295
5296void PeerConnection::OnTransportControllerCandidatesGathered(
5297 const std::string& transport_name,
5298 const cricket::Candidates& candidates) {
5299 RTC_DCHECK(signaling_thread()->IsCurrent());
5300 int sdp_mline_index;
5301 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005302 RTC_LOG(LS_ERROR)
5303 << "OnTransportControllerCandidatesGathered: content name "
5304 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005305 return;
5306 }
5307
5308 for (cricket::Candidates::const_iterator citer = candidates.begin();
5309 citer != candidates.end(); ++citer) {
5310 // Use transport_name as the candidate media id.
5311 std::unique_ptr<JsepIceCandidate> candidate(
5312 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5313 if (local_description()) {
5314 mutable_local_description()->AddCandidate(candidate.get());
5315 }
5316 OnIceCandidate(std::move(candidate));
5317 }
5318}
5319
5320void PeerConnection::OnTransportControllerCandidatesRemoved(
5321 const std::vector<cricket::Candidate>& candidates) {
5322 RTC_DCHECK(signaling_thread()->IsCurrent());
5323 // Sanity check.
5324 for (const cricket::Candidate& candidate : candidates) {
5325 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005326 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005327 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005328 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005329 return;
5330 }
5331 }
5332
5333 if (local_description()) {
5334 mutable_local_description()->RemoveCandidates(candidates);
5335 }
5336 OnIceCandidatesRemoved(candidates);
5337}
5338
5339void PeerConnection::OnTransportControllerDtlsHandshakeError(
5340 rtc::SSLHandshakeError error) {
Qingsi Wang78fef762018-07-11 18:33:52 +00005341 if (metrics_observer()) {
5342 metrics_observer()->IncrementEnumCounter(
5343 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5344 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5345 }
Steve Anton75737c02017-11-06 10:37:17 -08005346}
5347
Steve Antoned10bd92017-12-05 10:52:59 -08005348void PeerConnection::EnableSending() {
5349 for (auto transceiver : transceivers_) {
5350 cricket::BaseChannel* channel = transceiver->internal()->channel();
5351 if (channel && !channel->enabled()) {
5352 channel->Enable(true);
5353 }
Steve Anton75737c02017-11-06 10:37:17 -08005354 }
5355
Steve Anton4171afb2017-11-20 10:20:22 -08005356 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005357 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005358 }
Steve Anton75737c02017-11-06 10:37:17 -08005359}
5360
5361// Returns the media index for a local ice candidate given the content name.
5362bool PeerConnection::GetLocalCandidateMediaIndex(
5363 const std::string& content_name,
5364 int* sdp_mline_index) {
5365 if (!local_description() || !sdp_mline_index) {
5366 return false;
5367 }
5368
5369 bool content_found = false;
5370 const ContentInfos& contents = local_description()->description()->contents();
5371 for (size_t index = 0; index < contents.size(); ++index) {
5372 if (contents[index].name == content_name) {
5373 *sdp_mline_index = static_cast<int>(index);
5374 content_found = true;
5375 break;
5376 }
5377 }
5378 return content_found;
5379}
5380
5381bool PeerConnection::UseCandidatesInSessionDescription(
5382 const SessionDescriptionInterface* remote_desc) {
5383 if (!remote_desc) {
5384 return true;
5385 }
5386 bool ret = true;
5387
5388 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5389 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5390 for (size_t n = 0; n < candidates->count(); ++n) {
5391 const IceCandidateInterface* candidate = candidates->at(n);
5392 bool valid = false;
5393 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5394 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005395 RTC_LOG(LS_INFO)
5396 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005397 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005398 }
5399 continue;
5400 }
5401 ret = UseCandidate(candidate);
5402 if (!ret) {
5403 break;
5404 }
5405 }
5406 }
5407 return ret;
5408}
5409
5410bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5411 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5412 size_t remote_content_size =
5413 remote_description()->description()->contents().size();
5414 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005415 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005416 return false;
5417 }
5418
5419 cricket::ContentInfo content =
5420 remote_description()->description()->contents()[mediacontent_index];
5421 std::vector<cricket::Candidate> candidates;
5422 candidates.push_back(candidate->candidate());
5423 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005424 RTCError error =
5425 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005426 if (error.ok()) {
5427 // Candidates successfully submitted for checking.
5428 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5429 ice_connection_state_ ==
5430 PeerConnectionInterface::kIceConnectionDisconnected) {
5431 // If state is New, then the session has just gotten its first remote ICE
5432 // candidates, so go to Checking.
5433 // If state is Disconnected, the session is re-using old candidates or
5434 // receiving additional ones, so go to Checking.
5435 // If state is Connected, stay Connected.
5436 // TODO(bemasc): If state is Connected, and the new candidates are for a
5437 // newly added transport, then the state actually _should_ move to
5438 // checking. Add a way to distinguish that case.
5439 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5440 }
5441 // TODO(bemasc): If state is Completed, go back to Connected.
5442 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005443 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005444 }
5445 return true;
5446}
5447
5448void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005449 // Destroy video channel first since it may have a pointer to the
5450 // voice channel.
5451 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005452 if (!video_info || video_info->rejected) {
5453 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005454 }
5455
Steve Anton6fec8802017-12-04 10:37:29 -08005456 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5457 if (!audio_info || audio_info->rejected) {
5458 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005459 }
5460
5461 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5462 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005463 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005464 }
5465}
5466
Steve Antondcc3c022017-12-22 16:02:54 -08005467RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5468 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005469 const cricket::ContentGroup* bundle_group = nullptr;
5470 if (configuration_.bundle_policy ==
5471 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005472 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005473 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005474 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5475 "max-bundle configured but session description "
5476 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005477 }
5478 }
Steve Antondcc3c022017-12-22 16:02:54 -08005479 return std::move(bundle_group);
5480}
5481
5482RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005483 // Creating the media channels. Transports should already have been created
5484 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005485 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005486 if (voice && !voice->rejected &&
5487 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005488 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005489 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005490 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5491 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005492 }
5493 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5494 }
5495
Steve Antondcc3c022017-12-22 16:02:54 -08005496 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005497 if (video && !video->rejected &&
5498 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005499 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005500 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005501 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5502 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005503 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005504 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005505 }
5506
Steve Antondcc3c022017-12-22 16:02:54 -08005507 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005508 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5509 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005510 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005511 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5512 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005513 }
5514 }
5515
Steve Anton8a006912017-12-04 15:25:56 -08005516 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005517}
5518
Steve Anton4171afb2017-11-20 10:20:22 -08005519// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005520cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005521 const std::string& mid) {
5522 RtpTransportInternal* rtp_transport =
5523 transport_controller_->GetRtpTransport(mid);
5524 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005525 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005526 call_.get(), configuration_.media_config, rtp_transport,
5527 signaling_thread(), mid, SrtpRequired(),
5528 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005529 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005530 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005531 }
Steve Anton75737c02017-11-06 10:37:17 -08005532 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5533 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005534 voice_channel->SignalSentPacket.connect(this,
5535 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005536 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005537 if (uma_observer_) {
5538 voice_channel->SetMetricsObserver(uma_observer_);
5539 }
Steve Anton4171afb2017-11-20 10:20:22 -08005540
Steve Antoneda6ccd2017-12-04 10:21:55 -08005541 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005542}
5543
Steve Anton4171afb2017-11-20 10:20:22 -08005544// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005545cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005546 const std::string& mid) {
5547 RtpTransportInternal* rtp_transport =
5548 transport_controller_->GetRtpTransport(mid);
5549 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005550 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005551 call_.get(), configuration_.media_config, rtp_transport,
5552 signaling_thread(), mid, SrtpRequired(),
5553 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005554 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005555 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005556 }
Steve Anton75737c02017-11-06 10:37:17 -08005557 video_channel->SignalDtlsSrtpSetupFailure.connect(
5558 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005559 video_channel->SignalSentPacket.connect(this,
5560 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005561 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005562 if (uma_observer_) {
5563 video_channel->SetMetricsObserver(uma_observer_);
5564 }
Steve Anton4171afb2017-11-20 10:20:22 -08005565
Steve Antoneda6ccd2017-12-04 10:21:55 -08005566 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005567}
5568
Zhi Huange830e682018-03-30 10:48:35 -07005569bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005570 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5571 if (sctp) {
5572 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005573 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005574 << "Trying to create SCTP transport, but didn't compile with "
5575 "SCTP support (HAVE_SCTP)";
5576 return false;
5577 }
5578 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005579 RTC_FROM_HERE,
5580 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005581 return false;
5582 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005583 for (const auto& channel : sctp_data_channels_) {
5584 channel->OnTransportChannelCreated();
5585 }
Steve Anton75737c02017-11-06 10:37:17 -08005586 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005587 RtpTransportInternal* rtp_transport =
5588 transport_controller_->GetRtpTransport(mid);
5589 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005590 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005591 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5592 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005593 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005594 return false;
5595 }
Steve Anton75737c02017-11-06 10:37:17 -08005596 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5597 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5598 rtp_data_channel_->SignalSentPacket.connect(
5599 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005600 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005601 if (uma_observer_) {
5602 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5603 }
Steve Anton75737c02017-11-06 10:37:17 -08005604 }
5605
Steve Anton75737c02017-11-06 10:37:17 -08005606 return true;
5607}
5608
5609Call::Stats PeerConnection::GetCallStats() {
5610 if (!worker_thread()->IsCurrent()) {
5611 return worker_thread()->Invoke<Call::Stats>(
5612 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5613 }
5614 if (call_) {
5615 return call_->GetStats();
5616 } else {
5617 return Call::Stats();
5618 }
5619}
5620
Zhi Huange830e682018-03-30 10:48:35 -07005621bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005622 RTC_DCHECK(network_thread()->IsCurrent());
5623 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005624 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005625 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005626 RTC_DCHECK(dtls_transport);
5627 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005628 RTC_DCHECK(sctp_transport_);
5629 sctp_invoker_.reset(new rtc::AsyncInvoker());
5630 sctp_transport_->SignalReadyToSendData.connect(
5631 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5632 sctp_transport_->SignalDataReceived.connect(
5633 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005634 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5635 // another thread. Would be nice if there was a helper class similar to
5636 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5637 // code.
5638 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5639 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5640 sctp_transport_->SignalClosingProcedureComplete.connect(
5641 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005642 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005643 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005644 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005645}
5646
5647void PeerConnection::DestroySctpTransport_n() {
5648 RTC_DCHECK(network_thread()->IsCurrent());
5649 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005650 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005651 sctp_invoker_.reset(nullptr);
5652 sctp_ready_to_send_data_ = false;
5653}
5654
5655void PeerConnection::OnSctpTransportReadyToSendData_n() {
5656 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5657 RTC_DCHECK(network_thread()->IsCurrent());
5658 // Note: Cannot use rtc::Bind here because it will grab a reference to
5659 // PeerConnection and potentially cause PeerConnection to live longer than
5660 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5661 // be destroyed before PeerConnection is destroyed, and at that point all
5662 // pending tasks will be cleared.
5663 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5664 OnSctpTransportReadyToSendData_s(true);
5665 });
5666}
5667
5668void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5669 RTC_DCHECK(signaling_thread()->IsCurrent());
5670 sctp_ready_to_send_data_ = ready;
5671 SignalSctpReadyToSendData(ready);
5672}
5673
5674void PeerConnection::OnSctpTransportDataReceived_n(
5675 const cricket::ReceiveDataParams& params,
5676 const rtc::CopyOnWriteBuffer& payload) {
5677 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5678 RTC_DCHECK(network_thread()->IsCurrent());
5679 // Note: Cannot use rtc::Bind here because it will grab a reference to
5680 // PeerConnection and potentially cause PeerConnection to live longer than
5681 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5682 // be destroyed before PeerConnection is destroyed, and at that point all
5683 // pending tasks will be cleared.
5684 sctp_invoker_->AsyncInvoke<void>(
5685 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5686 OnSctpTransportDataReceived_s(params, payload);
5687 });
5688}
5689
5690void PeerConnection::OnSctpTransportDataReceived_s(
5691 const cricket::ReceiveDataParams& params,
5692 const rtc::CopyOnWriteBuffer& payload) {
5693 RTC_DCHECK(signaling_thread()->IsCurrent());
5694 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5695 // Received OPEN message; parse and signal that a new data channel should
5696 // be created.
5697 std::string label;
5698 InternalDataChannelInit config;
5699 config.id = params.ssrc;
5700 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005701 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5702 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005703 return;
5704 }
5705 config.open_handshake_role = InternalDataChannelInit::kAcker;
5706 OnDataChannelOpenMessage(label, config);
5707 } else {
5708 // Otherwise just forward the signal.
5709 SignalSctpDataReceived(params, payload);
5710 }
5711}
5712
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005713void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005714 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5715 RTC_DCHECK(network_thread()->IsCurrent());
5716 sctp_invoker_->AsyncInvoke<void>(
5717 RTC_FROM_HERE, signaling_thread(),
5718 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005719 &SignalSctpClosingProcedureStartedRemotely, sid));
5720}
5721
5722void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5723 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5724 RTC_DCHECK(network_thread()->IsCurrent());
5725 sctp_invoker_->AsyncInvoke<void>(
5726 RTC_FROM_HERE, signaling_thread(),
5727 rtc::Bind(&sigslot::signal1<int>::operator(),
5728 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005729}
5730
5731// Returns false if bundle is enabled and rtcp_mux is disabled.
5732bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5733 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5734 if (!bundle_enabled)
5735 return true;
5736
5737 const cricket::ContentGroup* bundle_group =
5738 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5739 RTC_DCHECK(bundle_group != NULL);
5740
5741 const cricket::ContentInfos& contents = desc->contents();
5742 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5743 citer != contents.end(); ++citer) {
5744 const cricket::ContentInfo* content = (&*citer);
5745 RTC_DCHECK(content != NULL);
5746 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005747 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005748 if (!HasRtcpMuxEnabled(content))
5749 return false;
5750 }
5751 }
5752 // RTCP-MUX is enabled in all the contents.
5753 return true;
5754}
5755
5756bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005757 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005758}
5759
Steve Anton8a006912017-12-04 15:25:56 -08005760RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005761 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005762 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005763 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005764 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005765 }
5766
5767 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005768 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005769 }
5770
Steve Anton3828c062017-12-06 10:34:51 -08005771 SdpType type = sdesc->GetType();
5772 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5773 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005774 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005775 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005776 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005777 }
5778
5779 // Verify crypto settings.
5780 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005781 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5782 dtls_enabled_) {
Qingsi Wang78fef762018-07-11 18:33:52 +00005783 RTCError crypto_error =
5784 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005785 if (!crypto_error.ok()) {
5786 return crypto_error;
5787 }
Steve Anton75737c02017-11-06 10:37:17 -08005788 }
5789
5790 // Verify ice-ufrag and ice-pwd.
5791 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005792 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5793 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005794 }
5795
5796 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005797 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5798 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005799 }
5800
5801 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5802 // m-lines that do not rtcp-mux enabled.
5803
5804 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005805 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005806 // With an answer we want to compare the new answer session description with
5807 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005808 const cricket::SessionDescription* offer_desc =
5809 (source == cricket::CS_LOCAL) ? remote_description()->description()
5810 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005811 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5812 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5813 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005814 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5815 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005816 }
5817 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005818 // The re-offers should respect the order of m= sections in current
5819 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005820 // With a re-offer, either the current local or current remote descriptions
5821 // could be the most up to date, so we would like to check against both of
5822 // them if they exist. It could be the case that one of them has a 0 port
5823 // for a media section, but the other does not. This is important to check
5824 // against in the case that we are recycling an m= section.
5825 const cricket::SessionDescription* current_desc = nullptr;
5826 const cricket::SessionDescription* secondary_current_desc = nullptr;
5827 if (local_description()) {
5828 current_desc = local_description()->description();
5829 if (remote_description()) {
5830 secondary_current_desc = remote_description()->description();
5831 }
5832 } else if (remote_description()) {
5833 current_desc = remote_description()->description();
5834 }
Steve Anton75737c02017-11-06 10:37:17 -08005835 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005836 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5837 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005838 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5839 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005840 }
5841 }
5842
Steve Antonba42e992018-04-09 14:10:01 -07005843 if (IsUnifiedPlan()) {
5844 // Ensure that each audio and video media section has at most one
5845 // "StreamParams". This will return an error if receiving a session
5846 // description from a "Plan B" endpoint which adds multiple tracks of the
5847 // same type. With Unified Plan, there can only be at most one track per
5848 // media section.
5849 for (const ContentInfo& content : sdesc->description()->contents()) {
5850 const MediaContentDescription& desc = *content.description;
5851 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5852 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5853 desc.streams().size() > 1u) {
5854 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5855 "Media section has more than one track specified "
5856 "with a=ssrc lines which is not supported with "
5857 "Unified Plan.");
5858 }
5859 }
5860 }
5861
Steve Anton8a006912017-12-04 15:25:56 -08005862 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005863}
5864
Steve Anton3828c062017-12-06 10:34:51 -08005865bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005866 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005867 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005868 return (state == PeerConnectionInterface::kStable) ||
5869 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005870 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005871 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005872 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5873 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5874 }
5875}
5876
Steve Anton3828c062017-12-06 10:34:51 -08005877bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005878 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005879 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005880 return (state == PeerConnectionInterface::kStable) ||
5881 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005882 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005883 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005884 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5885 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5886 }
5887}
5888
Steve Antonf8470812017-12-04 10:46:21 -08005889const char* PeerConnection::SessionErrorToString(SessionError error) const {
5890 switch (error) {
5891 case SessionError::kNone:
5892 return "ERROR_NONE";
5893 case SessionError::kContent:
5894 return "ERROR_CONTENT";
5895 case SessionError::kTransport:
5896 return "ERROR_TRANSPORT";
5897 }
5898 RTC_NOTREACHED();
5899 return "";
5900}
5901
Steve Anton75737c02017-11-06 10:37:17 -08005902std::string PeerConnection::GetSessionErrorMsg() {
5903 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005904 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5905 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005906 return desc.str();
5907}
5908
Steve Anton8e20f172018-03-06 10:55:04 -08005909void PeerConnection::ReportSdpFormatReceived(
5910 const SessionDescriptionInterface& remote_offer) {
Qingsi Wang78fef762018-07-11 18:33:52 +00005911 if (!uma_observer_) {
5912 return;
5913 }
Steve Anton8e20f172018-03-06 10:55:04 -08005914 int num_audio_mlines = 0;
5915 int num_video_mlines = 0;
5916 int num_audio_tracks = 0;
5917 int num_video_tracks = 0;
5918 for (const ContentInfo& content : remote_offer.description()->contents()) {
5919 cricket::MediaType media_type = content.media_description()->type();
5920 int num_tracks = std::max(
5921 1, static_cast<int>(content.media_description()->streams().size()));
5922 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5923 num_audio_mlines += 1;
5924 num_audio_tracks += num_tracks;
5925 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5926 num_video_mlines += 1;
5927 num_video_tracks += num_tracks;
5928 }
5929 }
5930 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5931 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5932 format = kSdpFormatReceivedComplexUnifiedPlan;
5933 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5934 format = kSdpFormatReceivedComplexPlanB;
5935 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5936 format = kSdpFormatReceivedSimple;
5937 }
Qingsi Wang78fef762018-07-11 18:33:52 +00005938 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5939 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005940}
5941
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005942void PeerConnection::NoteUsageEvent(UsageEvent event) {
5943 RTC_DCHECK_RUN_ON(signaling_thread());
5944 usage_event_accumulator_ |= static_cast<int>(event);
5945}
5946
5947void PeerConnection::ReportUsagePattern() const {
5948 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang78fef762018-07-11 18:33:52 +00005949 if (uma_observer_) {
5950 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5951 usage_event_accumulator_);
5952 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005953}
5954
Steve Anton0ffaaa22018-02-23 10:31:30 -08005955void PeerConnection::ReportNegotiatedSdpSemantics(
5956 const SessionDescriptionInterface& answer) {
Qingsi Wang78fef762018-07-11 18:33:52 +00005957 if (!uma_observer_) {
5958 return;
5959 }
Steve Anton0ffaaa22018-02-23 10:31:30 -08005960 switch (answer.description()->msid_signaling()) {
5961 case 0:
Qingsi Wang78fef762018-07-11 18:33:52 +00005962 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5963 kSdpSemanticNegotiatedNone,
5964 kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005965 break;
5966 case cricket::kMsidSignalingMediaSection:
Qingsi Wang78fef762018-07-11 18:33:52 +00005967 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5968 kSdpSemanticNegotiatedUnifiedPlan,
5969 kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005970 break;
5971 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang78fef762018-07-11 18:33:52 +00005972 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5973 kSdpSemanticNegotiatedPlanB,
5974 kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005975 break;
5976 case cricket::kMsidSignalingMediaSection |
5977 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang78fef762018-07-11 18:33:52 +00005978 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5979 kSdpSemanticNegotiatedMixed,
5980 kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005981 break;
5982 default:
5983 RTC_NOTREACHED();
5984 }
5985}
5986
Steve Anton75737c02017-11-06 10:37:17 -08005987// We need to check the local/remote description for the Transport instead of
5988// the session, because a new Transport added during renegotiation may have
5989// them unset while the session has them set from the previous negotiation.
5990// Not doing so may trigger the auto generation of transport description and
5991// mess up DTLS identity information, ICE credential, etc.
5992bool PeerConnection::ReadyToUseRemoteCandidate(
5993 const IceCandidateInterface* candidate,
5994 const SessionDescriptionInterface* remote_desc,
5995 bool* valid) {
5996 *valid = true;
5997
5998 const SessionDescriptionInterface* current_remote_desc =
5999 remote_desc ? remote_desc : remote_description();
6000
6001 if (!current_remote_desc) {
6002 return false;
6003 }
6004
6005 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6006 size_t remote_content_size =
6007 current_remote_desc->description()->contents().size();
6008 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006009 RTC_LOG(LS_ERROR)
6010 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6011 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006012
6013 *valid = false;
6014 return false;
6015 }
6016
6017 cricket::ContentInfo content =
6018 current_remote_desc->description()->contents()[mediacontent_index];
6019
6020 const std::string transport_name = GetTransportName(content.name);
6021 if (transport_name.empty()) {
6022 return false;
6023 }
Zhi Huange830e682018-03-30 10:48:35 -07006024 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006025}
6026
6027bool PeerConnection::SrtpRequired() const {
6028 return dtls_enabled_ ||
6029 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6030}
6031
6032void PeerConnection::OnTransportControllerGatheringState(
6033 cricket::IceGatheringState state) {
6034 RTC_DCHECK(signaling_thread()->IsCurrent());
6035 if (state == cricket::kIceGatheringGathering) {
6036 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6037 } else if (state == cricket::kIceGatheringComplete) {
6038 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6039 }
6040}
6041
6042void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006043 std::map<std::string, std::set<cricket::MediaType>>
6044 media_types_by_transport_name;
6045 for (auto transceiver : transceivers_) {
6046 if (transceiver->internal()->channel()) {
6047 const std::string& transport_name =
6048 transceiver->internal()->channel()->transport_name();
6049 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006050 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006051 }
Steve Anton75737c02017-11-06 10:37:17 -08006052 }
6053 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006054 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6055 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006056 }
Zhi Huange830e682018-03-30 10:48:35 -07006057
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006058 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006059 if (transport_name) {
6060 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006061 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006062 }
Zhi Huange830e682018-03-30 10:48:35 -07006063
Steve Antonc7b964c2018-02-01 14:39:45 -08006064 for (const auto& entry : media_types_by_transport_name) {
6065 const std::string& transport_name = entry.first;
6066 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006067 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006068 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006069 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006070 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006071 }
6072 }
6073}
6074// Walk through the ConnectionInfos to gather best connection usage
6075// for IPv4 and IPv6.
6076void PeerConnection::ReportBestConnectionState(
6077 const cricket::TransportStats& stats) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006078 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006079 for (const cricket::TransportChannelStats& channel_stats :
6080 stats.channel_stats) {
6081 for (const cricket::ConnectionInfo& connection_info :
6082 channel_stats.connection_infos) {
6083 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006084 continue;
6085 }
6086
Qingsi Wang78fef762018-07-11 18:33:52 +00006087 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006088 const cricket::Candidate& local = connection_info.local_candidate;
6089 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006090
6091 // Increment the counter for IceCandidatePairType.
6092 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6093 (local.type() == RELAY_PORT_TYPE &&
6094 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006095 type = kEnumCounterIceCandidatePairTypeTcp;
Steve Anton75737c02017-11-06 10:37:17 -08006096 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006097 type = kEnumCounterIceCandidatePairTypeUdp;
Steve Anton75737c02017-11-06 10:37:17 -08006098 } else {
6099 RTC_CHECK(0);
6100 }
Qingsi Wang78fef762018-07-11 18:33:52 +00006101 metrics_observer()->IncrementEnumCounter(
6102 type, GetIceCandidatePairCounter(local, remote),
6103 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006104
6105 // Increment the counter for IP type.
6106 if (local.address().family() == AF_INET) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006107 metrics_observer()->IncrementEnumCounter(
6108 kEnumCounterAddressFamily, kBestConnections_IPv4,
6109 kPeerConnectionAddressFamilyCounter_Max);
6110
Steve Anton75737c02017-11-06 10:37:17 -08006111 } else if (local.address().family() == AF_INET6) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006112 metrics_observer()->IncrementEnumCounter(
6113 kEnumCounterAddressFamily, kBestConnections_IPv6,
6114 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006115 } else {
6116 RTC_CHECK(0);
6117 }
6118
6119 return;
6120 }
6121 }
6122}
6123
6124void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006125 const cricket::TransportStats& stats,
6126 const std::set<cricket::MediaType>& media_types) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006127 RTC_DCHECK(metrics_observer());
Steve Anton75737c02017-11-06 10:37:17 -08006128 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6129 return;
6130 }
6131
6132 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6133 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6134 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6135 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6136 return;
6137 }
6138
Qingsi Wang78fef762018-07-11 18:33:52 +00006139 for (cricket::MediaType media_type : media_types) {
6140 PeerConnectionEnumCounterType srtp_counter_type;
6141 PeerConnectionEnumCounterType ssl_counter_type;
6142 switch (media_type) {
6143 case cricket::MEDIA_TYPE_AUDIO:
6144 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6145 ssl_counter_type = kEnumCounterAudioSslCipher;
6146 break;
6147 case cricket::MEDIA_TYPE_VIDEO:
6148 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6149 ssl_counter_type = kEnumCounterVideoSslCipher;
6150 break;
6151 case cricket::MEDIA_TYPE_DATA:
6152 srtp_counter_type = kEnumCounterDataSrtpCipher;
6153 ssl_counter_type = kEnumCounterDataSslCipher;
6154 break;
6155 default:
6156 RTC_NOTREACHED();
6157 continue;
Steve Antonc7b964c2018-02-01 14:39:45 -08006158 }
Qingsi Wang78fef762018-07-11 18:33:52 +00006159 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6160 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6161 srtp_crypto_suite);
6162 }
6163 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6164 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6165 ssl_cipher_suite);
Steve Antonc7b964c2018-02-01 14:39:45 -08006166 }
Steve Anton75737c02017-11-06 10:37:17 -08006167 }
6168}
6169
6170void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6171 RTC_DCHECK(worker_thread()->IsCurrent());
6172 RTC_DCHECK(call_);
6173 call_->OnSentPacket(sent_packet);
6174}
6175
6176const std::string PeerConnection::GetTransportName(
6177 const std::string& content_name) {
6178 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006179 if (channel) {
6180 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006181 }
Steve Anton6fec8802017-12-04 10:37:29 -08006182 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006183 RTC_DCHECK(sctp_mid_);
6184 if (content_name == *sctp_mid_) {
6185 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006186 }
6187 }
6188 // Return an empty string if failed to retrieve the transport name.
6189 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006190}
6191
Steve Anton6fec8802017-12-04 10:37:29 -08006192void PeerConnection::DestroyTransceiverChannel(
6193 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6194 transceiver) {
6195 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006196
Steve Anton6fec8802017-12-04 10:37:29 -08006197 cricket::BaseChannel* channel = transceiver->internal()->channel();
6198 if (channel) {
6199 transceiver->internal()->SetChannel(nullptr);
6200 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006201 }
6202}
6203
6204void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006205 if (rtp_data_channel_) {
6206 OnDataChannelDestroyed();
6207 DestroyBaseChannel(rtp_data_channel_);
6208 rtp_data_channel_ = nullptr;
6209 }
6210
6211 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6212 // grab a reference to this PeerConnection. If this is called from the
6213 // PeerConnection destructor, the RefCountedObject vtable will have already
6214 // been destroyed (since it is a subclass of PeerConnection) and using
6215 // rtc::Bind will cause "Pure virtual function called" error to appear.
6216
6217 if (sctp_transport_) {
6218 OnDataChannelDestroyed();
6219 network_thread()->Invoke<void>(RTC_FROM_HERE,
6220 [this] { DestroySctpTransport_n(); });
6221 }
6222}
6223
6224void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6225 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006226 switch (channel->media_type()) {
6227 case cricket::MEDIA_TYPE_AUDIO:
6228 channel_manager()->DestroyVoiceChannel(
6229 static_cast<cricket::VoiceChannel*>(channel));
6230 break;
6231 case cricket::MEDIA_TYPE_VIDEO:
6232 channel_manager()->DestroyVideoChannel(
6233 static_cast<cricket::VideoChannel*>(channel));
6234 break;
6235 case cricket::MEDIA_TYPE_DATA:
6236 channel_manager()->DestroyRtpDataChannel(
6237 static_cast<cricket::RtpDataChannel*>(channel));
6238 break;
6239 default:
6240 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6241 break;
6242 }
Zhi Huange830e682018-03-30 10:48:35 -07006243}
Steve Anton6fec8802017-12-04 10:37:29 -08006244
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006245bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006246 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006247 RtpTransportInternal* rtp_transport,
6248 cricket::DtlsTransportInternal* dtls_transport) {
6249 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006250 auto base_channel = GetChannel(mid);
6251 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006252 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006253 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006254 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006255 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006256 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006257 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006258}
6259
Harald Alvestrand89061872018-01-02 14:08:34 +01006260void PeerConnection::ClearStatsCache() {
6261 if (stats_collector_) {
6262 stats_collector_->ClearCachedStatsReport();
6263 }
6264}
6265
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006266} // namespace webrtc