blob: db18ca3aa96918ff76d11400ab1f54dd909b9360 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/jsepicecandidate.h"
21#include "api/jsepsessiondescription.h"
22#include "api/mediaconstraintsinterface.h"
23#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
25#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080026#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020027#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080031#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080037#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080040#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080041#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010048#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020049#include "rtc_base/ptr_util.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
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100386void 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);
395 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()) {
413 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
414 it->second,
415 kEnumCounterKeyProtocolMediaTypeMax);
416 }
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.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100425RTCError 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,
437 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
deadbeef91dd5672016-05-18 16:55:30 -0700916 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700917 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700918 if (!network_thread()->Invoke<bool>(
919 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
920 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921 return false;
922 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923
Zhi Huange830e682018-03-30 10:48:35 -0700924 const PeerConnectionFactoryInterface::Options& options = factory_->options();
925
Steve Anton75737c02017-11-06 10:37:17 -0800926 // RFC 3264: The numeric value of the session id and version in the
927 // o line MUST be representable with a "64 bit signed integer".
928 // Due to this constraint session id |session_id_| is max limited to
929 // LLONG_MAX.
930 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700931 JsepTransportController::Config config;
932 config.redetermine_role_on_ice_restart =
933 configuration.redetermine_role_on_ice_restart;
934 config.ssl_max_version = factory_->options().ssl_max_version;
935 config.disable_encryption = options.disable_encryption;
936 config.bundle_policy = configuration.bundle_policy;
937 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
938 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700939 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700940 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700941#if defined(ENABLE_EXTERNAL_AUTH)
942 config.enable_external_auth = true;
943#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700944 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700945 transport_controller_.reset(new JsepTransportController(
946 signaling_thread(), network_thread(), port_allocator_.get(), config));
947 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800948 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700949 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800950 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700951 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800952 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700953 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800954 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
955 transport_controller_->SignalDtlsHandshakeError.connect(
956 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
957
958 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700959
deadbeefab9b2d12015-10-14 11:33:11 -0700960 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700961 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962
Steve Antonba818672017-11-06 10:21:57 -0800963 configuration_ = configuration;
964
Steve Anton75737c02017-11-06 10:37:17 -0800965 // Obtain a certificate from RTCConfiguration if any were provided (optional).
966 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
967 if (!configuration.certificates.empty()) {
968 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
969 // just picking the first one. The decision should be made based on the DTLS
970 // handshake. The DTLS negotiations need to know about all certificates.
971 certificate = configuration.certificates[0];
972 }
973
Steve Antond25da372017-11-06 14:50:29 -0800974 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800975
976 if (options.disable_encryption) {
977 dtls_enabled_ = false;
978 } else {
979 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700980 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800981 // |configuration| can override the default |dtls_enabled_| value.
982 if (configuration.enable_dtls_srtp) {
983 dtls_enabled_ = *(configuration.enable_dtls_srtp);
984 }
985 }
986
987 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
988 // It takes precendence over the disable_sctp_data_channels
989 // PeerConnectionFactoryInterface::Options.
990 if (configuration.enable_rtp_data_channel) {
991 data_channel_type_ = cricket::DCT_RTP;
992 } else {
993 // DTLS has to be enabled to use SCTP.
994 if (!options.disable_sctp_data_channels && dtls_enabled_) {
995 data_channel_type_ = cricket::DCT_SCTP;
996 }
997 }
998
999 video_options_.screencast_min_bitrate_kbps =
1000 configuration.screencast_min_bitrate;
1001 audio_options_.combined_audio_video_bwe =
1002 configuration.combined_audio_video_bwe;
1003
1004 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001005 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001006
1007 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001008 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001009
1010 // Whether the certificate generator/certificate is null or not determines
1011 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1012 // the right instructions by clearing the variables if needed.
1013 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001014 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001015 certificate = nullptr;
1016 } else if (certificate) {
1017 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001018 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001019 }
1020
1021 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1022 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001023 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001024 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1025 this, &PeerConnection::OnCertificateReady);
1026
1027 if (options.disable_encryption) {
1028 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1029 }
1030
1031 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1032 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033
Steve Anton4171afb2017-11-20 10:20:22 -08001034 // Add default audio/video transceivers for Plan B SDP.
1035 if (!IsUnifiedPlan()) {
1036 transceivers_.push_back(
1037 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1038 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1039 transceivers_.push_back(
1040 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1041 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1042 }
Harald Alvestrand19793842018-06-25 12:03:50 +02001043 signaling_thread()->PostDelayed(
1044 RTC_FROM_HERE,
1045 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS, this,
1046 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001047 return true;
1048}
1049
Steve Anton038834f2017-07-14 15:59:59 -07001050RTCError PeerConnection::ValidateConfiguration(
1051 const RTCConfiguration& config) const {
1052 if (config.ice_regather_interval_range &&
1053 config.continual_gathering_policy == GATHER_ONCE) {
1054 return RTCError(RTCErrorType::INVALID_PARAMETER,
1055 "ice_regather_interval_range specified but continual "
1056 "gathering policy is GATHER_ONCE");
1057 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001058 auto result =
1059 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1060 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001061}
1062
Yves Gerey665174f2018-06-19 15:03:05 +02001063rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001064 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1065 "Plan SdpSemantics. Please use GetSenders "
1066 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001067 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068}
1069
Yves Gerey665174f2018-06-19 15:03:05 +02001070rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001071 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1072 "Plan SdpSemantics. Please use GetReceivers "
1073 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001074 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075}
1076
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001077bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001078 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1079 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001080 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 if (IsClosed()) {
1082 return false;
1083 }
deadbeefab9b2d12015-10-14 11:33:11 -07001084 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085 return false;
1086 }
deadbeefab9b2d12015-10-14 11:33:11 -07001087
1088 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001089 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1090 observer->SignalAudioTrackAdded.connect(this,
1091 &PeerConnection::OnAudioTrackAdded);
1092 observer->SignalAudioTrackRemoved.connect(
1093 this, &PeerConnection::OnAudioTrackRemoved);
1094 observer->SignalVideoTrackAdded.connect(this,
1095 &PeerConnection::OnVideoTrackAdded);
1096 observer->SignalVideoTrackRemoved.connect(
1097 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001098 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001099
deadbeefab9b2d12015-10-14 11:33:11 -07001100 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001101 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001102 }
1103 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001104 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001105 }
1106
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001107 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001108 observer_->OnRenegotiationNeeded();
1109 return true;
1110}
1111
1112void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001113 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1114 "Plan SdpSemantics. Please use RemoveTrack "
1115 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001116 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001117 if (!IsClosed()) {
1118 for (const auto& track : local_stream->GetAudioTracks()) {
1119 RemoveAudioTrack(track.get(), local_stream);
1120 }
1121 for (const auto& track : local_stream->GetVideoTracks()) {
1122 RemoveVideoTrack(track.get(), local_stream);
1123 }
deadbeefab9b2d12015-10-14 11:33:11 -07001124 }
deadbeefab9b2d12015-10-14 11:33:11 -07001125 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001126 stream_observers_.erase(
1127 std::remove_if(
1128 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001129 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001130 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001131 }),
1132 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001133
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001134 if (IsClosed()) {
1135 return;
1136 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001137 observer_->OnRenegotiationNeeded();
1138}
1139
deadbeefe1f9d832016-01-14 15:35:42 -08001140rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1141 MediaStreamTrackInterface* track,
1142 std::vector<MediaStreamInterface*> streams) {
1143 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001144 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001145 for (auto* stream : streams) {
1146 if (!stream) {
1147 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1148 return nullptr;
1149 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001150 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001151 }
Seth Hampson845e8782018-03-02 11:34:10 -08001152 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001153 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001154 return nullptr;
1155 }
Steve Antonf9381f02017-12-14 10:23:57 -08001156 return sender_or_error.MoveValue();
1157}
1158
Steve Anton2d6c76a2018-01-05 17:10:52 -08001159RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001160 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001161 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001162 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001163 if (!track) {
1164 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1165 }
1166 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1167 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1168 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1169 "Track has invalid kind: " + track->kind());
1170 }
Steve Antonf9381f02017-12-14 10:23:57 -08001171 if (IsClosed()) {
1172 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1173 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001174 }
Steve Anton4171afb2017-11-20 10:20:22 -08001175 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001176 LOG_AND_RETURN_ERROR(
1177 RTCErrorType::INVALID_PARAMETER,
1178 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001179 }
Steve Antonf9381f02017-12-14 10:23:57 -08001180 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001181 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1182 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001183 if (sender_or_error.ok()) {
1184 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001185 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001186 }
1187 return sender_or_error;
1188}
deadbeefe1f9d832016-01-14 15:35:42 -08001189
Steve Antonf9381f02017-12-14 10:23:57 -08001190RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1191PeerConnection::AddTrackPlanB(
1192 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001193 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001194 if (stream_ids.size() > 1u) {
1195 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1196 "AddTrack with more than one stream is not "
1197 "supported with Plan B semantics.");
1198 }
1199 std::vector<std::string> adjusted_stream_ids = stream_ids;
1200 if (adjusted_stream_ids.empty()) {
1201 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1202 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001203 cricket::MediaType media_type =
1204 (track->kind() == MediaStreamTrackInterface::kAudioKind
1205 ? cricket::MEDIA_TYPE_AUDIO
1206 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001207 auto new_sender =
1208 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001209 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001210 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001211 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001212 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001213 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001214 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001215 if (sender_info) {
1216 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001217 }
Steve Antonf9381f02017-12-14 10:23:57 -08001218 } else {
1219 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001220 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001221 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001222 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001223 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001224 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001225 if (sender_info) {
1226 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001227 }
deadbeefe1f9d832016-01-14 15:35:42 -08001228 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001229 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001230}
deadbeefe1f9d832016-01-14 15:35:42 -08001231
Steve Antonf9381f02017-12-14 10:23:57 -08001232RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1233PeerConnection::AddTrackUnifiedPlan(
1234 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001235 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001236 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1237 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001238 RTC_LOG(LS_INFO) << "Reusing an existing "
1239 << cricket::MediaTypeToString(transceiver->media_type())
1240 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001241 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001242 transceiver->internal()->set_direction(
1243 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001244 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001245 transceiver->internal()->set_direction(
1246 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001247 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001248 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001249 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001250 } else {
1251 cricket::MediaType media_type =
1252 (track->kind() == MediaStreamTrackInterface::kAudioKind
1253 ? cricket::MEDIA_TYPE_AUDIO
1254 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001255 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1256 << " transceiver in response to a call to AddTrack.";
Steve Anton111fdfd2018-06-25 13:03:36 -07001257 auto sender = CreateSender(media_type, track->id(), track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001258 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1259 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001260 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001261 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001262 }
Steve Antonf9381f02017-12-14 10:23:57 -08001263 return transceiver->sender();
1264}
1265
1266rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1267PeerConnection::FindFirstTransceiverForAddedTrack(
1268 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1269 RTC_DCHECK(track);
1270 for (auto transceiver : transceivers_) {
1271 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001272 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001273 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001274 !transceiver->internal()->has_ever_been_used_to_send() &&
1275 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001276 return transceiver;
1277 }
1278 }
1279 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001280}
1281
1282bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1283 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001284 return RemoveTrackInternal(sender).ok();
1285}
1286
1287RTCError PeerConnection::RemoveTrackInternal(
1288 rtc::scoped_refptr<RtpSenderInterface> sender) {
1289 if (!sender) {
1290 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1291 }
deadbeefe1f9d832016-01-14 15:35:42 -08001292 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001293 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1294 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001295 }
Steve Antonf9381f02017-12-14 10:23:57 -08001296 if (IsUnifiedPlan()) {
1297 auto transceiver = FindTransceiverBySender(sender);
1298 if (!transceiver || !sender->track()) {
1299 return RTCError::OK();
1300 }
1301 sender->SetTrack(nullptr);
1302 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001303 transceiver->internal()->set_direction(
1304 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001305 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001306 transceiver->internal()->set_direction(
1307 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001308 }
Steve Anton4171afb2017-11-20 10:20:22 -08001309 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001310 bool removed;
1311 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1312 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1313 } else {
1314 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1315 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1316 }
1317 if (!removed) {
1318 LOG_AND_RETURN_ERROR(
1319 RTCErrorType::INVALID_PARAMETER,
1320 "Couldn't find sender " + sender->id() + " to remove.");
1321 }
Steve Anton4171afb2017-11-20 10:20:22 -08001322 }
deadbeefe1f9d832016-01-14 15:35:42 -08001323 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001324 return RTCError::OK();
1325}
1326
1327rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1328PeerConnection::FindTransceiverBySender(
1329 rtc::scoped_refptr<RtpSenderInterface> sender) {
1330 for (auto transceiver : transceivers_) {
1331 if (transceiver->sender() == sender) {
1332 return transceiver;
1333 }
1334 }
1335 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001336}
1337
Steve Anton9158ef62017-11-27 13:01:52 -08001338RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1339PeerConnection::AddTransceiver(
1340 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1341 return AddTransceiver(track, RtpTransceiverInit());
1342}
1343
1344RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1345PeerConnection::AddTransceiver(
1346 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1347 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001348 RTC_CHECK(IsUnifiedPlan())
1349 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001350 if (!track) {
1351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1352 }
1353 cricket::MediaType media_type;
1354 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1355 media_type = cricket::MEDIA_TYPE_AUDIO;
1356 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1357 media_type = cricket::MEDIA_TYPE_VIDEO;
1358 } else {
1359 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1360 "Track kind is not audio or video");
1361 }
1362 return AddTransceiver(media_type, track, init);
1363}
1364
1365RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1366PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1367 return AddTransceiver(media_type, RtpTransceiverInit());
1368}
1369
1370RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1371PeerConnection::AddTransceiver(cricket::MediaType media_type,
1372 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001373 RTC_CHECK(IsUnifiedPlan())
1374 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001375 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1376 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1377 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1378 "media type is not audio or video");
1379 }
1380 return AddTransceiver(media_type, nullptr, init);
1381}
1382
1383RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1384PeerConnection::AddTransceiver(
1385 cricket::MediaType media_type,
1386 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001387 const RtpTransceiverInit& init,
1388 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001389 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1390 media_type == cricket::MEDIA_TYPE_VIDEO));
1391 if (track) {
1392 RTC_DCHECK_EQ(media_type,
1393 (track->kind() == MediaStreamTrackInterface::kAudioKind
1394 ? cricket::MEDIA_TYPE_AUDIO
1395 : cricket::MEDIA_TYPE_VIDEO));
1396 }
1397
1398 // TODO(bugs.webrtc.org/7600): Verify init.
1399
Steve Anton3d954a62018-04-02 11:27:23 -07001400 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1401 << " transceiver in response to a call to AddTransceiver.";
Steve Anton111fdfd2018-06-25 13:03:36 -07001402 auto sender =
1403 CreateSender(media_type, (track ? track->id() : rtc::CreateRandomUuid()),
1404 track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001405 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1406 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1407 transceiver->internal()->set_direction(init.direction);
1408
Steve Anton22da89f2018-01-25 13:58:07 -08001409 if (fire_callback) {
1410 observer_->OnRenegotiationNeeded();
1411 }
Steve Antonf9381f02017-12-14 10:23:57 -08001412
1413 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1414}
1415
Steve Anton02ee47c2018-01-10 16:26:06 -08001416rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1417PeerConnection::CreateSender(
1418 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001419 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001420 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001421 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001422 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001423 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1424 RTC_DCHECK(!track ||
1425 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1426 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1427 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001428 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001429 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001430 } else {
1431 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1432 RTC_DCHECK(!track ||
1433 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1434 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001435 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001436 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001437 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001438 bool set_track_succeeded = sender->SetTrack(track);
1439 RTC_DCHECK(set_track_succeeded);
1440 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001441 return sender;
1442}
1443
1444rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1445PeerConnection::CreateReceiver(cricket::MediaType media_type,
1446 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001447 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1448 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001449 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001450 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001451 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001452 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001453 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001454 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001455 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001456 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1457 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001458 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001459 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001460 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001461 return receiver;
1462}
1463
1464rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1465PeerConnection::CreateAndAddTransceiver(
1466 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1467 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1468 receiver) {
1469 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1470 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001471 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001472 transceiver->internal()->SignalNegotiationNeeded.connect(
1473 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001474 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001475}
1476
Steve Anton52d86772018-02-20 15:48:12 -08001477void PeerConnection::OnNegotiationNeeded() {
1478 RTC_DCHECK_RUN_ON(signaling_thread());
1479 RTC_DCHECK(!IsClosed());
1480 observer_->OnRenegotiationNeeded();
1481}
1482
deadbeeffac06552015-11-25 11:26:01 -08001483rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001484 const std::string& kind,
1485 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001486 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1487 "Plan SdpSemantics. Please use AddTransceiver "
1488 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001489 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001490 if (IsClosed()) {
1491 return nullptr;
1492 }
Steve Anton4171afb2017-11-20 10:20:22 -08001493
Seth Hampson5b4f0752018-04-02 16:31:36 -07001494 // Internally we need to have one stream with Plan B semantics, so we
1495 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001496 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001497 if (stream_id.empty()) {
1498 stream_ids.push_back(rtc::CreateRandomUuid());
1499 RTC_LOG(LS_INFO)
1500 << "No stream_id specified for sender. Generated stream ID: "
1501 << stream_ids[0];
1502 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001503 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001504 }
1505
Steve Anton4171afb2017-11-20 10:20:22 -08001506 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001507 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001508 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001509 auto* audio_sender = new AudioRtpSender(
1510 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001511 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001512 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001513 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001514 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001515 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001516 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001517 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001518 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001519 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001520 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001521 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001522 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001523 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001524 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001525 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001526 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001527
deadbeefe1f9d832016-01-14 15:35:42 -08001528 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001529}
1530
deadbeef70ab1a12015-09-28 16:53:55 -07001531std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1532 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001533 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001534 for (auto sender : GetSendersInternal()) {
1535 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001536 }
1537 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001538}
1539
Steve Anton4171afb2017-11-20 10:20:22 -08001540std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1541PeerConnection::GetSendersInternal() const {
1542 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1543 all_senders;
1544 for (auto transceiver : transceivers_) {
1545 auto senders = transceiver->internal()->senders();
1546 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1547 }
1548 return all_senders;
1549}
1550
deadbeef70ab1a12015-09-28 16:53:55 -07001551std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1552PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001553 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001554 for (const auto& receiver : GetReceiversInternal()) {
1555 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001556 }
1557 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001558}
1559
Steve Anton4171afb2017-11-20 10:20:22 -08001560std::vector<
1561 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1562PeerConnection::GetReceiversInternal() const {
1563 std::vector<
1564 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1565 all_receivers;
1566 for (auto transceiver : transceivers_) {
1567 auto receivers = transceiver->internal()->receivers();
1568 all_receivers.insert(all_receivers.end(), receivers.begin(),
1569 receivers.end());
1570 }
1571 return all_receivers;
1572}
1573
Steve Anton9158ef62017-11-27 13:01:52 -08001574std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1575PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001576 RTC_CHECK(IsUnifiedPlan())
1577 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001578 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1579 for (auto transceiver : transceivers_) {
1580 all_transceivers.push_back(transceiver);
1581 }
1582 return all_transceivers;
1583}
1584
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001586 MediaStreamTrackInterface* track,
1587 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001588 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001589 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001590 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001591 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001592 return false;
1593 }
1594
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001595 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001596 // The StatsCollector is used to tell if a track is valid because it may
1597 // remember tracks that the PeerConnection previously removed.
1598 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001599 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1600 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001601 return false;
1602 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001603 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001604 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001605 return true;
1606}
1607
hbos74e1a4f2016-09-15 23:33:01 -07001608void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001609 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001610 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001611 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001612 stats_collector_->GetStatsReport(callback);
1613}
1614
Henrik Boström1df1bf82018-03-20 13:24:20 +01001615void PeerConnection::GetStats(
1616 rtc::scoped_refptr<RtpSenderInterface> selector,
1617 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1618 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1619 RTC_DCHECK(callback);
1620 RTC_DCHECK(stats_collector_);
1621 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1622 if (selector) {
1623 for (const auto& proxy_transceiver : transceivers_) {
1624 for (const auto& proxy_sender :
1625 proxy_transceiver->internal()->senders()) {
1626 if (proxy_sender == selector) {
1627 internal_sender = proxy_sender->internal();
1628 break;
1629 }
1630 }
1631 if (internal_sender)
1632 break;
1633 }
1634 }
1635 // If there is no |internal_sender| then |selector| is either null or does not
1636 // belong to the PeerConnection (in Plan B, senders can be removed from the
1637 // PeerConnection). This means that "all the stats objects representing the
1638 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1639 // produces an empty stats report.
1640 stats_collector_->GetStatsReport(internal_sender, callback);
1641}
1642
1643void PeerConnection::GetStats(
1644 rtc::scoped_refptr<RtpReceiverInterface> selector,
1645 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1646 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1647 RTC_DCHECK(callback);
1648 RTC_DCHECK(stats_collector_);
1649 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1650 if (selector) {
1651 for (const auto& proxy_transceiver : transceivers_) {
1652 for (const auto& proxy_receiver :
1653 proxy_transceiver->internal()->receivers()) {
1654 if (proxy_receiver == selector) {
1655 internal_receiver = proxy_receiver->internal();
1656 break;
1657 }
1658 }
1659 if (internal_receiver)
1660 break;
1661 }
1662 }
1663 // If there is no |internal_receiver| then |selector| is either null or does
1664 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1665 // the PeerConnection). This means that "all the stats objects representing
1666 // the selector" is an empty set. Invoking GetStatsReport() with a null
1667 // selector produces an empty stats report.
1668 stats_collector_->GetStatsReport(internal_receiver, callback);
1669}
1670
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001671PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1672 return signaling_state_;
1673}
1674
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001675PeerConnectionInterface::IceConnectionState
1676PeerConnection::ice_connection_state() {
1677 return ice_connection_state_;
1678}
1679
1680PeerConnectionInterface::IceGatheringState
1681PeerConnection::ice_gathering_state() {
1682 return ice_gathering_state_;
1683}
1684
Yves Gerey665174f2018-06-19 15:03:05 +02001685rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001686 const std::string& label,
1687 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001688 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001689
deadbeefab9b2d12015-10-14 11:33:11 -07001690 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001691
kwibergd1fe2812016-04-27 06:47:29 -07001692 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001693 if (config) {
1694 internal_config.reset(new InternalDataChannelInit(*config));
1695 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001696 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001697 InternalCreateDataChannel(label, internal_config.get()));
1698 if (!channel.get()) {
1699 return nullptr;
1700 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001702 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1703 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001704 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001705 observer_->OnRenegotiationNeeded();
1706 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001707 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001708 return DataChannelProxy::Create(signaling_thread(), channel.get());
1709}
1710
1711void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1712 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001713 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001714
zhihuang1c378ed2017-08-17 14:10:50 -07001715 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1716 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1717 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1718 // compares the mandatory fields parsed with the mandatory fields added in the
1719 // |constraints| and some downstream applications might create offers with
1720 // mandatory fields which would not be parsed in the helper method. For
1721 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1722 // |constraints| as a mandatory field but it is not parsed.
1723 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001724
zhihuang1c378ed2017-08-17 14:10:50 -07001725 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001726}
1727
1728void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1729 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001730 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001731
nisse7ce109a2017-01-31 00:57:56 -08001732 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001733 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001734 return;
1735 }
deadbeefab9b2d12015-10-14 11:33:11 -07001736
Steve Anton8d3444d2017-10-20 15:30:51 -07001737 if (IsClosed()) {
1738 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001739 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001740 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001741 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001742 return;
1743 }
1744
zhihuang1c378ed2017-08-17 14:10:50 -07001745 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001746 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001747 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001748 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001749 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001750 return;
1751 }
1752
Steve Anton22da89f2018-01-25 13:58:07 -08001753 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1754 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1755 if (IsUnifiedPlan()) {
1756 RTCError error = HandleLegacyOfferOptions(options);
1757 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001758 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001759 return;
1760 }
1761 }
1762
zhihuang1c378ed2017-08-17 14:10:50 -07001763 cricket::MediaSessionOptions session_options;
1764 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001765 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001766}
1767
Steve Anton22da89f2018-01-25 13:58:07 -08001768RTCError PeerConnection::HandleLegacyOfferOptions(
1769 const RTCOfferAnswerOptions& options) {
1770 RTC_DCHECK(IsUnifiedPlan());
1771
1772 if (options.offer_to_receive_audio == 0) {
1773 RemoveRecvDirectionFromReceivingTransceiversOfType(
1774 cricket::MEDIA_TYPE_AUDIO);
1775 } else if (options.offer_to_receive_audio == 1) {
1776 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1777 } else if (options.offer_to_receive_audio > 1) {
1778 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1779 "offer_to_receive_audio > 1 is not supported.");
1780 }
1781
1782 if (options.offer_to_receive_video == 0) {
1783 RemoveRecvDirectionFromReceivingTransceiversOfType(
1784 cricket::MEDIA_TYPE_VIDEO);
1785 } else if (options.offer_to_receive_video == 1) {
1786 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1787 } else if (options.offer_to_receive_video > 1) {
1788 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1789 "offer_to_receive_video > 1 is not supported.");
1790 }
1791
1792 return RTCError::OK();
1793}
1794
1795void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1796 cricket::MediaType media_type) {
1797 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001798 RtpTransceiverDirection new_direction =
1799 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1800 if (new_direction != transceiver->direction()) {
1801 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1802 << " transceiver (MID="
1803 << transceiver->mid().value_or("<not set>") << ") from "
1804 << RtpTransceiverDirectionToString(
1805 transceiver->direction())
1806 << " to "
1807 << RtpTransceiverDirectionToString(new_direction)
1808 << " since CreateOffer specified offer_to_receive=0";
1809 transceiver->internal()->set_direction(new_direction);
1810 }
Steve Anton22da89f2018-01-25 13:58:07 -08001811 }
1812}
1813
1814void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1815 cricket::MediaType media_type) {
1816 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001817 RTC_LOG(LS_INFO)
1818 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1819 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001820 RtpTransceiverInit init;
1821 init.direction = RtpTransceiverDirection::kRecvOnly;
1822 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1823 }
1824}
1825
1826std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1827PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1828 std::vector<
1829 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1830 receiving_transceivers;
1831 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001832 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001833 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1834 receiving_transceivers.push_back(transceiver);
1835 }
1836 }
1837 return receiving_transceivers;
1838}
1839
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001840void PeerConnection::CreateAnswer(
1841 CreateSessionDescriptionObserver* observer,
1842 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001843 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001844
nisse7ce109a2017-01-31 00:57:56 -08001845 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001846 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847 return;
1848 }
deadbeefab9b2d12015-10-14 11:33:11 -07001849
zhihuang1c378ed2017-08-17 14:10:50 -07001850 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1851 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1852 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001853 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001854 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001855 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001856 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001857 return;
1858 }
1859
Steve Anton8d3444d2017-10-20 15:30:51 -07001860 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001861}
1862
1863void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1864 const RTCOfferAnswerOptions& options) {
1865 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001866 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001867 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001868 return;
1869 }
1870
Steve Antondffead82018-02-06 10:31:29 -08001871 if (!(signaling_state_ == kHaveRemoteOffer ||
1872 signaling_state_ == kHaveLocalPrAnswer)) {
1873 std::string error =
1874 "PeerConnection cannot create an answer in a state other than "
1875 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001876 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001877 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001878 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001879 return;
1880 }
1881
Steve Antondffead82018-02-06 10:31:29 -08001882 // The remote description should be set if we're in the right state.
1883 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001884
Steve Anton22da89f2018-01-25 13:58:07 -08001885 if (IsUnifiedPlan()) {
1886 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1887 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1888 "supported with Unified Plan semantics. Use the "
1889 "RtpTransceiver API instead.";
1890 }
1891 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1892 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1893 "supported with Unified Plan semantics. Use the "
1894 "RtpTransceiver API instead.";
1895 }
1896 }
1897
htaa2a49d92016-03-04 02:51:39 -08001898 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001899 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001900
Steve Antond25da372017-11-06 14:50:29 -08001901 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902}
1903
1904void PeerConnection::SetLocalDescription(
1905 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001906 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001907 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001908
Steve Anton80dd7b52018-02-16 17:08:42 -08001909 // The SetLocalDescription contract is that we take ownership of the session
1910 // description regardless of the outcome, so wrap it in a unique_ptr right
1911 // away. Ideally, SetLocalDescription's signature will be changed to take the
1912 // description as a unique_ptr argument to formalize this agreement.
1913 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1914
nisse7ce109a2017-01-31 00:57:56 -08001915 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001916 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001917 return;
1918 }
Steve Anton8a006912017-12-04 15:25:56 -08001919
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001920 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001921 PostSetSessionDescriptionFailure(
1922 observer,
1923 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001924 return;
1925 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001926
Steve Anton80dd7b52018-02-16 17:08:42 -08001927 // If a session error has occurred the PeerConnection is in a possibly
1928 // inconsistent state so fail right away.
1929 if (session_error() != SessionError::kNone) {
1930 std::string error_message = GetSessionErrorMsg();
1931 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001932 PostSetSessionDescriptionFailure(
1933 observer,
1934 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001935 return;
1936 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001937
Steve Anton80dd7b52018-02-16 17:08:42 -08001938 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1939 if (!error.ok()) {
1940 std::string error_message = GetSetDescriptionErrorMessage(
1941 cricket::CS_LOCAL, desc->GetType(), error);
1942 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001943 PostSetSessionDescriptionFailure(
1944 observer,
1945 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001946 return;
1947 }
1948
1949 // Grab the description type before moving ownership to ApplyLocalDescription,
1950 // which may destroy it before returning.
1951 const SdpType type = desc->GetType();
1952
1953 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001954 // |desc| may be destroyed at this point.
1955
1956 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001957 // If ApplyLocalDescription fails, the PeerConnection could be in an
1958 // inconsistent state, so act conservatively here and set the session error
1959 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1960 SetSessionError(SessionError::kContent, error.message());
1961 std::string error_message =
1962 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1963 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001964 PostSetSessionDescriptionFailure(
1965 observer,
1966 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001967 return;
1968 }
Steve Anton8a006912017-12-04 15:25:56 -08001969 RTC_DCHECK(local_description());
1970
1971 PostSetSessionDescriptionSuccess(observer);
1972
Steve Anton8a006912017-12-04 15:25:56 -08001973 // MaybeStartGathering needs to be called after posting
1974 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1975 // before signaling that SetLocalDescription completed.
1976 transport_controller_->MaybeStartGathering();
1977
Steve Antona3a92c22017-12-07 10:27:41 -08001978 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001979 // TODO(deadbeef): We already had to hop to the network thread for
1980 // MaybeStartGathering...
1981 network_thread()->Invoke<void>(
1982 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1983 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001984 // Make UMA notes about what was agreed to.
1985 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001986 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001987 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001988}
1989
1990RTCError PeerConnection::ApplyLocalDescription(
1991 std::unique_ptr<SessionDescriptionInterface> desc) {
1992 RTC_DCHECK_RUN_ON(signaling_thread());
1993 RTC_DCHECK(desc);
1994
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001995 // Update stats here so that we have the most recent stats for tracks and
1996 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001997 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001998
Steve Antondcc3c022017-12-22 16:02:54 -08001999 // Take a reference to the old local description since it's used below to
2000 // compare against the new local description. When setting the new local
2001 // description, grab ownership of the replaced session description in case it
2002 // is the same as |old_local_description|, to keep it alive for the duration
2003 // of the method.
2004 const SessionDescriptionInterface* old_local_description =
2005 local_description();
2006 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002007 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002008 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002009 replaced_local_description = pending_local_description_
2010 ? std::move(pending_local_description_)
2011 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002012 current_local_description_ = std::move(desc);
2013 pending_local_description_ = nullptr;
2014 current_remote_description_ = std::move(pending_remote_description_);
2015 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002016 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002017 pending_local_description_ = std::move(desc);
2018 }
2019 // The session description to apply now must be accessed by
2020 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002021 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002022
Zhi Huange830e682018-03-30 10:48:35 -07002023 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2024 if (!error.ok()) {
2025 return error;
2026 }
2027
Steve Antondcc3c022017-12-22 16:02:54 -08002028 if (IsUnifiedPlan()) {
2029 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002030 cricket::CS_LOCAL, *local_description(), old_local_description,
2031 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002032 if (!error.ok()) {
2033 return error;
2034 }
Steve Antondcc3c022017-12-22 16:02:54 -08002035 for (auto transceiver : transceivers_) {
2036 const ContentInfo* content =
2037 FindMediaSectionForTransceiver(transceiver, local_description());
2038 if (!content) {
2039 continue;
2040 }
2041 const MediaContentDescription* media_desc = content->media_description();
2042 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2043 transceiver->internal()->set_current_direction(media_desc->direction());
2044 }
2045 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002046 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2047 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002048 transceiver->Stop();
2049 }
2050 }
2051 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002052 // Media channels will be created only when offer is set. These may use new
2053 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002054 if (type == SdpType::kOffer) {
2055 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2056 // description is applied. Restore back to old description.
2057 RTCError error = CreateChannels(*local_description()->description());
2058 if (!error.ok()) {
2059 return error;
2060 }
2061 }
Steve Antondcc3c022017-12-22 16:02:54 -08002062 // Remove unused channels if MediaContentDescription is rejected.
2063 RemoveUnusedChannels(local_description()->description());
2064 }
Steve Anton8a006912017-12-04 15:25:56 -08002065
Zhi Huange830e682018-03-30 10:48:35 -07002066 error = UpdateSessionState(type, cricket::CS_LOCAL,
2067 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002068 if (!error.ok()) {
2069 return error;
2070 }
Steve Antondcc3c022017-12-22 16:02:54 -08002071
Steve Anton8a006912017-12-04 15:25:56 -08002072 if (remote_description()) {
2073 // Now that we have a local description, we can push down remote candidates.
2074 UseCandidatesInSessionDescription(remote_description());
2075 }
2076
2077 pending_ice_restarts_.clear();
2078 if (session_error() != SessionError::kNone) {
2079 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2080 }
2081
deadbeefab9b2d12015-10-14 11:33:11 -07002082 // If setting the description decided our SSL role, allocate any necessary
2083 // SCTP sids.
2084 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002085 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002086 AllocateSctpSids(role);
2087 }
2088
Steve Antond3679212018-01-17 17:41:02 -08002089 if (IsUnifiedPlan()) {
2090 for (auto transceiver : transceivers_) {
2091 const ContentInfo* content =
2092 FindMediaSectionForTransceiver(transceiver, local_description());
2093 if (!content) {
2094 continue;
2095 }
Steve Anton74255ff2018-01-24 18:32:57 -08002096 const auto& streams = content->media_description()->streams();
2097 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002098 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002099 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002100 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002101 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002102 } else {
2103 // 0 is a special value meaning "this sender has no associated send
2104 // stream". Need to call this so the sender won't attempt to configure
2105 // a no longer existing stream and run into DCHECKs in the lower
2106 // layers.
2107 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002108 }
2109 }
2110 } else {
2111 // Plan B semantics.
2112
Steve Antondcc3c022017-12-22 16:02:54 -08002113 // Update state and SSRC of local MediaStreams and DataChannels based on the
2114 // local session description.
2115 const cricket::ContentInfo* audio_content =
2116 GetFirstAudioContent(local_description()->description());
2117 if (audio_content) {
2118 if (audio_content->rejected) {
2119 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2120 } else {
2121 const cricket::AudioContentDescription* audio_desc =
2122 audio_content->media_description()->as_audio();
2123 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2124 }
deadbeeffaac4972015-11-12 15:33:07 -08002125 }
deadbeefab9b2d12015-10-14 11:33:11 -07002126
Steve Antondcc3c022017-12-22 16:02:54 -08002127 const cricket::ContentInfo* video_content =
2128 GetFirstVideoContent(local_description()->description());
2129 if (video_content) {
2130 if (video_content->rejected) {
2131 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2132 } else {
2133 const cricket::VideoContentDescription* video_desc =
2134 video_content->media_description()->as_video();
2135 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2136 }
deadbeeffaac4972015-11-12 15:33:07 -08002137 }
deadbeefab9b2d12015-10-14 11:33:11 -07002138 }
2139
2140 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002141 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002142 if (data_content) {
2143 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002144 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002145 if (rtc::starts_with(data_desc->protocol().data(),
2146 cricket::kMediaProtocolRtpPrefix)) {
2147 UpdateLocalRtpDataChannels(data_desc->streams());
2148 }
2149 }
2150
Steve Anton8a006912017-12-04 15:25:56 -08002151 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002152}
2153
2154void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002155 SetSessionDescriptionObserver* observer,
2156 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002157 SetRemoteDescription(
2158 std::unique_ptr<SessionDescriptionInterface>(desc),
2159 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2160 new SetRemoteDescriptionObserverAdapter(this, observer)));
2161}
2162
2163void PeerConnection::SetRemoteDescription(
2164 std::unique_ptr<SessionDescriptionInterface> desc,
2165 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002166 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002167
nisse7ce109a2017-01-31 00:57:56 -08002168 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002169 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002170 return;
2171 }
Steve Anton8a006912017-12-04 15:25:56 -08002172
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002173 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002174 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002175 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002176 return;
2177 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002178
Steve Anton80dd7b52018-02-16 17:08:42 -08002179 // If a session error has occurred the PeerConnection is in a possibly
2180 // inconsistent state so fail right away.
2181 if (session_error() != SessionError::kNone) {
2182 std::string error_message = GetSessionErrorMsg();
2183 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2184 observer->OnSetRemoteDescriptionComplete(
2185 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2186 return;
2187 }
Steve Anton71439a62018-02-15 11:53:06 -08002188
Steve Antonba42e992018-04-09 14:10:01 -07002189 if (desc->GetType() == SdpType::kOffer) {
2190 // Report to UMA the format of the received offer.
2191 ReportSdpFormatReceived(*desc);
2192 }
2193
Steve Anton80dd7b52018-02-16 17:08:42 -08002194 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002195 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002196 std::string error_message = GetSetDescriptionErrorMessage(
2197 cricket::CS_REMOTE, desc->GetType(), error);
2198 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002199 observer->OnSetRemoteDescriptionComplete(
2200 RTCError(error.type(), std::move(error_message)));
2201 return;
2202 }
Steve Anton71439a62018-02-15 11:53:06 -08002203
Steve Anton80dd7b52018-02-16 17:08:42 -08002204 // Grab the description type before moving ownership to
2205 // ApplyRemoteDescription, which may destroy it before returning.
2206 const SdpType type = desc->GetType();
2207
2208 error = ApplyRemoteDescription(std::move(desc));
2209 // |desc| may be destroyed at this point.
2210
2211 if (!error.ok()) {
2212 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2213 // inconsistent state, so act conservatively here and set the session error
2214 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2215 SetSessionError(SessionError::kContent, error.message());
2216 std::string error_message =
2217 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2218 RTC_LOG(LS_ERROR) << error_message;
2219 observer->OnSetRemoteDescriptionComplete(
2220 RTCError(error.type(), std::move(error_message)));
2221 return;
2222 }
2223 RTC_DCHECK(remote_description());
2224
2225 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002226 // TODO(deadbeef): We already had to hop to the network thread for
2227 // MaybeStartGathering...
2228 network_thread()->Invoke<void>(
2229 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2230 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002231 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002232 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002233 }
2234
2235 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002236 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002237}
2238
2239RTCError PeerConnection::ApplyRemoteDescription(
2240 std::unique_ptr<SessionDescriptionInterface> desc) {
2241 RTC_DCHECK_RUN_ON(signaling_thread());
2242 RTC_DCHECK(desc);
2243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002244 // Update stats here so that we have the most recent stats for tracks and
2245 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002246 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002247
Steve Antondcc3c022017-12-22 16:02:54 -08002248 // Take a reference to the old remote description since it's used below to
2249 // compare against the new remote description. When setting the new remote
2250 // description, grab ownership of the replaced session description in case it
2251 // is the same as |old_remote_description|, to keep it alive for the duration
2252 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002253 const SessionDescriptionInterface* old_remote_description =
2254 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002255 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002256 SdpType type = desc->GetType();
2257 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002258 replaced_remote_description = pending_remote_description_
2259 ? std::move(pending_remote_description_)
2260 : std::move(current_remote_description_);
2261 current_remote_description_ = std::move(desc);
2262 pending_remote_description_ = nullptr;
2263 current_local_description_ = std::move(pending_local_description_);
2264 } else {
2265 replaced_remote_description = std::move(pending_remote_description_);
2266 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002267 }
Steve Anton8a006912017-12-04 15:25:56 -08002268 // The session description to apply now must be accessed by
2269 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002270 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002271
Zhi Huange830e682018-03-30 10:48:35 -07002272 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2273 if (!error.ok()) {
2274 return error;
2275 }
Steve Anton8a006912017-12-04 15:25:56 -08002276 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002277 if (IsUnifiedPlan()) {
2278 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002279 cricket::CS_REMOTE, *remote_description(), local_description(),
2280 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002281 if (!error.ok()) {
2282 return error;
2283 }
Steve Antondcc3c022017-12-22 16:02:54 -08002284 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002285 // Media channels will be created only when offer is set. These may use new
2286 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002287 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002288 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002289 // description is applied. Restore back to old description.
2290 RTCError error = CreateChannels(*remote_description()->description());
2291 if (!error.ok()) {
2292 return error;
2293 }
2294 }
Steve Antondcc3c022017-12-22 16:02:54 -08002295 // Remove unused channels if MediaContentDescription is rejected.
2296 RemoveUnusedChannels(remote_description()->description());
2297 }
Steve Anton8a006912017-12-04 15:25:56 -08002298
Zhi Huange830e682018-03-30 10:48:35 -07002299 // NOTE: Candidates allocation will be initiated only when
2300 // SetLocalDescription is called.
2301 error = UpdateSessionState(type, cricket::CS_REMOTE,
2302 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002303 if (!error.ok()) {
2304 return error;
2305 }
2306
2307 if (local_description() &&
2308 !UseCandidatesInSessionDescription(remote_description())) {
2309 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2310 }
2311
2312 if (old_remote_description) {
2313 for (const cricket::ContentInfo& content :
2314 old_remote_description->description()->contents()) {
2315 // Check if this new SessionDescription contains new ICE ufrag and
2316 // password that indicates the remote peer requests an ICE restart.
2317 // TODO(deadbeef): When we start storing both the current and pending
2318 // remote description, this should reset pending_ice_restarts and compare
2319 // against the current description.
2320 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2321 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002322 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002323 pending_ice_restarts_.insert(content.name);
2324 }
2325 } else {
2326 // We retain all received candidates only if ICE is not restarted.
2327 // When ICE is restarted, all previous candidates belong to an old
2328 // generation and should not be kept.
2329 // TODO(deadbeef): This goes against the W3C spec which says the remote
2330 // description should only contain candidates from the last set remote
2331 // description plus any candidates added since then. We should remove
2332 // this once we're sure it won't break anything.
2333 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2334 old_remote_description, content.name, mutable_remote_description());
2335 }
2336 }
2337 }
2338
2339 if (session_error() != SessionError::kNone) {
2340 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2341 }
2342
2343 // Set the the ICE connection state to connecting since the connection may
2344 // become writable with peer reflexive candidates before any remote candidate
2345 // is signaled.
2346 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2347 // is to have a new signal the indicates a change in checking state from the
2348 // transport and expose a new checking() member from transport that can be
2349 // read to determine the current checking state. The existing SignalConnecting
2350 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002351 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002352 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002353 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2354 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2355 }
2356
deadbeefab9b2d12015-10-14 11:33:11 -07002357 // If setting the description decided our SSL role, allocate any necessary
2358 // SCTP sids.
2359 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002360 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002361 AllocateSctpSids(role);
2362 }
2363
Steve Antondcc3c022017-12-22 16:02:54 -08002364 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002365 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002366 now_receiving_transceivers;
2367 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2368 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002369 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002370 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002371 for (auto transceiver : transceivers_) {
2372 const ContentInfo* content =
2373 FindMediaSectionForTransceiver(transceiver, remote_description());
2374 if (!content) {
2375 continue;
2376 }
2377 const MediaContentDescription* media_desc = content->media_description();
2378 RtpTransceiverDirection local_direction =
2379 RtpTransceiverDirectionReversed(media_desc->direction());
2380 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2381 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2382 // transceiver's current direction is neither sendrecv nor recvonly,
2383 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002384 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002385 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002386 // The remote description has signaled the stream IDs.
2387 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002388 }
Steve Antondcc3c022017-12-22 16:02:54 -08002389 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2390 (!transceiver->current_direction() ||
2391 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002392 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002393 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002394 << content->name << " (added to "
2395 << GetStreamIdsString(stream_ids) << ").";
2396
2397 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2398 for (const std::string& stream_id : stream_ids) {
2399 rtc::scoped_refptr<MediaStreamInterface> stream =
2400 remote_streams_->find(stream_id);
2401 if (!stream) {
2402 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2403 MediaStream::Create(stream_id));
2404 remote_streams_->AddStream(stream);
2405 added_streams.push_back(stream);
2406 }
2407 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002408 }
Steve Anton3172c032018-05-03 15:30:18 -07002409 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002410 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002411 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002412 }
2413 // If direction is sendonly or inactive, and transceiver's current
2414 // direction is neither sendonly nor inactive, process the removal of a
2415 // remote track for the media description.
2416 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002417 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002418 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002419 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2420 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002421 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2422 transceiver->internal()->receiver_internal()->streams();
2423 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002424 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002425 no_longer_receiving_transceivers.push_back(transceiver);
2426 // Remove any streams that no longer have tracks.
2427 for (auto stream : media_streams) {
2428 if (stream->GetAudioTracks().empty() &&
2429 stream->GetVideoTracks().empty()) {
2430 remote_streams_->RemoveStream(stream);
2431 removed_streams.push_back(stream);
2432 }
2433 }
Steve Antondcc3c022017-12-22 16:02:54 -08002434 }
2435 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2436 transceiver->internal()->set_current_direction(local_direction);
2437 }
2438 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002439 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2440 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002441 transceiver->Stop();
2442 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002443 if (!content->rejected &&
2444 RtpTransceiverDirectionHasRecv(local_direction)) {
2445 // Set ssrc to 0 in the case of an unsignalled ssrc.
2446 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002447 if (!media_desc->streams().empty() &&
2448 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002449 ssrc = media_desc->streams()[0].first_ssrc();
2450 }
2451 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002452 }
Steve Antondcc3c022017-12-22 16:02:54 -08002453 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002454 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002455 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002456 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002457 observer_->OnTrack(transceiver);
2458 observer_->OnAddTrack(transceiver->receiver(),
2459 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002460 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002461 for (auto stream : added_streams) {
2462 observer_->OnAddStream(stream);
2463 }
Steve Anton3172c032018-05-03 15:30:18 -07002464 for (auto transceiver : no_longer_receiving_transceivers) {
2465 observer_->OnRemoveTrack(transceiver->receiver());
2466 }
2467 for (auto stream : removed_streams) {
2468 observer_->OnRemoveStream(stream);
2469 }
Steve Antondcc3c022017-12-22 16:02:54 -08002470 }
2471
Henrik Boströmfdb92012017-11-09 19:55:44 +01002472 const cricket::ContentInfo* audio_content =
2473 GetFirstAudioContent(remote_description()->description());
2474 const cricket::ContentInfo* video_content =
2475 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002476 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002477 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002478 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002479 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002480 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002481 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002482
2483 // Check if the descriptions include streams, just in case the peer supports
2484 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002485 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002486 (audio_desc && !audio_desc->streams().empty()) ||
2487 (video_desc && !video_desc->streams().empty())) {
2488 remote_peer_supports_msid_ = true;
2489 }
deadbeefab9b2d12015-10-14 11:33:11 -07002490
2491 // We wait to signal new streams until we finish processing the description,
2492 // since only at that point will new streams have all their tracks.
2493 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2494
Steve Antondcc3c022017-12-22 16:02:54 -08002495 if (!IsUnifiedPlan()) {
2496 // TODO(steveanton): When removing RTP senders/receivers in response to a
2497 // rejected media section, there is some cleanup logic that expects the
2498 // voice/ video channel to still be set. But in this method the voice/video
2499 // channel would have been destroyed by the SetRemoteDescription caller
2500 // above so the cleanup that relies on them fails to run. The RemoveSenders
2501 // calls should be moved to right before the DestroyChannel calls to fix
2502 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002503
Steve Antondcc3c022017-12-22 16:02:54 -08002504 // Find all audio rtp streams and create corresponding remote AudioTracks
2505 // and MediaStreams.
2506 if (audio_content) {
2507 if (audio_content->rejected) {
2508 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2509 } else {
2510 bool default_audio_track_needed =
2511 !remote_peer_supports_msid_ &&
2512 RtpTransceiverDirectionHasSend(audio_desc->direction());
2513 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2514 default_audio_track_needed, audio_desc->type(),
2515 new_streams);
2516 }
deadbeeffaac4972015-11-12 15:33:07 -08002517 }
deadbeefab9b2d12015-10-14 11:33:11 -07002518
Steve Antondcc3c022017-12-22 16:02:54 -08002519 // Find all video rtp streams and create corresponding remote VideoTracks
2520 // and MediaStreams.
2521 if (video_content) {
2522 if (video_content->rejected) {
2523 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2524 } else {
2525 bool default_video_track_needed =
2526 !remote_peer_supports_msid_ &&
2527 RtpTransceiverDirectionHasSend(video_desc->direction());
2528 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2529 default_video_track_needed, video_desc->type(),
2530 new_streams);
2531 }
deadbeeffaac4972015-11-12 15:33:07 -08002532 }
deadbeefab9b2d12015-10-14 11:33:11 -07002533
Steve Antondcc3c022017-12-22 16:02:54 -08002534 // Update the DataChannels with the information from the remote peer.
2535 if (data_desc) {
2536 if (rtc::starts_with(data_desc->protocol().data(),
2537 cricket::kMediaProtocolRtpPrefix)) {
2538 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2539 }
deadbeefab9b2d12015-10-14 11:33:11 -07002540 }
deadbeefab9b2d12015-10-14 11:33:11 -07002541
Steve Antondcc3c022017-12-22 16:02:54 -08002542 // Iterate new_streams and notify the observer about new MediaStreams.
2543 for (size_t i = 0; i < new_streams->count(); ++i) {
2544 MediaStreamInterface* new_stream = new_streams->at(i);
2545 stats_->AddStream(new_stream);
2546 observer_->OnAddStream(
2547 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2548 }
deadbeefab9b2d12015-10-14 11:33:11 -07002549
Steve Antondcc3c022017-12-22 16:02:54 -08002550 UpdateEndedRemoteMediaStreams();
2551 }
deadbeefab9b2d12015-10-14 11:33:11 -07002552
Steve Anton8a006912017-12-04 15:25:56 -08002553 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002554}
2555
Steve Antondcc3c022017-12-22 16:02:54 -08002556RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2557 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002558 const SessionDescriptionInterface& new_session,
2559 const SessionDescriptionInterface* old_local_description,
2560 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002561 RTC_DCHECK(IsUnifiedPlan());
2562
Steve Anton7464fca2018-01-19 11:10:37 -08002563 const cricket::ContentGroup* bundle_group = nullptr;
2564 if (new_session.GetType() == SdpType::kOffer) {
2565 auto bundle_group_or_error =
2566 GetEarlyBundleGroup(*new_session.description());
2567 if (!bundle_group_or_error.ok()) {
2568 return bundle_group_or_error.MoveError();
2569 }
2570 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002571 }
Steve Antondcc3c022017-12-22 16:02:54 -08002572
Steve Antondcc3c022017-12-22 16:02:54 -08002573 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002574 for (size_t i = 0; i < new_contents.size(); ++i) {
2575 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002576 cricket::MediaType media_type = new_content.media_description()->type();
2577 seen_mids_.insert(new_content.name);
2578 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2579 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002580 const cricket::ContentInfo* old_local_content = nullptr;
2581 if (old_local_description &&
2582 i < old_local_description->description()->contents().size()) {
2583 old_local_content =
2584 &old_local_description->description()->contents()[i];
2585 }
2586 const cricket::ContentInfo* old_remote_content = nullptr;
2587 if (old_remote_description &&
2588 i < old_remote_description->description()->contents().size()) {
2589 old_remote_content =
2590 &old_remote_description->description()->contents()[i];
2591 }
Steve Antondcc3c022017-12-22 16:02:54 -08002592 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002593 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2594 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002595 if (!transceiver_or_error.ok()) {
2596 return transceiver_or_error.MoveError();
2597 }
2598 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002599 RTCError error =
2600 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2601 if (!error.ok()) {
2602 return error;
2603 }
2604 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002605 if (GetDataMid() && new_content.name != *GetDataMid()) {
2606 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002607 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2608 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002609 continue;
2610 }
2611 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2612 if (!error.ok()) {
2613 return error;
2614 }
Steve Antondcc3c022017-12-22 16:02:54 -08002615 } else {
2616 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2617 "Unknown section type.");
2618 }
2619 }
2620
2621 return RTCError::OK();
2622}
2623
2624RTCError PeerConnection::UpdateTransceiverChannel(
2625 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2626 transceiver,
2627 const cricket::ContentInfo& content,
2628 const cricket::ContentGroup* bundle_group) {
2629 RTC_DCHECK(IsUnifiedPlan());
2630 RTC_DCHECK(transceiver);
2631 cricket::BaseChannel* channel = transceiver->internal()->channel();
2632 if (content.rejected) {
2633 if (channel) {
2634 transceiver->internal()->SetChannel(nullptr);
2635 DestroyBaseChannel(channel);
2636 }
2637 } else {
2638 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002639 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002640 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002641 } else {
Steve Anton69470252018-02-09 11:43:08 -08002642 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002643 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002644 }
2645 if (!channel) {
2646 LOG_AND_RETURN_ERROR(
2647 RTCErrorType::INTERNAL_ERROR,
2648 "Failed to create channel for mid=" + content.name);
2649 }
2650 transceiver->internal()->SetChannel(channel);
2651 }
2652 }
2653 return RTCError::OK();
2654}
2655
Steve Antonfa2260d2017-12-28 16:38:23 -08002656RTCError PeerConnection::UpdateDataChannel(
2657 cricket::ContentSource source,
2658 const cricket::ContentInfo& content,
2659 const cricket::ContentGroup* bundle_group) {
2660 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002661 // If data channels are disabled, ignore this media section. CreateAnswer
2662 // will take care of rejecting it.
2663 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002664 }
2665 if (content.rejected) {
2666 DestroyDataChannel();
2667 } else {
2668 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002669 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002670 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2671 "Failed to create data channel.");
2672 }
2673 }
2674 if (source == cricket::CS_REMOTE) {
2675 const MediaContentDescription* data_desc = content.media_description();
2676 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2677 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2678 }
2679 }
2680 }
2681 return RTCError::OK();
2682}
2683
Steve Antondcc3c022017-12-22 16:02:54 -08002684RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2685PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002686 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002687 size_t mline_index,
2688 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002689 const ContentInfo* old_local_content,
2690 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002691 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002692 // If this is an offer then the m= section might be recycled. If the m=
2693 // section is being recycled (defined as: rejected in the current local or
2694 // remote description and not rejected in new description), dissociate the
2695 // currently associated RtpTransceiver by setting its mid property to null,
2696 // and discard the mapping between the transceiver and its m= section index.
2697 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2698 old_remote_content)) {
2699 // We want to dissociate the transceiver that has the rejected mid.
2700 const std::string& old_mid =
2701 (old_local_content && old_local_content->rejected)
2702 ? old_local_content->name
2703 : old_remote_content->name;
2704 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002705 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002706 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2707 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002708 old_transceiver->internal()->set_mid(absl::nullopt);
2709 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002710 }
2711 }
2712 const MediaContentDescription* media_desc = content.media_description();
2713 auto transceiver = GetAssociatedTransceiver(content.name);
2714 if (source == cricket::CS_LOCAL) {
2715 // Find the RtpTransceiver that corresponds to this m= section, using the
2716 // mapping between transceivers and m= section indices established when
2717 // creating the offer.
2718 if (!transceiver) {
2719 transceiver = GetTransceiverByMLineIndex(mline_index);
2720 }
2721 if (!transceiver) {
2722 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2723 "Unknown transceiver");
2724 }
2725 } else {
2726 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2727 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2728 // of the same type...
2729 if (!transceiver &&
2730 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2731 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2732 }
2733 // If no RtpTransceiver was found in the previous step, create one with a
2734 // recvonly direction.
2735 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002736 RTC_LOG(LS_INFO) << "Adding "
2737 << cricket::MediaTypeToString(media_desc->type())
2738 << " transceiver for MID=" << content.name
2739 << " at i=" << mline_index
2740 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002741 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002742 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002743 std::string receiver_id;
2744 if (!media_desc->streams().empty()) {
2745 receiver_id = media_desc->streams()[0].id;
2746 } else {
2747 receiver_id = rtc::CreateRandomUuid();
2748 }
2749 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002750 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002751 transceiver->internal()->set_direction(
2752 RtpTransceiverDirection::kRecvOnly);
2753 }
2754 }
2755 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002756 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002757 LOG_AND_RETURN_ERROR(
2758 RTCErrorType::INVALID_PARAMETER,
2759 "Transceiver type does not match media description type.");
2760 }
2761 // Associate the found or created RtpTransceiver with the m= section by
2762 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2763 // section, and establish a mapping between the transceiver and the index of
2764 // the m= section.
2765 transceiver->internal()->set_mid(content.name);
2766 transceiver->internal()->set_mline_index(mline_index);
2767 return std::move(transceiver);
2768}
2769
2770rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2771PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2772 RTC_DCHECK(IsUnifiedPlan());
2773 for (auto transceiver : transceivers_) {
2774 if (transceiver->mid() == mid) {
2775 return transceiver;
2776 }
2777 }
2778 return nullptr;
2779}
2780
2781rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2782PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2783 RTC_DCHECK(IsUnifiedPlan());
2784 for (auto transceiver : transceivers_) {
2785 if (transceiver->internal()->mline_index() == mline_index) {
2786 return transceiver;
2787 }
2788 }
2789 return nullptr;
2790}
2791
2792rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2793PeerConnection::FindAvailableTransceiverToReceive(
2794 cricket::MediaType media_type) const {
2795 RTC_DCHECK(IsUnifiedPlan());
2796 // From JSEP section 5.10 (Applying a Remote Description):
2797 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2798 // the same type that were added to the PeerConnection by addTrack and are not
2799 // associated with any m= section and are not stopped, find the first such
2800 // RtpTransceiver.
2801 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002802 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002803 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2804 !transceiver->stopped()) {
2805 return transceiver;
2806 }
2807 }
2808 return nullptr;
2809}
2810
Steve Antoned10bd92017-12-05 10:52:59 -08002811const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2812 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2813 transceiver,
2814 const SessionDescriptionInterface* sdesc) const {
2815 RTC_DCHECK(transceiver);
2816 RTC_DCHECK(sdesc);
2817 if (IsUnifiedPlan()) {
2818 if (!transceiver->internal()->mid()) {
2819 // This transceiver is not associated with a media section yet.
2820 return nullptr;
2821 }
2822 return sdesc->description()->GetContentByName(
2823 *transceiver->internal()->mid());
2824 } else {
2825 // Plan B only allows at most one audio and one video section, so use the
2826 // first media section of that type.
2827 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002828 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002829 }
2830}
2831
deadbeef46c73892016-11-16 19:42:04 -08002832PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2833 return configuration_;
2834}
2835
deadbeef293e9262017-01-11 12:28:30 -08002836bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2837 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002838 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002839 if (IsClosed()) {
2840 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2841 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2842 }
2843
Qingsi Wanga2d60672018-04-11 16:57:45 -07002844 // According to JSEP, after setLocalDescription, changing the candidate pool
2845 // size is not allowed, and changing the set of ICE servers will not result
2846 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002847 if (local_description() && configuration.ice_candidate_pool_size !=
2848 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002849 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2850 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002851 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002852 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002853
deadbeef293e9262017-01-11 12:28:30 -08002854 // The simplest (and most future-compatible) way to tell if the config was
2855 // modified in an invalid way is to copy each property we do support
2856 // modifying, then use operator==. There are far more properties we don't
2857 // support modifying than those we do, and more could be added.
2858 RTCConfiguration modified_config = configuration_;
2859 modified_config.servers = configuration.servers;
2860 modified_config.type = configuration.type;
2861 modified_config.ice_candidate_pool_size =
2862 configuration.ice_candidate_pool_size;
2863 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002864 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002865 modified_config.ice_check_interval_strong_connectivity =
2866 configuration.ice_check_interval_strong_connectivity;
2867 modified_config.ice_check_interval_weak_connectivity =
2868 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002869 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2870 modified_config.ice_unwritable_min_checks =
2871 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002872 modified_config.stun_candidate_keepalive_interval =
2873 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002874 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002875 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002876 modified_config.active_reset_srtp_params =
2877 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002878 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002879 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002880 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2881 }
2882
Steve Anton038834f2017-07-14 15:59:59 -07002883 // Validate the modified configuration.
2884 RTCError validate_error = ValidateConfiguration(modified_config);
2885 if (!validate_error.ok()) {
2886 return SafeSetError(std::move(validate_error), error);
2887 }
2888
deadbeef293e9262017-01-11 12:28:30 -08002889 // Note that this isn't possible through chromium, since it's an unsigned
2890 // short in WebIDL.
2891 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002892 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002893 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2894 }
2895
2896 // Parse ICE servers before hopping to network thread.
2897 cricket::ServerAddresses stun_servers;
2898 std::vector<cricket::RelayServerConfig> turn_servers;
2899 RTCErrorType parse_error =
2900 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2901 if (parse_error != RTCErrorType::NONE) {
2902 return SafeSetError(parse_error, error);
2903 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002904 // Note if STUN or TURN servers were supplied.
2905 if (!stun_servers.empty()) {
2906 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2907 }
2908 if (!turn_servers.empty()) {
2909 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2910 }
deadbeef293e9262017-01-11 12:28:30 -08002911
2912 // In theory this shouldn't fail.
2913 if (!network_thread()->Invoke<bool>(
2914 RTC_FROM_HERE,
2915 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2916 stun_servers, turn_servers, modified_config.type,
2917 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002918 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002919 modified_config.turn_customizer,
2920 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002921 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002922 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2923 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002924
deadbeefd1a38b52016-12-10 13:15:33 -08002925 // As described in JSEP, calling setConfiguration with new ICE servers or
2926 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2927 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002928 if (modified_config.servers != configuration_.servers ||
2929 modified_config.type != configuration_.type ||
2930 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002931 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002932 }
skvladd1f5fda2017-02-03 16:54:05 -08002933
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002934 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002935
Zhi Huangb57e1692018-06-12 11:41:11 -07002936 if (configuration_.active_reset_srtp_params !=
2937 modified_config.active_reset_srtp_params) {
2938 transport_controller_->SetActiveResetSrtpParams(
2939 modified_config.active_reset_srtp_params);
2940 }
2941
deadbeef293e9262017-01-11 12:28:30 -08002942 configuration_ = modified_config;
2943 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002944}
2945
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002946bool PeerConnection::AddIceCandidate(
2947 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002948 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002949 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002950 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002951 return false;
2952 }
Steve Antond25da372017-11-06 14:50:29 -08002953
2954 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002955 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002956 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002957 return false;
2958 }
2959
2960 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002961 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002962 return false;
2963 }
2964
2965 bool valid = false;
2966 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2967 if (!valid) {
2968 return false;
2969 }
2970
2971 // Add this candidate to the remote session description.
2972 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002973 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002974 return false;
2975 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002976 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002977
2978 if (ready) {
2979 return UseCandidate(ice_candidate);
2980 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002981 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002982 return true;
2983 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002984}
2985
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002986bool PeerConnection::RemoveIceCandidates(
2987 const std::vector<cricket::Candidate>& candidates) {
2988 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002989 if (IsClosed()) {
2990 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2991 return false;
2992 }
2993
Steve Antond25da372017-11-06 14:50:29 -08002994 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002995 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2996 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002997 return false;
2998 }
2999
3000 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003001 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003002 return false;
3003 }
3004
3005 size_t number_removed =
3006 mutable_remote_description()->RemoveCandidates(candidates);
3007 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003008 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003009 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003010 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003011 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003012 }
3013
3014 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003015 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3016 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003017 RTC_LOG(LS_ERROR)
3018 << "RemoveIceCandidates: Error when removing remote candidates: "
3019 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003020 }
3021 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003022}
3023
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003024void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003025 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003026 network_thread()->Invoke<void>(
3027 RTC_FROM_HERE,
3028 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3029 // Send information about IPv4/IPv6 status.
3030 if (uma_observer_) {
3031 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3032 uma_observer_->IncrementEnumCounter(
3033 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3034 kPeerConnectionAddressFamilyCounter_Max);
3035 } else {
3036 uma_observer_->IncrementEnumCounter(
3037 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3038 kPeerConnectionAddressFamilyCounter_Max);
3039 }
3040 }
3041}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003042
Qingsi Wanga2d60672018-04-11 16:57:45 -07003043void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3044 RTC_DCHECK(network_thread()->IsCurrent());
3045 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003046 if (transport_controller_) {
3047 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003048 }
3049
3050 for (auto transceiver : transceivers_) {
3051 auto* channel = transceiver->internal()->channel();
3052 if (channel) {
3053 channel->SetMetricsObserver(uma_observer_);
3054 }
3055 }
3056
deadbeef293e9262017-01-11 12:28:30 -08003057 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003058 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003059 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003060}
3061
Niels Möller0c4f7be2018-05-07 14:01:37 +02003062RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003063 if (!worker_thread()->IsCurrent()) {
3064 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003065 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003066 }
3067
Niels Möller0c4f7be2018-05-07 14:01:37 +02003068 const bool has_min = bitrate.min_bitrate_bps.has_value();
3069 const bool has_start = bitrate.start_bitrate_bps.has_value();
3070 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003071 if (has_min && *bitrate.min_bitrate_bps < 0) {
3072 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3073 "min_bitrate_bps <= 0");
3074 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003075 if (has_start) {
3076 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003078 "start_bitrate_bps < min_bitrate_bps");
3079 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3081 "curent_bitrate_bps < 0");
3082 }
3083 }
3084 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003085 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003086 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003087 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003088 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3089 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3090 "max_bitrate_bps < min_bitrate_bps");
3091 } else if (*bitrate.max_bitrate_bps < 0) {
3092 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3093 "max_bitrate_bps < 0");
3094 }
3095 }
3096
zstein4b979802017-06-02 14:37:37 -07003097 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003098 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003099
3100 return RTCError::OK();
3101}
3102
Alex Narest78609d52017-10-20 10:37:47 +02003103void PeerConnection::SetBitrateAllocationStrategy(
3104 std::unique_ptr<rtc::BitrateAllocationStrategy>
3105 bitrate_allocation_strategy) {
3106 rtc::Thread* worker_thread = factory_->worker_thread();
3107 if (!worker_thread->IsCurrent()) {
3108 rtc::BitrateAllocationStrategy* strategy_raw =
3109 bitrate_allocation_strategy.release();
3110 auto functor = [this, strategy_raw]() {
3111 call_->SetBitrateAllocationStrategy(
3112 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3113 };
3114 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3115 return;
3116 }
3117 RTC_DCHECK(call_.get());
3118 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3119}
3120
henrika5f6bf242017-11-01 11:06:56 +01003121void PeerConnection::SetAudioPlayout(bool playout) {
3122 if (!worker_thread()->IsCurrent()) {
3123 worker_thread()->Invoke<void>(
3124 RTC_FROM_HERE,
3125 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3126 return;
3127 }
3128 auto audio_state =
3129 factory_->channel_manager()->media_engine()->GetAudioState();
3130 audio_state->SetPlayout(playout);
3131}
3132
3133void PeerConnection::SetAudioRecording(bool recording) {
3134 if (!worker_thread()->IsCurrent()) {
3135 worker_thread()->Invoke<void>(
3136 RTC_FROM_HERE,
3137 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3138 return;
3139 }
3140 auto audio_state =
3141 factory_->channel_manager()->media_engine()->GetAudioState();
3142 audio_state->SetRecording(recording);
3143}
3144
Steve Anton8c0f7a72017-10-03 10:03:10 -07003145std::unique_ptr<rtc::SSLCertificate>
3146PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003147 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3148 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003149 return nullptr;
3150 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003151 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003152}
3153
Zhi Huang70b820f2018-01-27 14:16:15 -08003154std::unique_ptr<rtc::SSLCertChain>
3155PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003156 auto audio_transceiver = GetFirstAudioTransceiver();
3157 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003158 return nullptr;
3159 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003160 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003161 audio_transceiver->internal()->channel()->transport_name());
3162}
3163
3164rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3165PeerConnection::GetFirstAudioTransceiver() const {
3166 for (auto transceiver : transceivers_) {
3167 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3168 return transceiver;
3169 }
3170 }
3171 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003172}
3173
ivoc14d5dbe2016-07-04 07:06:55 -07003174bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3175 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003176 // TODO(eladalon): It would be better to not allow negative values into PC.
3177 const size_t max_size = (max_size_bytes < 0)
3178 ? RtcEventLog::kUnlimitedOutput
3179 : rtc::saturated_cast<size_t>(max_size_bytes);
3180 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003181 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3182 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003183}
3184
Bjorn Tereliusde939432017-11-20 17:38:14 +01003185bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3186 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003187 // TODO(eladalon): In C++14, this can be done with a lambda.
3188 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003189 bool operator()() {
3190 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3191 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003192 PeerConnection* const pc;
3193 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003194 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003195 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003196 return worker_thread()->Invoke<bool>(
3197 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003198}
3199
3200void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003201 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003202 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3203}
3204
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003205const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003206 return pending_local_description_ ? pending_local_description_.get()
3207 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003208}
3209
3210const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003211 return pending_remote_description_ ? pending_remote_description_.get()
3212 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213}
3214
deadbeeffe4a8a42016-12-20 17:56:17 -08003215const SessionDescriptionInterface* PeerConnection::current_local_description()
3216 const {
Steve Anton75737c02017-11-06 10:37:17 -08003217 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003218}
3219
3220const SessionDescriptionInterface* PeerConnection::current_remote_description()
3221 const {
Steve Anton75737c02017-11-06 10:37:17 -08003222 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003223}
3224
3225const SessionDescriptionInterface* PeerConnection::pending_local_description()
3226 const {
Steve Anton75737c02017-11-06 10:37:17 -08003227 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003228}
3229
3230const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3231 const {
Steve Anton75737c02017-11-06 10:37:17 -08003232 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003233}
3234
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003235void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003236 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003237 // Update stats here so that we have the most recent stats for tracks and
3238 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003239 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003240
Steve Anton75737c02017-11-06 10:37:17 -08003241 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003242 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003243
Steve Anton8af21862017-12-15 11:20:13 -08003244 for (auto transceiver : transceivers_) {
3245 transceiver->Stop();
3246 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003247
3248 // Ensure that all asynchronous stats requests are completed before destroying
3249 // the transport controller below.
3250 if (stats_collector_) {
3251 stats_collector_->WaitForPendingRequest();
3252 }
3253
3254 // Don't destroy BaseChannels until after stats has been cleaned up so that
3255 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003256 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003257
Qingsi Wang93a84392018-01-30 17:13:09 -08003258 // The event log is used in the transport controller, which must be outlived
3259 // by the former. CreateOffer by the peer connection is implemented
3260 // asynchronously and if the peer connection is closed without resetting the
3261 // WebRTC session description factory, the session description factory would
3262 // call the transport controller.
3263 webrtc_session_desc_factory_.reset();
3264 transport_controller_.reset();
3265
deadbeef42a42632017-03-10 15:18:00 -08003266 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003267 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3268 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003269
Steve Anton978b8762017-09-29 12:15:02 -07003270 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003271 call_.reset();
3272 // The event log must outlive call (and any other object that uses it).
3273 event_log_.reset();
3274 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003275 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276}
3277
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003278void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003279 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003280 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3281 SetSessionDescriptionMsg* param =
3282 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3283 param->observer->OnSuccess();
3284 delete param;
3285 break;
3286 }
3287 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3288 SetSessionDescriptionMsg* param =
3289 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003290 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291 delete param;
3292 break;
3293 }
deadbeefab9b2d12015-10-14 11:33:11 -07003294 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3295 CreateSessionDescriptionMsg* param =
3296 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003297 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003298 delete param;
3299 break;
3300 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003301 case MSG_GETSTATS: {
3302 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003303 StatsReports reports;
3304 stats_->GetStats(param->track, &reports);
3305 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003306 delete param;
3307 break;
3308 }
deadbeefbd292462015-12-14 18:15:29 -08003309 case MSG_FREE_DATACHANNELS: {
3310 sctp_data_channels_to_free_.clear();
3311 break;
3312 }
Harald Alvestrand19793842018-06-25 12:03:50 +02003313 case MSG_REPORT_USAGE_PATTERN: {
3314 ReportUsagePattern();
3315 break;
3316 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003318 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319 break;
3320 }
3321}
3322
Steve Antonafb0bb72018-02-20 11:35:37 -08003323cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3324 RTC_DCHECK(!IsUnifiedPlan());
3325 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3326 GetAudioTransceiver()->internal()->channel());
3327 if (voice_channel) {
3328 return voice_channel->media_channel();
3329 } else {
3330 return nullptr;
3331 }
3332}
3333
3334cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3335 RTC_DCHECK(!IsUnifiedPlan());
3336 auto* video_channel = static_cast<cricket::VideoChannel*>(
3337 GetVideoTransceiver()->internal()->channel());
3338 if (video_channel) {
3339 return video_channel->media_channel();
3340 } else {
3341 return nullptr;
3342 }
3343}
3344
Steve Anton4171afb2017-11-20 10:20:22 -08003345void PeerConnection::CreateAudioReceiver(
3346 MediaStreamInterface* stream,
3347 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003348 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3349 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003350 auto* audio_receiver = new AudioRtpReceiver(
3351 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003352 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003353 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3354 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3355 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003356 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003357 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003358 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003359}
3360
Steve Anton4171afb2017-11-20 10:20:22 -08003361void PeerConnection::CreateVideoReceiver(
3362 MediaStreamInterface* stream,
3363 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003364 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3365 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003366 auto* video_receiver = new VideoRtpReceiver(
3367 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003368 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003369 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3370 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3371 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003372 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003373 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003374 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375}
3376
deadbeef70ab1a12015-09-28 16:53:55 -07003377// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3378// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003379rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003380 const RtpSenderInfo& remote_sender_info) {
3381 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3382 if (!receiver) {
3383 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3384 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003385 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003386 }
Steve Anton4171afb2017-11-20 10:20:22 -08003387 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3388 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3389 } else {
3390 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3391 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003392 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393}
3394
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003395void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3396 MediaStreamInterface* stream) {
3397 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003398 RTC_DCHECK(track);
3399 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003400 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003401 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003402 // We already have a sender for this track, so just change the stream_id
3403 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003404 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003405 return;
3406 }
3407
3408 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003409 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3410 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003411 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003412 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003413 // If the sender has already been configured in SDP, we call SetSsrc,
3414 // which will connect the sender to the underlying transport. This can
3415 // occur if a local session description that contains the ID of the sender
3416 // is set before AddStream is called. It can also occur if the local
3417 // session description is not changed and RemoveStream is called, and
3418 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003419 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003420 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003421 if (sender_info) {
3422 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003423 }
3424}
3425
3426// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3427// indefinitely, when we have unified plan SDP.
3428void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3429 MediaStreamInterface* stream) {
3430 RTC_DCHECK(!IsClosed());
3431 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003432 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003433 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3434 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003435 return;
3436 }
Steve Anton4171afb2017-11-20 10:20:22 -08003437 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003438}
3439
3440void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3441 MediaStreamInterface* stream) {
3442 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003443 RTC_DCHECK(track);
3444 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003445 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003446 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003447 // We already have a sender for this track, so just change the stream_id
3448 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003449 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003450 return;
3451 }
3452
3453 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003454 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3455 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003456 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003457 GetVideoTransceiver()->internal()->AddSender(new_sender);
3458 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003459 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003460 if (sender_info) {
3461 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003462 }
3463}
3464
3465void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3466 MediaStreamInterface* stream) {
3467 RTC_DCHECK(!IsClosed());
3468 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003469 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003470 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3471 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003472 return;
3473 }
Steve Anton4171afb2017-11-20 10:20:22 -08003474 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003475}
3476
Steve Antonba818672017-11-06 10:21:57 -08003477void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003478 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003479 if (ice_connection_state_ == new_state) {
3480 return;
3481 }
3482
deadbeefcbecd352015-09-23 11:50:27 -07003483 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003484 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003485 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003486 return;
3487 }
Steve Antonba818672017-11-06 10:21:57 -08003488
Mirko Bonadei675513b2017-11-09 11:09:25 +01003489 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3490 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003491 RTC_DCHECK(ice_connection_state_ !=
3492 PeerConnectionInterface::kIceConnectionClosed);
3493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003494 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003495 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003496}
3497
3498void PeerConnection::OnIceGatheringChange(
3499 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003500 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003501 if (IsClosed()) {
3502 return;
3503 }
3504 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003505 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506}
3507
jbauch81bf7b02017-03-25 08:31:12 -07003508void PeerConnection::OnIceCandidate(
3509 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003510 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003511 if (IsClosed()) {
3512 return;
3513 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003514 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003515 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003516}
3517
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003518void PeerConnection::OnIceCandidatesRemoved(
3519 const std::vector<cricket::Candidate>& candidates) {
3520 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003521 if (IsClosed()) {
3522 return;
3523 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003524 observer_->OnIceCandidatesRemoved(candidates);
3525}
3526
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003527void PeerConnection::ChangeSignalingState(
3528 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003529 RTC_DCHECK(signaling_thread()->IsCurrent());
3530 if (signaling_state_ == signaling_state) {
3531 return;
3532 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003533 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3534 << GetSignalingStateString(signaling_state_)
3535 << " New state: "
3536 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003537 signaling_state_ = signaling_state;
3538 if (signaling_state == kClosed) {
3539 ice_connection_state_ = kIceConnectionClosed;
3540 observer_->OnIceConnectionChange(ice_connection_state_);
3541 if (ice_gathering_state_ != kIceGatheringComplete) {
3542 ice_gathering_state_ = kIceGatheringComplete;
3543 observer_->OnIceGatheringChange(ice_gathering_state_);
3544 }
3545 }
3546 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003547}
3548
deadbeefeb459812015-12-15 19:24:43 -08003549void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3550 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003551 if (IsClosed()) {
3552 return;
3553 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003554 AddAudioTrack(track, stream);
3555 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003556}
3557
deadbeefeb459812015-12-15 19:24:43 -08003558void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3559 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003560 if (IsClosed()) {
3561 return;
3562 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003563 RemoveAudioTrack(track, stream);
3564 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003565}
3566
3567void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3568 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003569 if (IsClosed()) {
3570 return;
3571 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003572 AddVideoTrack(track, stream);
3573 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003574}
3575
3576void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3577 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003578 if (IsClosed()) {
3579 return;
3580 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003581 RemoveVideoTrack(track, stream);
3582 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003583}
3584
Henrik Boström31638672017-11-23 17:48:32 +01003585void PeerConnection::PostSetSessionDescriptionSuccess(
3586 SetSessionDescriptionObserver* observer) {
3587 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3588 signaling_thread()->Post(RTC_FROM_HERE, this,
3589 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3590}
3591
deadbeefab9b2d12015-10-14 11:33:11 -07003592void PeerConnection::PostSetSessionDescriptionFailure(
3593 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003594 RTCError&& error) {
3595 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003596 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003597 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003598 signaling_thread()->Post(RTC_FROM_HERE, this,
3599 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003600}
3601
3602void PeerConnection::PostCreateSessionDescriptionFailure(
3603 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003604 RTCError error) {
3605 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003606 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003607 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003608 signaling_thread()->Post(RTC_FROM_HERE, this,
3609 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003610}
3611
zhihuang1c378ed2017-08-17 14:10:50 -07003612void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003613 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003614 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003615 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003616
Steve Antondcc3c022017-12-22 16:02:54 -08003617 if (IsUnifiedPlan()) {
3618 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3619 } else {
3620 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3621 }
3622
Steve Antonfa2260d2017-12-28 16:38:23 -08003623 // Intentionally unset the data channel type for RTP data channel with the
3624 // second condition. Otherwise the RTP data channels would be successfully
3625 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3626 // when building with chromium. We want to leave RTP data channels broken, so
3627 // people won't try to use them.
3628 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3629 session_options->data_channel_type = data_channel_type();
3630 }
3631
Steve Antondcc3c022017-12-22 16:02:54 -08003632 // Apply ICE restart flag and renomination flag.
3633 for (auto& options : session_options->media_description_options) {
3634 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3635 options.transport_options.enable_ice_renomination =
3636 configuration_.enable_ice_renomination;
3637 }
3638
3639 session_options->rtcp_cname = rtcp_cname_;
3640 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003641 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003642}
3643
3644void PeerConnection::GetOptionsForPlanBOffer(
3645 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3646 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003647 // Figure out transceiver directional preferences.
3648 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3649 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3650
3651 // By default, generate sendrecv/recvonly m= sections.
3652 bool recv_audio = true;
3653 bool recv_video = true;
3654
3655 // By default, only offer a new m= section if we have media to send with it.
3656 bool offer_new_audio_description = send_audio;
3657 bool offer_new_video_description = send_video;
3658 bool offer_new_data_description = HasDataChannels();
3659
3660 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003661 if (offer_answer_options.offer_to_receive_audio !=
3662 RTCOfferAnswerOptions::kUndefined) {
3663 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003664 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003665 offer_new_audio_description ||
3666 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003667 }
Steve Antondcc3c022017-12-22 16:02:54 -08003668 if (offer_answer_options.offer_to_receive_video !=
3669 RTCOfferAnswerOptions::kUndefined) {
3670 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003671 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003672 offer_new_video_description ||
3673 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003674 }
3675
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003676 absl::optional<size_t> audio_index;
3677 absl::optional<size_t> video_index;
3678 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003679 // If a current description exists, generate m= sections in the same order,
3680 // using the first audio/video/data section that appears and rejecting
3681 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003682 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003683 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003684 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003685 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3686 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3687 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003688 }
3689
zhihuang1c378ed2017-08-17 14:10:50 -07003690 // Add audio/video/data m= sections to the end if needed.
3691 if (!audio_index && offer_new_audio_description) {
3692 session_options->media_description_options.push_back(
3693 cricket::MediaDescriptionOptions(
3694 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003695 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3696 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003697 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003698 }
zhihuang1c378ed2017-08-17 14:10:50 -07003699 if (!video_index && offer_new_video_description) {
3700 session_options->media_description_options.push_back(
3701 cricket::MediaDescriptionOptions(
3702 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003703 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3704 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003705 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003706 }
zhihuang1c378ed2017-08-17 14:10:50 -07003707 if (!data_index && offer_new_data_description) {
3708 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003709 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003710 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003711 }
3712
3713 cricket::MediaDescriptionOptions* audio_media_description_options =
3714 !audio_index ? nullptr
3715 : &session_options->media_description_options[*audio_index];
3716 cricket::MediaDescriptionOptions* video_media_description_options =
3717 !video_index ? nullptr
3718 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003719
Steve Anton4171afb2017-11-20 10:20:22 -08003720 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003721 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003722}
3723
3724// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3725// and return a reference to it.
3726// Generated MIDs should be no more than 3 bytes long to take up less space in
3727// the RTP packet.
3728static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3729 RTC_DCHECK(used_mids);
3730 // We're boring: just generate MIDs 0, 1, 2, ...
3731 size_t i = 0;
3732 std::set<std::string>::iterator it;
3733 bool inserted;
3734 do {
3735 std::string mid = rtc::ToString(i++);
3736 auto insert_result = used_mids->insert(mid);
3737 it = insert_result.first;
3738 inserted = insert_result.second;
3739 } while (!inserted);
3740 return *it;
3741}
3742
3743static cricket::MediaDescriptionOptions
3744GetMediaDescriptionOptionsForTransceiver(
3745 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3746 transceiver,
3747 const std::string& mid) {
3748 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003749 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003750 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003751 // This behavior is specified in JSEP. The gist is that:
3752 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3753 // sendrecv.
3754 // 2. If the MSID is included, then it must be included in any subsequent
3755 // offer/answer exactly the same until the RtpTransceiver is stopped.
3756 if (!transceiver->stopped() &&
3757 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3758 transceiver->internal()->has_ever_been_used_to_send())) {
3759 cricket::SenderOptions sender_options;
3760 sender_options.track_id = transceiver->sender()->id();
3761 sender_options.stream_ids = transceiver->sender()->stream_ids();
3762 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3763 // set in the RTP parameters when the transceiver was added.
3764 sender_options.num_sim_layers = 1;
3765 media_description_options.sender_options.push_back(sender_options);
3766 }
Steve Antondcc3c022017-12-22 16:02:54 -08003767 return media_description_options;
3768}
3769
3770void PeerConnection::GetOptionsForUnifiedPlanOffer(
3771 const RTCOfferAnswerOptions& offer_answer_options,
3772 cricket::MediaSessionOptions* session_options) {
3773 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3774 // Offers) and 5.2.2 (Subsequent Offers).
3775 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3776 const ContentInfos& local_contents =
3777 (local_description() ? local_description()->description()->contents()
3778 : ContentInfos());
3779 const ContentInfos& remote_contents =
3780 (remote_description() ? remote_description()->description()->contents()
3781 : ContentInfos());
3782 // The mline indices that can be recycled. New transceivers should reuse these
3783 // slots first.
3784 std::queue<size_t> recycleable_mline_indices;
3785 // Track the MIDs used in previous offer/answer exchanges and the current
3786 // offer so that new, unique MIDs are generated.
3787 std::set<std::string> used_mids = seen_mids_;
3788 // First, go through each media section that exists in either the local or
3789 // remote description and generate a media section in this offer for the
3790 // associated transceiver. If a media section can be recycled, generate a
3791 // default, rejected media section here that can be later overwritten.
3792 for (size_t i = 0;
3793 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3794 // Either |local_content| or |remote_content| is non-null.
3795 const ContentInfo* local_content =
3796 (i < local_contents.size() ? &local_contents[i] : nullptr);
3797 const ContentInfo* remote_content =
3798 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3799 bool had_been_rejected = (local_content && local_content->rejected) ||
3800 (remote_content && remote_content->rejected);
3801 const std::string& mid =
3802 (local_content ? local_content->name : remote_content->name);
3803 cricket::MediaType media_type =
3804 (local_content ? local_content->media_description()->type()
3805 : remote_content->media_description()->type());
3806 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3807 media_type == cricket::MEDIA_TYPE_VIDEO) {
3808 auto transceiver = GetAssociatedTransceiver(mid);
3809 RTC_CHECK(transceiver);
3810 // A media section is considered eligible for recycling if it is marked as
3811 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003812 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003813 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003814 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3815 RtpTransceiverDirection::kInactive,
3816 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003817 recycleable_mline_indices.push(i);
3818 } else {
3819 session_options->media_description_options.push_back(
3820 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3821 // CreateOffer shouldn't really cause any state changes in
3822 // PeerConnection, but we need a way to match new transceivers to new
3823 // media sections in SetLocalDescription and JSEP specifies this is done
3824 // by recording the index of the media section generated for the
3825 // transceiver in the offer.
3826 transceiver->internal()->set_mline_index(i);
3827 }
3828 } else {
3829 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003830 RTC_CHECK(GetDataMid());
3831 if (had_been_rejected || mid != *GetDataMid()) {
3832 session_options->media_description_options.push_back(
3833 GetMediaDescriptionOptionsForRejectedData(mid));
3834 } else {
3835 session_options->media_description_options.push_back(
3836 GetMediaDescriptionOptionsForActiveData(mid));
3837 }
Steve Antondcc3c022017-12-22 16:02:54 -08003838 }
3839 }
3840 // Next, look for transceivers that are newly added (that is, are not stopped
3841 // and not associated). Reuse media sections marked as recyclable first,
3842 // otherwise append to the end of the offer. New media sections should be
3843 // added in the order they were added to the PeerConnection.
3844 for (auto transceiver : transceivers_) {
3845 if (transceiver->mid() || transceiver->stopped()) {
3846 continue;
3847 }
3848 size_t mline_index;
3849 if (!recycleable_mline_indices.empty()) {
3850 mline_index = recycleable_mline_indices.front();
3851 recycleable_mline_indices.pop();
3852 session_options->media_description_options[mline_index] =
3853 GetMediaDescriptionOptionsForTransceiver(transceiver,
3854 AllocateMid(&used_mids));
3855 } else {
3856 mline_index = session_options->media_description_options.size();
3857 session_options->media_description_options.push_back(
3858 GetMediaDescriptionOptionsForTransceiver(transceiver,
3859 AllocateMid(&used_mids)));
3860 }
3861 // See comment above for why CreateOffer changes the transceiver's state.
3862 transceiver->internal()->set_mline_index(mline_index);
3863 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003864 // Lastly, add a m-section if we have local data channels and an m section
3865 // does not already exist.
3866 if (!GetDataMid() && HasDataChannels()) {
3867 session_options->media_description_options.push_back(
3868 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3869 }
Steve Antondcc3c022017-12-22 16:02:54 -08003870}
3871
3872void PeerConnection::GetOptionsForAnswer(
3873 const RTCOfferAnswerOptions& offer_answer_options,
3874 cricket::MediaSessionOptions* session_options) {
3875 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3876
3877 if (IsUnifiedPlan()) {
3878 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3879 } else {
3880 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3881 }
3882
Steve Antonfa2260d2017-12-28 16:38:23 -08003883 // Intentionally unset the data channel type for RTP data channel. Otherwise
3884 // the RTP data channels would be successfully negotiated by default and the
3885 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3886 // We want to leave RTP data channels broken, so people won't try to use them.
3887 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3888 session_options->data_channel_type = data_channel_type();
3889 }
3890
Steve Antondcc3c022017-12-22 16:02:54 -08003891 // Apply ICE renomination flag.
3892 for (auto& options : session_options->media_description_options) {
3893 options.transport_options.enable_ice_renomination =
3894 configuration_.enable_ice_renomination;
3895 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003896
3897 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003898 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003899 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003900}
3901
Steve Antondcc3c022017-12-22 16:02:54 -08003902void PeerConnection::GetOptionsForPlanBAnswer(
3903 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003904 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003905 // Figure out transceiver directional preferences.
3906 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3907 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3908
3909 // By default, generate sendrecv/recvonly m= sections. The direction is also
3910 // restricted by the direction in the offer.
3911 bool recv_audio = true;
3912 bool recv_video = true;
3913
3914 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003915 if (offer_answer_options.offer_to_receive_audio !=
3916 RTCOfferAnswerOptions::kUndefined) {
3917 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003918 }
Steve Antondcc3c022017-12-22 16:02:54 -08003919 if (offer_answer_options.offer_to_receive_video !=
3920 RTCOfferAnswerOptions::kUndefined) {
3921 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003922 }
3923
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003924 absl::optional<size_t> audio_index;
3925 absl::optional<size_t> video_index;
3926 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003927
3928 // Generate m= sections that match those in the offer.
3929 // Note that mediasession.cc will handle intersection our preferred
3930 // direction with the offered direction.
3931 GenerateMediaDescriptionOptions(
3932 remote_description(),
3933 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3934 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3935 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003936
3937 cricket::MediaDescriptionOptions* audio_media_description_options =
3938 !audio_index ? nullptr
3939 : &session_options->media_description_options[*audio_index];
3940 cricket::MediaDescriptionOptions* video_media_description_options =
3941 !video_index ? nullptr
3942 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003943
Steve Anton4171afb2017-11-20 10:20:22 -08003944 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003945 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003946}
zhihuangaf388472016-11-02 16:49:48 -07003947
Steve Antondcc3c022017-12-22 16:02:54 -08003948void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3949 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3950 cricket::MediaSessionOptions* session_options) {
3951 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3952 // Answers) and 5.3.2 (Subsequent Answers).
3953 RTC_DCHECK(remote_description());
3954 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3955 for (const ContentInfo& content :
3956 remote_description()->description()->contents()) {
3957 cricket::MediaType media_type = content.media_description()->type();
3958 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3959 media_type == cricket::MEDIA_TYPE_VIDEO) {
3960 auto transceiver = GetAssociatedTransceiver(content.name);
3961 RTC_CHECK(transceiver);
3962 session_options->media_description_options.push_back(
3963 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3964 } else {
3965 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003966 // Reject all data sections if data channels are disabled.
3967 // Reject a data section if it has already been rejected.
3968 // Reject all data sections except for the first one.
3969 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3970 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003971 session_options->media_description_options.push_back(
3972 GetMediaDescriptionOptionsForRejectedData(content.name));
3973 } else {
3974 session_options->media_description_options.push_back(
3975 GetMediaDescriptionOptionsForActiveData(content.name));
3976 }
Steve Antondcc3c022017-12-22 16:02:54 -08003977 }
3978 }
htaa2a49d92016-03-04 02:51:39 -08003979}
3980
zhihuang1c378ed2017-08-17 14:10:50 -07003981void PeerConnection::GenerateMediaDescriptionOptions(
3982 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003983 RtpTransceiverDirection audio_direction,
3984 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003985 absl::optional<size_t>* audio_index,
3986 absl::optional<size_t>* video_index,
3987 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003988 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003989 for (const cricket::ContentInfo& content :
3990 session_desc->description()->contents()) {
3991 if (IsAudioContent(&content)) {
3992 // If we already have an audio m= section, reject this extra one.
3993 if (*audio_index) {
3994 session_options->media_description_options.push_back(
3995 cricket::MediaDescriptionOptions(
3996 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003997 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003998 } else {
3999 session_options->media_description_options.push_back(
4000 cricket::MediaDescriptionOptions(
4001 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004002 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004003 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004004 }
4005 } else if (IsVideoContent(&content)) {
4006 // If we already have an video m= section, reject this extra one.
4007 if (*video_index) {
4008 session_options->media_description_options.push_back(
4009 cricket::MediaDescriptionOptions(
4010 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004011 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004012 } else {
4013 session_options->media_description_options.push_back(
4014 cricket::MediaDescriptionOptions(
4015 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004016 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004017 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004018 }
4019 } else {
4020 RTC_DCHECK(IsDataContent(&content));
4021 // If we already have an data m= section, reject this extra one.
4022 if (*data_index) {
4023 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004024 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004025 } else {
4026 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004027 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004028 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004029 }
4030 }
htaa2a49d92016-03-04 02:51:39 -08004031 }
deadbeefab9b2d12015-10-14 11:33:11 -07004032}
4033
Steve Antonfa2260d2017-12-28 16:38:23 -08004034cricket::MediaDescriptionOptions
4035PeerConnection::GetMediaDescriptionOptionsForActiveData(
4036 const std::string& mid) const {
4037 // Direction for data sections is meaningless, but legacy endpoints might
4038 // expect sendrecv.
4039 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4040 RtpTransceiverDirection::kSendRecv,
4041 /*stopped=*/false);
4042 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4043 return options;
4044}
4045
4046cricket::MediaDescriptionOptions
4047PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4048 const std::string& mid) const {
4049 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4050 RtpTransceiverDirection::kInactive,
4051 /*stopped=*/true);
4052 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4053 return options;
4054}
4055
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004056absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004057 switch (data_channel_type_) {
4058 case cricket::DCT_RTP:
4059 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004060 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004061 }
4062 return rtp_data_channel_->content_name();
4063 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004064 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004065 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004066 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004067 }
4068}
4069
Steve Anton4171afb2017-11-20 10:20:22 -08004070void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4071 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4072 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004073 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004074}
4075
Steve Anton4171afb2017-11-20 10:20:22 -08004076void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004077 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004078 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004079 cricket::MediaType media_type,
4080 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004081 RTC_DCHECK(!IsUnifiedPlan());
4082
Steve Anton4171afb2017-11-20 10:20:22 -08004083 std::vector<RtpSenderInfo>* current_senders =
4084 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004085
Steve Anton4171afb2017-11-20 10:20:22 -08004086 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004087 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004088 for (auto sender_it = current_senders->begin();
4089 sender_it != current_senders->end();
4090 /* incremented manually */) {
4091 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004092 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004093 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004094 std::string params_stream_id;
4095 if (params) {
4096 params_stream_id =
4097 (!params->first_stream_id().empty() ? params->first_stream_id()
4098 : kDefaultStreamId);
4099 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004100 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004101 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004102 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004103 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004104 sender_exists) {
4105 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004106 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004107 OnRemoteSenderRemoved(info, media_type);
4108 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004109 }
4110 }
4111
Steve Anton4171afb2017-11-20 10:20:22 -08004112 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004113 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004114 if (!params.has_ssrcs()) {
4115 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4116 // sender, this means it is coming from a Unified Plan endpoint,so we just
4117 // create a default.
4118 default_sender_needed = true;
4119 break;
4120 }
4121
Seth Hampson845e8782018-03-02 11:34:10 -08004122 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004123 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004124 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4125 // not supported in Plan B, we just take the first here and create the
4126 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004127 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004128 (!params.first_stream_id().empty() ? params.first_stream_id()
4129 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004130 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004131 uint32_t ssrc = params.first_ssrc();
4132
4133 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004134 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004135 if (!stream) {
4136 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004137 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004138 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004139 remote_streams_->AddStream(stream);
4140 new_streams->AddStream(stream);
4141 }
4142
Steve Anton4171afb2017-11-20 10:20:22 -08004143 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004144 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004145 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004146 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004147 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004148 }
4149 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004150
Steve Anton4171afb2017-11-20 10:20:22 -08004151 // Add default sender if necessary.
4152 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004153 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004154 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004155 if (!default_stream) {
4156 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004157 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004158 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004159 remote_streams_->AddStream(default_stream);
4160 new_streams->AddStream(default_stream);
4161 }
Steve Anton4171afb2017-11-20 10:20:22 -08004162 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4163 ? kDefaultAudioSenderId
4164 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004165 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004166 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004167 if (!default_sender_info) {
4168 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004169 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004170 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004171 }
4172 }
deadbeefab9b2d12015-10-14 11:33:11 -07004173}
4174
Steve Anton4171afb2017-11-20 10:20:22 -08004175void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4176 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004177 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4178 << " receiver for track_id=" << sender_info.sender_id
4179 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004180
Steve Anton3d954a62018-04-02 11:27:23 -07004181 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004182 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004183 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004184 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004185 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004186 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004187 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004188 }
4189}
4190
Steve Anton4171afb2017-11-20 10:20:22 -08004191void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4192 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004193 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4194 << " receiver for track_id=" << sender_info.sender_id
4195 << " and stream_id=" << sender_info.stream_id;
4196
Seth Hampson845e8782018-03-02 11:34:10 -08004197 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004198
Henrik Boström933d8b02017-10-10 10:05:16 -07004199 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004200 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004201 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4202 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004203 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004204 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004205 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004206 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004207 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004208 }
4209 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004210 // Stopping or destroying a VideoRtpReceiver will end the
4211 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004212 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004213 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004214 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004215 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004216 // There's no guarantee the track is still available, e.g. the track may
4217 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004218 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004219 }
4220 } else {
nisseede5da42017-01-12 05:15:36 -08004221 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004222 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004223 if (receiver) {
4224 observer_->OnRemoveTrack(receiver);
4225 }
deadbeefab9b2d12015-10-14 11:33:11 -07004226}
4227
4228void PeerConnection::UpdateEndedRemoteMediaStreams() {
4229 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4230 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4231 MediaStreamInterface* stream = remote_streams_->at(i);
4232 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4233 streams_to_remove.push_back(stream);
4234 }
4235 }
4236
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004237 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004238 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004239 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004240 }
4241}
4242
Steve Anton4171afb2017-11-20 10:20:22 -08004243void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004244 const std::vector<cricket::StreamParams>& streams,
4245 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004246 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004247
Seth Hampson845e8782018-03-02 11:34:10 -08004248 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004249 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004250 for (auto sender_it = current_senders->begin();
4251 sender_it != current_senders->end();
4252 /* incremented manually */) {
4253 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004254 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004255 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4256 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004257 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004258 OnLocalSenderRemoved(info, media_type);
4259 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004260 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004261 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004262 }
4263 }
4264
Steve Anton4171afb2017-11-20 10:20:22 -08004265 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004266 for (const cricket::StreamParams& params : streams) {
4267 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004268 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004269 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004270 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004271 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004272 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004273 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004274 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004275 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004276 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004277 }
4278 }
4279}
4280
Steve Anton4171afb2017-11-20 10:20:22 -08004281void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4282 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004283 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004284 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004285 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004286 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4287 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004288 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004289 return;
4290 }
4291
deadbeeffac06552015-11-25 11:26:01 -08004292 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004293 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004294 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004295 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004296 }
deadbeeffac06552015-11-25 11:26:01 -08004297
Seth Hampson5b4f0752018-04-02 16:31:36 -07004298 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004299 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004300}
4301
Steve Anton4171afb2017-11-20 10:20:22 -08004302void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4303 cricket::MediaType media_type) {
4304 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004305 if (!sender) {
4306 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004307 // SessionDescriptions has been renegotiated.
4308 return;
4309 }
deadbeeffac06552015-11-25 11:26:01 -08004310
4311 // A sender has been removed from the SessionDescription but it's still
4312 // associated with the PeerConnection. This only occurs if the SDP doesn't
4313 // match with the calls to CreateSender, AddStream and RemoveStream.
4314 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004315 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004316 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004317 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004318 }
deadbeeffac06552015-11-25 11:26:01 -08004319
Steve Anton4171afb2017-11-20 10:20:22 -08004320 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004321}
4322
4323void PeerConnection::UpdateLocalRtpDataChannels(
4324 const cricket::StreamParamsVec& streams) {
4325 std::vector<std::string> existing_channels;
4326
4327 // Find new and active data channels.
4328 for (const cricket::StreamParams& params : streams) {
4329 // |it->sync_label| is actually the data channel label. The reason is that
4330 // we use the same naming of data channels as we do for
4331 // MediaStreams and Tracks.
4332 // For MediaStreams, the sync_label is the MediaStream label and the
4333 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004334 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004335 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004336 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004337 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004338 continue;
4339 }
4340 // Set the SSRC the data channel should use for sending.
4341 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4342 existing_channels.push_back(data_channel_it->first);
4343 }
4344
4345 UpdateClosingRtpDataChannels(existing_channels, true);
4346}
4347
4348void PeerConnection::UpdateRemoteRtpDataChannels(
4349 const cricket::StreamParamsVec& streams) {
4350 std::vector<std::string> existing_channels;
4351
4352 // Find new and active data channels.
4353 for (const cricket::StreamParams& params : streams) {
4354 // The data channel label is either the mslabel or the SSRC if the mslabel
4355 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004356 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004357 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004358 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004359 auto data_channel_it = rtp_data_channels_.find(label);
4360 if (data_channel_it == rtp_data_channels_.end()) {
4361 // This is a new data channel.
4362 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4363 } else {
4364 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4365 }
4366 existing_channels.push_back(label);
4367 }
4368
4369 UpdateClosingRtpDataChannels(existing_channels, false);
4370}
4371
4372void PeerConnection::UpdateClosingRtpDataChannels(
4373 const std::vector<std::string>& active_channels,
4374 bool is_local_update) {
4375 auto it = rtp_data_channels_.begin();
4376 while (it != rtp_data_channels_.end()) {
4377 DataChannel* data_channel = it->second;
4378 if (std::find(active_channels.begin(), active_channels.end(),
4379 data_channel->label()) != active_channels.end()) {
4380 ++it;
4381 continue;
4382 }
4383
4384 if (is_local_update) {
4385 data_channel->SetSendSsrc(0);
4386 } else {
4387 data_channel->RemotePeerRequestClose();
4388 }
4389
4390 if (data_channel->state() == DataChannel::kClosed) {
4391 rtp_data_channels_.erase(it);
4392 it = rtp_data_channels_.begin();
4393 } else {
4394 ++it;
4395 }
4396 }
4397}
4398
4399void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4400 uint32_t remote_ssrc) {
4401 rtc::scoped_refptr<DataChannel> channel(
4402 InternalCreateDataChannel(label, nullptr));
4403 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004404 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004405 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004406 return;
4407 }
4408 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004409 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4410 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004411 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004412}
4413
4414rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4415 const std::string& label,
4416 const InternalDataChannelInit* config) {
4417 if (IsClosed()) {
4418 return nullptr;
4419 }
Steve Anton75737c02017-11-06 10:37:17 -08004420 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004421 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004422 << "InternalCreateDataChannel: Data is not supported in this call.";
4423 return nullptr;
4424 }
4425 InternalDataChannelInit new_config =
4426 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004427 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004428 if (new_config.id < 0) {
4429 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004430 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004431 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004432 RTC_LOG(LS_ERROR)
4433 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004434 return nullptr;
4435 }
4436 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004437 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004438 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004439 return nullptr;
4440 }
4441 }
4442
Steve Anton75737c02017-11-06 10:37:17 -08004443 rtc::scoped_refptr<DataChannel> channel(
4444 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004445 if (!channel) {
4446 sid_allocator_.ReleaseSid(new_config.id);
4447 return nullptr;
4448 }
4449
4450 if (channel->data_channel_type() == cricket::DCT_RTP) {
4451 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004452 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4453 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004454 return nullptr;
4455 }
4456 rtp_data_channels_[channel->label()] = channel;
4457 } else {
4458 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4459 sctp_data_channels_.push_back(channel);
4460 channel->SignalClosed.connect(this,
4461 &PeerConnection::OnSctpDataChannelClosed);
4462 }
4463
Steve Anton2d8609c2018-01-23 16:38:46 -08004464 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004465 return channel;
4466}
4467
4468bool PeerConnection::HasDataChannels() const {
4469 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4470}
4471
4472void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4473 for (const auto& channel : sctp_data_channels_) {
4474 if (channel->id() < 0) {
4475 int sid;
4476 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004477 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004478 continue;
4479 }
4480 channel->SetSctpSid(sid);
4481 }
4482 }
4483}
4484
4485void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004486 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004487 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4488 ++it) {
4489 if (it->get() == channel) {
4490 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004491 // After the closing procedure is done, it's safe to use this ID for
4492 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004493 sid_allocator_.ReleaseSid(channel->id());
4494 }
deadbeefbd292462015-12-14 18:15:29 -08004495 // Since this method is triggered by a signal from the DataChannel,
4496 // we can't free it directly here; we need to free it asynchronously.
4497 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004498 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004499 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4500 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004501 return;
4502 }
4503 }
4504}
4505
deadbeefab9b2d12015-10-14 11:33:11 -07004506void PeerConnection::OnDataChannelDestroyed() {
4507 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4508 // DataChannel may callback to us and try to modify the list.
4509 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4510 temp_rtp_dcs.swap(rtp_data_channels_);
4511 for (const auto& kv : temp_rtp_dcs) {
4512 kv.second->OnTransportChannelDestroyed();
4513 }
4514
4515 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4516 temp_sctp_dcs.swap(sctp_data_channels_);
4517 for (const auto& channel : temp_sctp_dcs) {
4518 channel->OnTransportChannelDestroyed();
4519 }
4520}
4521
4522void PeerConnection::OnDataChannelOpenMessage(
4523 const std::string& label,
4524 const InternalDataChannelInit& config) {
4525 rtc::scoped_refptr<DataChannel> channel(
4526 InternalCreateDataChannel(label, &config));
4527 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004528 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004529 return;
4530 }
4531
deadbeefa601f5c2016-06-06 14:27:39 -07004532 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4533 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004534 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004535}
4536
Steve Anton4171afb2017-11-20 10:20:22 -08004537rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4538PeerConnection::GetAudioTransceiver() const {
4539 // This method only works with Plan B SDP, where there is a single
4540 // audio/video transceiver.
4541 RTC_DCHECK(!IsUnifiedPlan());
4542 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004543 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004544 return transceiver;
4545 }
4546 }
4547 RTC_NOTREACHED();
4548 return nullptr;
4549}
4550
4551rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4552PeerConnection::GetVideoTransceiver() const {
4553 // This method only works with Plan B SDP, where there is a single
4554 // audio/video transceiver.
4555 RTC_DCHECK(!IsUnifiedPlan());
4556 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004557 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004558 return transceiver;
4559 }
4560 }
4561 RTC_NOTREACHED();
4562 return nullptr;
4563}
4564
4565// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4566// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004567bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004568 switch (type) {
4569 case cricket::MEDIA_TYPE_AUDIO:
4570 return !GetAudioTransceiver()->internal()->senders().empty();
4571 case cricket::MEDIA_TYPE_VIDEO:
4572 return !GetVideoTransceiver()->internal()->senders().empty();
4573 case cricket::MEDIA_TYPE_DATA:
4574 return false;
4575 }
4576 RTC_NOTREACHED();
4577 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004578}
4579
Steve Anton4171afb2017-11-20 10:20:22 -08004580rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4581PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4582 for (auto transceiver : transceivers_) {
4583 for (auto sender : transceiver->internal()->senders()) {
4584 if (sender->track() == track) {
4585 return sender;
4586 }
4587 }
4588 }
4589 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004590}
4591
Steve Anton4171afb2017-11-20 10:20:22 -08004592rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4593PeerConnection::FindSenderById(const std::string& sender_id) const {
4594 for (auto transceiver : transceivers_) {
4595 for (auto sender : transceiver->internal()->senders()) {
4596 if (sender->id() == sender_id) {
4597 return sender;
4598 }
4599 }
4600 }
4601 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004602}
4603
Steve Anton4171afb2017-11-20 10:20:22 -08004604rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4605PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4606 for (auto transceiver : transceivers_) {
4607 for (auto receiver : transceiver->internal()->receivers()) {
4608 if (receiver->id() == receiver_id) {
4609 return receiver;
4610 }
4611 }
4612 }
4613 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004614}
4615
Steve Anton4171afb2017-11-20 10:20:22 -08004616std::vector<PeerConnection::RtpSenderInfo>*
4617PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4618 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4619 media_type == cricket::MEDIA_TYPE_VIDEO);
4620 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4621 ? &remote_audio_sender_infos_
4622 : &remote_video_sender_infos_;
4623}
4624
4625std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004626 cricket::MediaType media_type) {
4627 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4628 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004629 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4630 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004631}
4632
Steve Anton4171afb2017-11-20 10:20:22 -08004633const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4634 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004635 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004636 const std::string sender_id) const {
4637 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004638 if (sender_info.stream_id == stream_id &&
4639 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004640 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004641 }
4642 }
4643 return nullptr;
4644}
4645
4646DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4647 for (const auto& channel : sctp_data_channels_) {
4648 if (channel->id() == sid) {
4649 return channel;
4650 }
4651 }
4652 return nullptr;
4653}
4654
deadbeef91dd5672016-05-18 16:55:30 -07004655bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004656 const RTCConfiguration& configuration) {
4657 cricket::ServerAddresses stun_servers;
4658 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004659 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4660 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004661 return false;
4662 }
4663
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004664 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004665 // To handle both internal and externally created port allocator, we will
4666 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004667 port_allocator_flags_ = port_allocator_->flags();
4668 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4669 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4670 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004671 // If the disable-IPv6 flag was specified, we'll not override it
4672 // by experiment.
4673 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004674 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004675 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4676 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004677 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004678 }
4679
zhihuangb09b3f92017-03-07 14:40:51 -08004680 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004681 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004682 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004683 }
4684
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004685 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004686 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004687 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004688 }
4689
honghaiz60347052016-05-31 18:29:12 -07004690 if (configuration.candidate_network_policy ==
4691 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004692 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004693 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004694 }
4695
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004696 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004697 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004698 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4699 }
4700
Qingsi Wanga2d60672018-04-11 16:57:45 -07004701 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004702 // No step delay is used while allocating ports.
4703 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4704 port_allocator_->set_candidate_filter(
4705 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004706 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004707
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004708 if (tls_cert_verifier_ != nullptr) {
4709 for (auto& turn_server : turn_servers) {
4710 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4711 }
4712 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004713 // Call this last since it may create pooled allocator sessions using the
4714 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004715 port_allocator_->SetConfiguration(
4716 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4717 configuration.prune_turn_ports, configuration.turn_customizer,
4718 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004719 return true;
4720}
4721
deadbeef91dd5672016-05-18 16:55:30 -07004722bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004723 const cricket::ServerAddresses& stun_servers,
4724 const std::vector<cricket::RelayServerConfig>& turn_servers,
4725 IceTransportsType type,
4726 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004727 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004728 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004729 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004730 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004731 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004732 // According to JSEP, after setLocalDescription, changing the candidate pool
4733 // size is not allowed, and changing the set of ICE servers will not result
4734 // in new candidates being gathered.
4735 if (local_description()) {
4736 port_allocator_->FreezeCandidatePool();
4737 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004738 // Call this last since it may create pooled allocator sessions using the
4739 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004740 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004741 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004742 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004743}
4744
Steve Antonba818672017-11-06 10:21:57 -08004745cricket::ChannelManager* PeerConnection::channel_manager() const {
4746 return factory_->channel_manager();
4747}
4748
4749MetricsObserverInterface* PeerConnection::metrics_observer() const {
4750 return uma_observer_;
4751}
4752
Elad Alon99c3fe52017-10-13 16:29:40 +02004753bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004754 std::unique_ptr<RtcEventLogOutput> output,
4755 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004756 if (!event_log_) {
4757 return false;
4758 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004759 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004760}
4761
4762void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004763 if (event_log_) {
4764 event_log_->StopLogging();
4765 }
ivoc14d5dbe2016-07-04 07:06:55 -07004766}
nisseeaabdf62017-05-05 02:23:02 -07004767
Steve Anton75737c02017-11-06 10:37:17 -08004768cricket::BaseChannel* PeerConnection::GetChannel(
4769 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004770 for (auto transceiver : transceivers_) {
4771 cricket::BaseChannel* channel = transceiver->internal()->channel();
4772 if (channel && channel->content_name() == content_name) {
4773 return channel;
4774 }
Steve Anton75737c02017-11-06 10:37:17 -08004775 }
4776 if (rtp_data_channel() &&
4777 rtp_data_channel()->content_name() == content_name) {
4778 return rtp_data_channel();
4779 }
4780 return nullptr;
4781}
4782
4783bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4784 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004785 RTC_LOG(LS_INFO)
4786 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004787 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004788 return false;
4789 }
4790 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004791 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004792 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004793 return false;
4794 }
4795
Zhi Huange830e682018-03-30 10:48:35 -07004796 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4797 if (dtls_role) {
4798 *role = *dtls_role;
4799 return true;
4800 }
4801 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004802}
4803
4804bool PeerConnection::GetSslRole(const std::string& content_name,
4805 rtc::SSLRole* role) {
4806 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004807 RTC_LOG(LS_INFO)
4808 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004809 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004810 return false;
4811 }
4812
Zhi Huange830e682018-03-30 10:48:35 -07004813 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4814 if (dtls_role) {
4815 *role = *dtls_role;
4816 return true;
4817 }
4818 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004819}
4820
Steve Antonf8470812017-12-04 10:46:21 -08004821void PeerConnection::SetSessionError(SessionError error,
4822 const std::string& error_desc) {
4823 RTC_DCHECK_RUN_ON(signaling_thread());
4824 if (error != session_error_) {
4825 session_error_ = error;
4826 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004827 }
4828}
4829
Zhi Huange830e682018-03-30 10:48:35 -07004830RTCError PeerConnection::UpdateSessionState(
4831 SdpType type,
4832 cricket::ContentSource source,
4833 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004834 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004835
4836 // If there's already a pending error then no state transition should happen.
4837 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004838 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004839
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004840 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004841 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004842 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004843 }
4844
4845 // Update the signaling state according to the specified state machine (see
4846 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004847 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004848 ChangeSignalingState(source == cricket::CS_LOCAL
4849 ? PeerConnectionInterface::kHaveLocalOffer
4850 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004851 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004852 ChangeSignalingState(source == cricket::CS_LOCAL
4853 ? PeerConnectionInterface::kHaveLocalPrAnswer
4854 : PeerConnectionInterface::kHaveRemotePrAnswer);
4855 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004856 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004857 ChangeSignalingState(PeerConnectionInterface::kStable);
4858 }
4859
4860 // Update internal objects according to the session description's media
4861 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004862 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004863 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004864 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004865 }
4866
Steve Anton8a006912017-12-04 15:25:56 -08004867 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004868}
4869
Steve Anton8a006912017-12-04 15:25:56 -08004870RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004871 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004872 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004873 const SessionDescriptionInterface* sdesc =
4874 (source == cricket::CS_LOCAL ? local_description()
4875 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004876 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004877
4878 // Push down the new SDP media section for each audio/video transceiver.
4879 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004880 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004881 FindMediaSectionForTransceiver(transceiver, sdesc);
4882 cricket::BaseChannel* channel = transceiver->internal()->channel();
4883 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004884 continue;
4885 }
4886 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004887 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004888 if (!content_desc) {
4889 continue;
4890 }
4891 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004892 bool success = (source == cricket::CS_LOCAL)
4893 ? channel->SetLocalContent(content_desc, type, &error)
4894 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004895 if (!success) {
4896 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4897 }
4898 }
4899
4900 // If using the RtpDataChannel, push down the new SDP section for it too.
4901 if (rtp_data_channel_) {
4902 const ContentInfo* data_content =
4903 cricket::GetFirstDataContent(sdesc->description());
4904 if (data_content && !data_content->rejected) {
4905 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004906 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004907 if (data_desc) {
4908 std::string error;
4909 bool success =
4910 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004911 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004912 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004913 if (!success) {
4914 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4915 std::move(error));
4916 }
Steve Anton75737c02017-11-06 10:37:17 -08004917 }
4918 }
4919 }
Steve Antoned10bd92017-12-05 10:52:59 -08004920
Steve Anton75737c02017-11-06 10:37:17 -08004921 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4922 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4923 if (sctp_transport_ && local_description() && remote_description() &&
4924 cricket::GetFirstDataContent(local_description()->description()) &&
4925 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004926 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004927 RTC_FROM_HERE,
4928 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004929 if (!success) {
4930 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4931 "Failed to push down SCTP parameters.");
4932 }
Steve Anton75737c02017-11-06 10:37:17 -08004933 }
Steve Antoned10bd92017-12-05 10:52:59 -08004934
Steve Anton8a006912017-12-04 15:25:56 -08004935 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004936}
4937
4938bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4939 RTC_DCHECK(network_thread()->IsCurrent());
4940 RTC_DCHECK(local_description());
4941 RTC_DCHECK(remote_description());
4942 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4943 // When we support "max-message-size", that would also be pushed down here.
4944 return sctp_transport_->Start(
4945 GetSctpPort(local_description()->description()),
4946 GetSctpPort(remote_description()->description()));
4947}
4948
Steve Anton8a006912017-12-04 15:25:56 -08004949RTCError PeerConnection::PushdownTransportDescription(
4950 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004951 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004952 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004953
Zhi Huange830e682018-03-30 10:48:35 -07004954 if (source == cricket::CS_LOCAL) {
4955 const SessionDescriptionInterface* sdesc = local_description();
4956 RTC_DCHECK(sdesc);
4957 return transport_controller_->SetLocalDescription(type,
4958 sdesc->description());
4959 } else {
4960 const SessionDescriptionInterface* sdesc = remote_description();
4961 RTC_DCHECK(sdesc);
4962 return transport_controller_->SetRemoteDescription(type,
4963 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004964 }
Steve Anton75737c02017-11-06 10:37:17 -08004965}
4966
4967bool PeerConnection::GetTransportDescription(
4968 const SessionDescription* description,
4969 const std::string& content_name,
4970 cricket::TransportDescription* tdesc) {
4971 if (!description || !tdesc) {
4972 return false;
4973 }
4974 const TransportInfo* transport_info =
4975 description->GetTransportInfoByName(content_name);
4976 if (!transport_info) {
4977 return false;
4978 }
4979 *tdesc = transport_info->description;
4980 return true;
4981}
4982
Steve Anton75737c02017-11-06 10:37:17 -08004983cricket::IceConfig PeerConnection::ParseIceConfig(
4984 const PeerConnectionInterface::RTCConfiguration& config) const {
4985 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004986 switch (config.continual_gathering_policy) {
4987 case PeerConnectionInterface::GATHER_ONCE:
4988 gathering_policy = cricket::GATHER_ONCE;
4989 break;
4990 case PeerConnectionInterface::GATHER_CONTINUALLY:
4991 gathering_policy = cricket::GATHER_CONTINUALLY;
4992 break;
4993 default:
4994 RTC_NOTREACHED();
4995 gathering_policy = cricket::GATHER_ONCE;
4996 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004997
Steve Anton75737c02017-11-06 10:37:17 -08004998 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004999 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5000 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005001 ice_config.prioritize_most_likely_candidate_pairs =
5002 config.prioritize_most_likely_ice_candidate_pairs;
5003 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005004 RTCConfigurationToIceConfigOptionalInt(
5005 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005006 ice_config.continual_gathering_policy = gathering_policy;
5007 ice_config.presume_writable_when_fully_relayed =
5008 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005009 ice_config.ice_check_interval_strong_connectivity =
5010 config.ice_check_interval_strong_connectivity;
5011 ice_config.ice_check_interval_weak_connectivity =
5012 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005013 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005014 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005015 ice_config.regather_all_networks_interval_range =
5016 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005017 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005018 return ice_config;
5019}
5020
Steve Anton75737c02017-11-06 10:37:17 -08005021bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5022 std::string* track_id) {
5023 if (!local_description()) {
5024 return false;
5025 }
5026 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5027 track_id);
5028}
5029
5030bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5031 std::string* track_id) {
5032 if (!remote_description()) {
5033 return false;
5034 }
5035 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5036 track_id);
5037}
5038
5039bool PeerConnection::SendData(const cricket::SendDataParams& params,
5040 const rtc::CopyOnWriteBuffer& payload,
5041 cricket::SendDataResult* result) {
5042 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005043 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005044 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005045 return false;
5046 }
5047 return rtp_data_channel_
5048 ? rtp_data_channel_->SendData(params, payload, result)
5049 : network_thread()->Invoke<bool>(
5050 RTC_FROM_HERE,
5051 Bind(&cricket::SctpTransportInternal::SendData,
5052 sctp_transport_.get(), params, payload, result));
5053}
5054
5055bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5056 if (!rtp_data_channel_ && !sctp_transport_) {
5057 // Don't log an error here, because DataChannels are expected to call
5058 // ConnectDataChannel in this state. It's the only way to initially tell
5059 // whether or not the underlying transport is ready.
5060 return false;
5061 }
5062 if (rtp_data_channel_) {
5063 rtp_data_channel_->SignalReadyToSendData.connect(
5064 webrtc_data_channel, &DataChannel::OnChannelReady);
5065 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5066 &DataChannel::OnDataReceived);
5067 } else {
5068 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5069 &DataChannel::OnChannelReady);
5070 SignalSctpDataReceived.connect(webrtc_data_channel,
5071 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005072 SignalSctpClosingProcedureStartedRemotely.connect(
5073 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5074 SignalSctpClosingProcedureComplete.connect(
5075 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005076 }
5077 return true;
5078}
5079
5080void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5081 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005082 RTC_LOG(LS_ERROR)
5083 << "DisconnectDataChannel called when rtp_data_channel_ and "
5084 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005085 return;
5086 }
5087 if (rtp_data_channel_) {
5088 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5089 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5090 } else {
5091 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5092 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005093 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5094 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005095 }
5096}
5097
5098void PeerConnection::AddSctpDataStream(int sid) {
5099 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005100 RTC_LOG(LS_ERROR)
5101 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005102 return;
5103 }
5104 network_thread()->Invoke<void>(
5105 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5106 sctp_transport_.get(), sid));
5107}
5108
5109void PeerConnection::RemoveSctpDataStream(int sid) {
5110 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005111 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005112 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005113 return;
5114 }
5115 network_thread()->Invoke<void>(
5116 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5117 sctp_transport_.get(), sid));
5118}
5119
5120bool PeerConnection::ReadyToSendData() const {
5121 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5122 sctp_ready_to_send_data_;
5123}
5124
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005125absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005126 if (sctp_mid_ && transport_controller_) {
5127 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5128 if (dtls_transport) {
5129 return dtls_transport->transport_name();
5130 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005131 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005132 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005133 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005134}
5135
Qingsi Wang72a43a12018-02-20 16:03:18 -08005136cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5137 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005138 network_thread()->Invoke<void>(
5139 RTC_FROM_HERE,
5140 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5141 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005142 return candidate_states_list;
5143}
5144
Steve Anton5dfde182018-02-06 10:34:40 -08005145std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5146 const {
5147 std::map<std::string, std::string> transport_names_by_mid;
5148 for (auto transceiver : transceivers_) {
5149 cricket::BaseChannel* channel = transceiver->internal()->channel();
5150 if (channel) {
5151 transport_names_by_mid[channel->content_name()] =
5152 channel->transport_name();
5153 }
Steve Anton75737c02017-11-06 10:37:17 -08005154 }
Steve Anton5dfde182018-02-06 10:34:40 -08005155 if (rtp_data_channel_) {
5156 transport_names_by_mid[rtp_data_channel_->content_name()] =
5157 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005158 }
5159 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005160 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005161 RTC_DCHECK(transport_name);
5162 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005163 }
Steve Anton5dfde182018-02-06 10:34:40 -08005164 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005165}
5166
Steve Anton5dfde182018-02-06 10:34:40 -08005167std::map<std::string, cricket::TransportStats>
5168PeerConnection::GetTransportStatsByNames(
5169 const std::set<std::string>& transport_names) {
5170 if (!network_thread()->IsCurrent()) {
5171 return network_thread()
5172 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5173 RTC_FROM_HERE,
5174 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005175 }
Steve Anton5dfde182018-02-06 10:34:40 -08005176 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5177 for (const std::string& transport_name : transport_names) {
5178 cricket::TransportStats transport_stats;
5179 bool success =
5180 transport_controller_->GetStats(transport_name, &transport_stats);
5181 if (success) {
5182 transport_stats_by_name[transport_name] = std::move(transport_stats);
5183 } else {
5184 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5185 << transport_name;
5186 }
5187 }
5188 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005189}
5190
5191bool PeerConnection::GetLocalCertificate(
5192 const std::string& transport_name,
5193 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005194 if (!certificate) {
5195 return false;
5196 }
5197 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5198 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005199}
5200
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005201std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005202 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005203 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005204}
5205
5206cricket::DataChannelType PeerConnection::data_channel_type() const {
5207 return data_channel_type_;
5208}
5209
5210bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5211 return pending_ice_restarts_.find(content_name) !=
5212 pending_ice_restarts_.end();
5213}
5214
Steve Anton75737c02017-11-06 10:37:17 -08005215bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5216 return transport_controller_->NeedsIceRestart(content_name);
5217}
5218
5219void PeerConnection::OnCertificateReady(
5220 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5221 transport_controller_->SetLocalCertificate(certificate);
5222}
5223
5224void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005225 SetSessionError(SessionError::kTransport,
5226 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005227}
5228
5229void PeerConnection::OnTransportControllerConnectionState(
5230 cricket::IceConnectionState state) {
5231 switch (state) {
5232 case cricket::kIceConnectionConnecting:
5233 // If the current state is Connected or Completed, then there were
5234 // writable channels but now there are not, so the next state must
5235 // be Disconnected.
5236 // kIceConnectionConnecting is currently used as the default,
5237 // un-connected state by the TransportController, so its only use is
5238 // detecting disconnections.
5239 if (ice_connection_state_ ==
5240 PeerConnectionInterface::kIceConnectionConnected ||
5241 ice_connection_state_ ==
5242 PeerConnectionInterface::kIceConnectionCompleted) {
5243 SetIceConnectionState(
5244 PeerConnectionInterface::kIceConnectionDisconnected);
5245 }
5246 break;
5247 case cricket::kIceConnectionFailed:
5248 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5249 break;
5250 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005251 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005252 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005253 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005254 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005255 break;
5256 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005257 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005258 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005259 if (ice_connection_state_ !=
5260 PeerConnectionInterface::kIceConnectionConnected) {
5261 // If jumping directly from "checking" to "connected",
5262 // signal "connected" first.
5263 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5264 }
5265 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005266 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005267 if (metrics_observer()) {
5268 ReportTransportStats();
5269 }
5270 break;
5271 default:
5272 RTC_NOTREACHED();
5273 }
5274}
5275
5276void PeerConnection::OnTransportControllerCandidatesGathered(
5277 const std::string& transport_name,
5278 const cricket::Candidates& candidates) {
5279 RTC_DCHECK(signaling_thread()->IsCurrent());
5280 int sdp_mline_index;
5281 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005282 RTC_LOG(LS_ERROR)
5283 << "OnTransportControllerCandidatesGathered: content name "
5284 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005285 return;
5286 }
5287
5288 for (cricket::Candidates::const_iterator citer = candidates.begin();
5289 citer != candidates.end(); ++citer) {
5290 // Use transport_name as the candidate media id.
5291 std::unique_ptr<JsepIceCandidate> candidate(
5292 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5293 if (local_description()) {
5294 mutable_local_description()->AddCandidate(candidate.get());
5295 }
5296 OnIceCandidate(std::move(candidate));
5297 }
5298}
5299
5300void PeerConnection::OnTransportControllerCandidatesRemoved(
5301 const std::vector<cricket::Candidate>& candidates) {
5302 RTC_DCHECK(signaling_thread()->IsCurrent());
5303 // Sanity check.
5304 for (const cricket::Candidate& candidate : candidates) {
5305 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005306 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005307 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005308 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005309 return;
5310 }
5311 }
5312
5313 if (local_description()) {
5314 mutable_local_description()->RemoveCandidates(candidates);
5315 }
5316 OnIceCandidatesRemoved(candidates);
5317}
5318
5319void PeerConnection::OnTransportControllerDtlsHandshakeError(
5320 rtc::SSLHandshakeError error) {
5321 if (metrics_observer()) {
5322 metrics_observer()->IncrementEnumCounter(
5323 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5324 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5325 }
5326}
5327
Steve Antoned10bd92017-12-05 10:52:59 -08005328void PeerConnection::EnableSending() {
5329 for (auto transceiver : transceivers_) {
5330 cricket::BaseChannel* channel = transceiver->internal()->channel();
5331 if (channel && !channel->enabled()) {
5332 channel->Enable(true);
5333 }
Steve Anton75737c02017-11-06 10:37:17 -08005334 }
5335
Steve Anton4171afb2017-11-20 10:20:22 -08005336 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005337 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005338 }
Steve Anton75737c02017-11-06 10:37:17 -08005339}
5340
5341// Returns the media index for a local ice candidate given the content name.
5342bool PeerConnection::GetLocalCandidateMediaIndex(
5343 const std::string& content_name,
5344 int* sdp_mline_index) {
5345 if (!local_description() || !sdp_mline_index) {
5346 return false;
5347 }
5348
5349 bool content_found = false;
5350 const ContentInfos& contents = local_description()->description()->contents();
5351 for (size_t index = 0; index < contents.size(); ++index) {
5352 if (contents[index].name == content_name) {
5353 *sdp_mline_index = static_cast<int>(index);
5354 content_found = true;
5355 break;
5356 }
5357 }
5358 return content_found;
5359}
5360
5361bool PeerConnection::UseCandidatesInSessionDescription(
5362 const SessionDescriptionInterface* remote_desc) {
5363 if (!remote_desc) {
5364 return true;
5365 }
5366 bool ret = true;
5367
5368 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5369 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5370 for (size_t n = 0; n < candidates->count(); ++n) {
5371 const IceCandidateInterface* candidate = candidates->at(n);
5372 bool valid = false;
5373 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5374 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005375 RTC_LOG(LS_INFO)
5376 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005377 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005378 }
5379 continue;
5380 }
5381 ret = UseCandidate(candidate);
5382 if (!ret) {
5383 break;
5384 }
5385 }
5386 }
5387 return ret;
5388}
5389
5390bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5391 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5392 size_t remote_content_size =
5393 remote_description()->description()->contents().size();
5394 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005395 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005396 return false;
5397 }
5398
5399 cricket::ContentInfo content =
5400 remote_description()->description()->contents()[mediacontent_index];
5401 std::vector<cricket::Candidate> candidates;
5402 candidates.push_back(candidate->candidate());
5403 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005404 RTCError error =
5405 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005406 if (error.ok()) {
5407 // Candidates successfully submitted for checking.
5408 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5409 ice_connection_state_ ==
5410 PeerConnectionInterface::kIceConnectionDisconnected) {
5411 // If state is New, then the session has just gotten its first remote ICE
5412 // candidates, so go to Checking.
5413 // If state is Disconnected, the session is re-using old candidates or
5414 // receiving additional ones, so go to Checking.
5415 // If state is Connected, stay Connected.
5416 // TODO(bemasc): If state is Connected, and the new candidates are for a
5417 // newly added transport, then the state actually _should_ move to
5418 // checking. Add a way to distinguish that case.
5419 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5420 }
5421 // TODO(bemasc): If state is Completed, go back to Connected.
5422 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005423 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005424 }
5425 return true;
5426}
5427
5428void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005429 // Destroy video channel first since it may have a pointer to the
5430 // voice channel.
5431 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005432 if (!video_info || video_info->rejected) {
5433 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005434 }
5435
Steve Anton6fec8802017-12-04 10:37:29 -08005436 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5437 if (!audio_info || audio_info->rejected) {
5438 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005439 }
5440
5441 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5442 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005443 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005444 }
5445}
5446
Steve Antondcc3c022017-12-22 16:02:54 -08005447RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5448 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005449 const cricket::ContentGroup* bundle_group = nullptr;
5450 if (configuration_.bundle_policy ==
5451 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005452 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005453 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5455 "max-bundle configured but session description "
5456 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005457 }
5458 }
Steve Antondcc3c022017-12-22 16:02:54 -08005459 return std::move(bundle_group);
5460}
5461
5462RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005463 // Creating the media channels. Transports should already have been created
5464 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005465 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005466 if (voice && !voice->rejected &&
5467 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005468 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005469 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005470 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5471 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005472 }
5473 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5474 }
5475
Steve Antondcc3c022017-12-22 16:02:54 -08005476 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005477 if (video && !video->rejected &&
5478 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005479 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005480 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005481 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5482 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005483 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005484 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005485 }
5486
Steve Antondcc3c022017-12-22 16:02:54 -08005487 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005488 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5489 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005490 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005491 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5492 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005493 }
5494 }
5495
Steve Anton8a006912017-12-04 15:25:56 -08005496 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005497}
5498
Steve Anton4171afb2017-11-20 10:20:22 -08005499// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005500cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005501 const std::string& mid) {
5502 RtpTransportInternal* rtp_transport =
5503 transport_controller_->GetRtpTransport(mid);
5504 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005505 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005506 call_.get(), configuration_.media_config, rtp_transport,
5507 signaling_thread(), mid, SrtpRequired(),
5508 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005509 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005510 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005511 }
Steve Anton75737c02017-11-06 10:37:17 -08005512 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5513 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005514 voice_channel->SignalSentPacket.connect(this,
5515 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005516 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005517 if (uma_observer_) {
5518 voice_channel->SetMetricsObserver(uma_observer_);
5519 }
Steve Anton4171afb2017-11-20 10:20:22 -08005520
Steve Antoneda6ccd2017-12-04 10:21:55 -08005521 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005522}
5523
Steve Anton4171afb2017-11-20 10:20:22 -08005524// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005525cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005526 const std::string& mid) {
5527 RtpTransportInternal* rtp_transport =
5528 transport_controller_->GetRtpTransport(mid);
5529 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005530 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005531 call_.get(), configuration_.media_config, rtp_transport,
5532 signaling_thread(), mid, SrtpRequired(),
5533 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005534 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005535 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005536 }
Steve Anton75737c02017-11-06 10:37:17 -08005537 video_channel->SignalDtlsSrtpSetupFailure.connect(
5538 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005539 video_channel->SignalSentPacket.connect(this,
5540 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005541 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005542 if (uma_observer_) {
5543 video_channel->SetMetricsObserver(uma_observer_);
5544 }
Steve Anton4171afb2017-11-20 10:20:22 -08005545
Steve Antoneda6ccd2017-12-04 10:21:55 -08005546 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005547}
5548
Zhi Huange830e682018-03-30 10:48:35 -07005549bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005550 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5551 if (sctp) {
5552 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005553 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005554 << "Trying to create SCTP transport, but didn't compile with "
5555 "SCTP support (HAVE_SCTP)";
5556 return false;
5557 }
5558 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005559 RTC_FROM_HERE,
5560 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005561 return false;
5562 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005563 for (const auto& channel : sctp_data_channels_) {
5564 channel->OnTransportChannelCreated();
5565 }
Steve Anton75737c02017-11-06 10:37:17 -08005566 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005567 RtpTransportInternal* rtp_transport =
5568 transport_controller_->GetRtpTransport(mid);
5569 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005570 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005571 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5572 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005573 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005574 return false;
5575 }
Steve Anton75737c02017-11-06 10:37:17 -08005576 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5577 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5578 rtp_data_channel_->SignalSentPacket.connect(
5579 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005580 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005581 if (uma_observer_) {
5582 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5583 }
Steve Anton75737c02017-11-06 10:37:17 -08005584 }
5585
Steve Anton75737c02017-11-06 10:37:17 -08005586 return true;
5587}
5588
5589Call::Stats PeerConnection::GetCallStats() {
5590 if (!worker_thread()->IsCurrent()) {
5591 return worker_thread()->Invoke<Call::Stats>(
5592 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5593 }
5594 if (call_) {
5595 return call_->GetStats();
5596 } else {
5597 return Call::Stats();
5598 }
5599}
5600
Zhi Huange830e682018-03-30 10:48:35 -07005601bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005602 RTC_DCHECK(network_thread()->IsCurrent());
5603 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005604 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005605 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005606 RTC_DCHECK(dtls_transport);
5607 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005608 RTC_DCHECK(sctp_transport_);
5609 sctp_invoker_.reset(new rtc::AsyncInvoker());
5610 sctp_transport_->SignalReadyToSendData.connect(
5611 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5612 sctp_transport_->SignalDataReceived.connect(
5613 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005614 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5615 // another thread. Would be nice if there was a helper class similar to
5616 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5617 // code.
5618 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5619 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5620 sctp_transport_->SignalClosingProcedureComplete.connect(
5621 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005622 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005623 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005624 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005625}
5626
5627void PeerConnection::DestroySctpTransport_n() {
5628 RTC_DCHECK(network_thread()->IsCurrent());
5629 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005630 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005631 sctp_invoker_.reset(nullptr);
5632 sctp_ready_to_send_data_ = false;
5633}
5634
5635void PeerConnection::OnSctpTransportReadyToSendData_n() {
5636 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5637 RTC_DCHECK(network_thread()->IsCurrent());
5638 // Note: Cannot use rtc::Bind here because it will grab a reference to
5639 // PeerConnection and potentially cause PeerConnection to live longer than
5640 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5641 // be destroyed before PeerConnection is destroyed, and at that point all
5642 // pending tasks will be cleared.
5643 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5644 OnSctpTransportReadyToSendData_s(true);
5645 });
5646}
5647
5648void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5649 RTC_DCHECK(signaling_thread()->IsCurrent());
5650 sctp_ready_to_send_data_ = ready;
5651 SignalSctpReadyToSendData(ready);
5652}
5653
5654void PeerConnection::OnSctpTransportDataReceived_n(
5655 const cricket::ReceiveDataParams& params,
5656 const rtc::CopyOnWriteBuffer& payload) {
5657 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5658 RTC_DCHECK(network_thread()->IsCurrent());
5659 // Note: Cannot use rtc::Bind here because it will grab a reference to
5660 // PeerConnection and potentially cause PeerConnection to live longer than
5661 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5662 // be destroyed before PeerConnection is destroyed, and at that point all
5663 // pending tasks will be cleared.
5664 sctp_invoker_->AsyncInvoke<void>(
5665 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5666 OnSctpTransportDataReceived_s(params, payload);
5667 });
5668}
5669
5670void PeerConnection::OnSctpTransportDataReceived_s(
5671 const cricket::ReceiveDataParams& params,
5672 const rtc::CopyOnWriteBuffer& payload) {
5673 RTC_DCHECK(signaling_thread()->IsCurrent());
5674 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5675 // Received OPEN message; parse and signal that a new data channel should
5676 // be created.
5677 std::string label;
5678 InternalDataChannelInit config;
5679 config.id = params.ssrc;
5680 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005681 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5682 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005683 return;
5684 }
5685 config.open_handshake_role = InternalDataChannelInit::kAcker;
5686 OnDataChannelOpenMessage(label, config);
5687 } else {
5688 // Otherwise just forward the signal.
5689 SignalSctpDataReceived(params, payload);
5690 }
5691}
5692
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005693void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005694 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5695 RTC_DCHECK(network_thread()->IsCurrent());
5696 sctp_invoker_->AsyncInvoke<void>(
5697 RTC_FROM_HERE, signaling_thread(),
5698 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005699 &SignalSctpClosingProcedureStartedRemotely, sid));
5700}
5701
5702void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5703 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5704 RTC_DCHECK(network_thread()->IsCurrent());
5705 sctp_invoker_->AsyncInvoke<void>(
5706 RTC_FROM_HERE, signaling_thread(),
5707 rtc::Bind(&sigslot::signal1<int>::operator(),
5708 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005709}
5710
5711// Returns false if bundle is enabled and rtcp_mux is disabled.
5712bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5713 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5714 if (!bundle_enabled)
5715 return true;
5716
5717 const cricket::ContentGroup* bundle_group =
5718 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5719 RTC_DCHECK(bundle_group != NULL);
5720
5721 const cricket::ContentInfos& contents = desc->contents();
5722 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5723 citer != contents.end(); ++citer) {
5724 const cricket::ContentInfo* content = (&*citer);
5725 RTC_DCHECK(content != NULL);
5726 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005727 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005728 if (!HasRtcpMuxEnabled(content))
5729 return false;
5730 }
5731 }
5732 // RTCP-MUX is enabled in all the contents.
5733 return true;
5734}
5735
5736bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005737 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005738}
5739
Steve Anton8a006912017-12-04 15:25:56 -08005740RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005741 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005742 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005743 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005744 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005745 }
5746
5747 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005748 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005749 }
5750
Steve Anton3828c062017-12-06 10:34:51 -08005751 SdpType type = sdesc->GetType();
5752 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5753 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005754 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005755 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005756 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005757 }
5758
5759 // Verify crypto settings.
5760 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005761 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5762 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005763 RTCError crypto_error =
5764 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005765 if (!crypto_error.ok()) {
5766 return crypto_error;
5767 }
Steve Anton75737c02017-11-06 10:37:17 -08005768 }
5769
5770 // Verify ice-ufrag and ice-pwd.
5771 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005772 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5773 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005774 }
5775
5776 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005777 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5778 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005779 }
5780
5781 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5782 // m-lines that do not rtcp-mux enabled.
5783
5784 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005785 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005786 // With an answer we want to compare the new answer session description with
5787 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005788 const cricket::SessionDescription* offer_desc =
5789 (source == cricket::CS_LOCAL) ? remote_description()->description()
5790 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005791 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5792 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5793 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005794 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5795 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005796 }
5797 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005798 // The re-offers should respect the order of m= sections in current
5799 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005800 // With a re-offer, either the current local or current remote descriptions
5801 // could be the most up to date, so we would like to check against both of
5802 // them if they exist. It could be the case that one of them has a 0 port
5803 // for a media section, but the other does not. This is important to check
5804 // against in the case that we are recycling an m= section.
5805 const cricket::SessionDescription* current_desc = nullptr;
5806 const cricket::SessionDescription* secondary_current_desc = nullptr;
5807 if (local_description()) {
5808 current_desc = local_description()->description();
5809 if (remote_description()) {
5810 secondary_current_desc = remote_description()->description();
5811 }
5812 } else if (remote_description()) {
5813 current_desc = remote_description()->description();
5814 }
Steve Anton75737c02017-11-06 10:37:17 -08005815 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005816 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5817 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005818 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5819 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005820 }
5821 }
5822
Steve Antonba42e992018-04-09 14:10:01 -07005823 if (IsUnifiedPlan()) {
5824 // Ensure that each audio and video media section has at most one
5825 // "StreamParams". This will return an error if receiving a session
5826 // description from a "Plan B" endpoint which adds multiple tracks of the
5827 // same type. With Unified Plan, there can only be at most one track per
5828 // media section.
5829 for (const ContentInfo& content : sdesc->description()->contents()) {
5830 const MediaContentDescription& desc = *content.description;
5831 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5832 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5833 desc.streams().size() > 1u) {
5834 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5835 "Media section has more than one track specified "
5836 "with a=ssrc lines which is not supported with "
5837 "Unified Plan.");
5838 }
5839 }
5840 }
5841
Steve Anton8a006912017-12-04 15:25:56 -08005842 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005843}
5844
Steve Anton3828c062017-12-06 10:34:51 -08005845bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005846 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005847 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005848 return (state == PeerConnectionInterface::kStable) ||
5849 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005850 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005851 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005852 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5853 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5854 }
5855}
5856
Steve Anton3828c062017-12-06 10:34:51 -08005857bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005858 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005859 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005860 return (state == PeerConnectionInterface::kStable) ||
5861 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005862 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005863 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005864 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5865 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5866 }
5867}
5868
Steve Antonf8470812017-12-04 10:46:21 -08005869const char* PeerConnection::SessionErrorToString(SessionError error) const {
5870 switch (error) {
5871 case SessionError::kNone:
5872 return "ERROR_NONE";
5873 case SessionError::kContent:
5874 return "ERROR_CONTENT";
5875 case SessionError::kTransport:
5876 return "ERROR_TRANSPORT";
5877 }
5878 RTC_NOTREACHED();
5879 return "";
5880}
5881
Steve Anton75737c02017-11-06 10:37:17 -08005882std::string PeerConnection::GetSessionErrorMsg() {
5883 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005884 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5885 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005886 return desc.str();
5887}
5888
Steve Anton8e20f172018-03-06 10:55:04 -08005889void PeerConnection::ReportSdpFormatReceived(
5890 const SessionDescriptionInterface& remote_offer) {
5891 if (!uma_observer_) {
5892 return;
5893 }
5894 int num_audio_mlines = 0;
5895 int num_video_mlines = 0;
5896 int num_audio_tracks = 0;
5897 int num_video_tracks = 0;
5898 for (const ContentInfo& content : remote_offer.description()->contents()) {
5899 cricket::MediaType media_type = content.media_description()->type();
5900 int num_tracks = std::max(
5901 1, static_cast<int>(content.media_description()->streams().size()));
5902 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5903 num_audio_mlines += 1;
5904 num_audio_tracks += num_tracks;
5905 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5906 num_video_mlines += 1;
5907 num_video_tracks += num_tracks;
5908 }
5909 }
5910 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5911 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5912 format = kSdpFormatReceivedComplexUnifiedPlan;
5913 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5914 format = kSdpFormatReceivedComplexPlanB;
5915 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5916 format = kSdpFormatReceivedSimple;
5917 }
5918 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5919 kSdpFormatReceivedMax);
5920}
5921
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005922void PeerConnection::NoteUsageEvent(UsageEvent event) {
5923 RTC_DCHECK_RUN_ON(signaling_thread());
5924 usage_event_accumulator_ |= static_cast<int>(event);
5925}
5926
5927void PeerConnection::ReportUsagePattern() const {
5928 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5929 if (uma_observer_) {
5930 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5931 usage_event_accumulator_);
5932 }
5933}
5934
Steve Anton0ffaaa22018-02-23 10:31:30 -08005935void PeerConnection::ReportNegotiatedSdpSemantics(
5936 const SessionDescriptionInterface& answer) {
5937 if (!uma_observer_) {
5938 return;
5939 }
5940 switch (answer.description()->msid_signaling()) {
5941 case 0:
5942 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5943 kSdpSemanticNegotiatedNone,
5944 kSdpSemanticNegotiatedMax);
5945 break;
5946 case cricket::kMsidSignalingMediaSection:
5947 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5948 kSdpSemanticNegotiatedUnifiedPlan,
5949 kSdpSemanticNegotiatedMax);
5950 break;
5951 case cricket::kMsidSignalingSsrcAttribute:
5952 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5953 kSdpSemanticNegotiatedPlanB,
5954 kSdpSemanticNegotiatedMax);
5955 break;
5956 case cricket::kMsidSignalingMediaSection |
5957 cricket::kMsidSignalingSsrcAttribute:
5958 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5959 kSdpSemanticNegotiatedMixed,
5960 kSdpSemanticNegotiatedMax);
5961 break;
5962 default:
5963 RTC_NOTREACHED();
5964 }
5965}
5966
Steve Anton75737c02017-11-06 10:37:17 -08005967// We need to check the local/remote description for the Transport instead of
5968// the session, because a new Transport added during renegotiation may have
5969// them unset while the session has them set from the previous negotiation.
5970// Not doing so may trigger the auto generation of transport description and
5971// mess up DTLS identity information, ICE credential, etc.
5972bool PeerConnection::ReadyToUseRemoteCandidate(
5973 const IceCandidateInterface* candidate,
5974 const SessionDescriptionInterface* remote_desc,
5975 bool* valid) {
5976 *valid = true;
5977
5978 const SessionDescriptionInterface* current_remote_desc =
5979 remote_desc ? remote_desc : remote_description();
5980
5981 if (!current_remote_desc) {
5982 return false;
5983 }
5984
5985 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5986 size_t remote_content_size =
5987 current_remote_desc->description()->contents().size();
5988 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005989 RTC_LOG(LS_ERROR)
5990 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5991 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005992
5993 *valid = false;
5994 return false;
5995 }
5996
5997 cricket::ContentInfo content =
5998 current_remote_desc->description()->contents()[mediacontent_index];
5999
6000 const std::string transport_name = GetTransportName(content.name);
6001 if (transport_name.empty()) {
6002 return false;
6003 }
Zhi Huange830e682018-03-30 10:48:35 -07006004 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006005}
6006
6007bool PeerConnection::SrtpRequired() const {
6008 return dtls_enabled_ ||
6009 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6010}
6011
6012void PeerConnection::OnTransportControllerGatheringState(
6013 cricket::IceGatheringState state) {
6014 RTC_DCHECK(signaling_thread()->IsCurrent());
6015 if (state == cricket::kIceGatheringGathering) {
6016 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6017 } else if (state == cricket::kIceGatheringComplete) {
6018 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6019 }
6020}
6021
6022void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006023 std::map<std::string, std::set<cricket::MediaType>>
6024 media_types_by_transport_name;
6025 for (auto transceiver : transceivers_) {
6026 if (transceiver->internal()->channel()) {
6027 const std::string& transport_name =
6028 transceiver->internal()->channel()->transport_name();
6029 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006030 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006031 }
Steve Anton75737c02017-11-06 10:37:17 -08006032 }
6033 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006034 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6035 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006036 }
Zhi Huange830e682018-03-30 10:48:35 -07006037
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006038 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006039 if (transport_name) {
6040 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006041 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006042 }
Zhi Huange830e682018-03-30 10:48:35 -07006043
Steve Antonc7b964c2018-02-01 14:39:45 -08006044 for (const auto& entry : media_types_by_transport_name) {
6045 const std::string& transport_name = entry.first;
6046 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006047 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006048 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006049 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006050 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006051 }
6052 }
6053}
6054// Walk through the ConnectionInfos to gather best connection usage
6055// for IPv4 and IPv6.
6056void PeerConnection::ReportBestConnectionState(
6057 const cricket::TransportStats& stats) {
6058 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006059 for (const cricket::TransportChannelStats& channel_stats :
6060 stats.channel_stats) {
6061 for (const cricket::ConnectionInfo& connection_info :
6062 channel_stats.connection_infos) {
6063 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006064 continue;
6065 }
6066
6067 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006068 const cricket::Candidate& local = connection_info.local_candidate;
6069 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006070
6071 // Increment the counter for IceCandidatePairType.
6072 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6073 (local.type() == RELAY_PORT_TYPE &&
6074 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6075 type = kEnumCounterIceCandidatePairTypeTcp;
6076 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6077 type = kEnumCounterIceCandidatePairTypeUdp;
6078 } else {
6079 RTC_CHECK(0);
6080 }
6081 metrics_observer()->IncrementEnumCounter(
6082 type, GetIceCandidatePairCounter(local, remote),
6083 kIceCandidatePairMax);
6084
6085 // Increment the counter for IP type.
6086 if (local.address().family() == AF_INET) {
6087 metrics_observer()->IncrementEnumCounter(
6088 kEnumCounterAddressFamily, kBestConnections_IPv4,
6089 kPeerConnectionAddressFamilyCounter_Max);
6090
6091 } else if (local.address().family() == AF_INET6) {
6092 metrics_observer()->IncrementEnumCounter(
6093 kEnumCounterAddressFamily, kBestConnections_IPv6,
6094 kPeerConnectionAddressFamilyCounter_Max);
6095 } else {
6096 RTC_CHECK(0);
6097 }
6098
6099 return;
6100 }
6101 }
6102}
6103
6104void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006105 const cricket::TransportStats& stats,
6106 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006107 RTC_DCHECK(metrics_observer());
6108 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6109 return;
6110 }
6111
6112 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6113 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6114 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6115 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6116 return;
6117 }
6118
Steve Antonc7b964c2018-02-01 14:39:45 -08006119 for (cricket::MediaType media_type : media_types) {
6120 PeerConnectionEnumCounterType srtp_counter_type;
6121 PeerConnectionEnumCounterType ssl_counter_type;
6122 switch (media_type) {
6123 case cricket::MEDIA_TYPE_AUDIO:
6124 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6125 ssl_counter_type = kEnumCounterAudioSslCipher;
6126 break;
6127 case cricket::MEDIA_TYPE_VIDEO:
6128 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6129 ssl_counter_type = kEnumCounterVideoSslCipher;
6130 break;
6131 case cricket::MEDIA_TYPE_DATA:
6132 srtp_counter_type = kEnumCounterDataSrtpCipher;
6133 ssl_counter_type = kEnumCounterDataSslCipher;
6134 break;
6135 default:
6136 RTC_NOTREACHED();
6137 continue;
6138 }
6139 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6140 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6141 srtp_crypto_suite);
6142 }
6143 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6144 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6145 ssl_cipher_suite);
6146 }
Steve Anton75737c02017-11-06 10:37:17 -08006147 }
6148}
6149
6150void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6151 RTC_DCHECK(worker_thread()->IsCurrent());
6152 RTC_DCHECK(call_);
6153 call_->OnSentPacket(sent_packet);
6154}
6155
6156const std::string PeerConnection::GetTransportName(
6157 const std::string& content_name) {
6158 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006159 if (channel) {
6160 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006161 }
Steve Anton6fec8802017-12-04 10:37:29 -08006162 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006163 RTC_DCHECK(sctp_mid_);
6164 if (content_name == *sctp_mid_) {
6165 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006166 }
6167 }
6168 // Return an empty string if failed to retrieve the transport name.
6169 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006170}
6171
Steve Anton6fec8802017-12-04 10:37:29 -08006172void PeerConnection::DestroyTransceiverChannel(
6173 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6174 transceiver) {
6175 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006176
Steve Anton6fec8802017-12-04 10:37:29 -08006177 cricket::BaseChannel* channel = transceiver->internal()->channel();
6178 if (channel) {
6179 transceiver->internal()->SetChannel(nullptr);
6180 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006181 }
6182}
6183
6184void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006185 if (rtp_data_channel_) {
6186 OnDataChannelDestroyed();
6187 DestroyBaseChannel(rtp_data_channel_);
6188 rtp_data_channel_ = nullptr;
6189 }
6190
6191 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6192 // grab a reference to this PeerConnection. If this is called from the
6193 // PeerConnection destructor, the RefCountedObject vtable will have already
6194 // been destroyed (since it is a subclass of PeerConnection) and using
6195 // rtc::Bind will cause "Pure virtual function called" error to appear.
6196
6197 if (sctp_transport_) {
6198 OnDataChannelDestroyed();
6199 network_thread()->Invoke<void>(RTC_FROM_HERE,
6200 [this] { DestroySctpTransport_n(); });
6201 }
6202}
6203
6204void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6205 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006206 switch (channel->media_type()) {
6207 case cricket::MEDIA_TYPE_AUDIO:
6208 channel_manager()->DestroyVoiceChannel(
6209 static_cast<cricket::VoiceChannel*>(channel));
6210 break;
6211 case cricket::MEDIA_TYPE_VIDEO:
6212 channel_manager()->DestroyVideoChannel(
6213 static_cast<cricket::VideoChannel*>(channel));
6214 break;
6215 case cricket::MEDIA_TYPE_DATA:
6216 channel_manager()->DestroyRtpDataChannel(
6217 static_cast<cricket::RtpDataChannel*>(channel));
6218 break;
6219 default:
6220 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6221 break;
6222 }
Zhi Huange830e682018-03-30 10:48:35 -07006223}
Steve Anton6fec8802017-12-04 10:37:29 -08006224
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006225bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006226 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006227 RtpTransportInternal* rtp_transport,
6228 cricket::DtlsTransportInternal* dtls_transport) {
6229 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006230 auto base_channel = GetChannel(mid);
6231 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006232 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006233 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006234 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006235 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006236 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006237 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006238}
6239
Harald Alvestrand89061872018-01-02 14:08:34 +01006240void PeerConnection::ClearStatsCache() {
6241 if (stats_collector_) {
6242 stats_collector_->ClearCachedStatsReport();
6243 }
6244}
6245
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006246} // namespace webrtc