blob: f4dcb51fd43cf58004df54e36a1370b3ef1425b4 [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);
Seth Hampson5b4f0752018-04-02 16:31:36 -07001207 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001208 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001209 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001210 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001211 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001212 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001213 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001214 if (sender_info) {
1215 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001216 }
Steve Antonf9381f02017-12-14 10:23:57 -08001217 } else {
1218 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001219 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001220 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001221 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001222 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001223 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001224 if (sender_info) {
1225 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001226 }
deadbeefe1f9d832016-01-14 15:35:42 -08001227 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001228 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001229}
deadbeefe1f9d832016-01-14 15:35:42 -08001230
Steve Antonf9381f02017-12-14 10:23:57 -08001231RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1232PeerConnection::AddTrackUnifiedPlan(
1233 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001234 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001235 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1236 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001237 RTC_LOG(LS_INFO) << "Reusing an existing "
1238 << cricket::MediaTypeToString(transceiver->media_type())
1239 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001240 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001241 transceiver->internal()->set_direction(
1242 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001243 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001244 transceiver->internal()->set_direction(
1245 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001246 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001247 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001248 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001249 } else {
1250 cricket::MediaType media_type =
1251 (track->kind() == MediaStreamTrackInterface::kAudioKind
1252 ? cricket::MEDIA_TYPE_AUDIO
1253 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001254 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1255 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 11:34:10 -08001256 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001257 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1258 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001259 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001260 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001261 }
Steve Antonf9381f02017-12-14 10:23:57 -08001262 return transceiver->sender();
1263}
1264
1265rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1266PeerConnection::FindFirstTransceiverForAddedTrack(
1267 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1268 RTC_DCHECK(track);
1269 for (auto transceiver : transceivers_) {
1270 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001271 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001272 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001273 !transceiver->internal()->has_ever_been_used_to_send() &&
1274 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001275 return transceiver;
1276 }
1277 }
1278 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001279}
1280
1281bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1282 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001283 return RemoveTrackInternal(sender).ok();
1284}
1285
1286RTCError PeerConnection::RemoveTrackInternal(
1287 rtc::scoped_refptr<RtpSenderInterface> sender) {
1288 if (!sender) {
1289 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1290 }
deadbeefe1f9d832016-01-14 15:35:42 -08001291 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001292 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1293 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001294 }
Steve Antonf9381f02017-12-14 10:23:57 -08001295 if (IsUnifiedPlan()) {
1296 auto transceiver = FindTransceiverBySender(sender);
1297 if (!transceiver || !sender->track()) {
1298 return RTCError::OK();
1299 }
1300 sender->SetTrack(nullptr);
1301 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001302 transceiver->internal()->set_direction(
1303 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001304 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001305 transceiver->internal()->set_direction(
1306 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001307 }
Steve Anton4171afb2017-11-20 10:20:22 -08001308 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001309 bool removed;
1310 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1311 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1312 } else {
1313 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1314 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1315 }
1316 if (!removed) {
1317 LOG_AND_RETURN_ERROR(
1318 RTCErrorType::INVALID_PARAMETER,
1319 "Couldn't find sender " + sender->id() + " to remove.");
1320 }
Steve Anton4171afb2017-11-20 10:20:22 -08001321 }
deadbeefe1f9d832016-01-14 15:35:42 -08001322 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001323 return RTCError::OK();
1324}
1325
1326rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1327PeerConnection::FindTransceiverBySender(
1328 rtc::scoped_refptr<RtpSenderInterface> sender) {
1329 for (auto transceiver : transceivers_) {
1330 if (transceiver->sender() == sender) {
1331 return transceiver;
1332 }
1333 }
1334 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001335}
1336
Steve Anton9158ef62017-11-27 13:01:52 -08001337RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1338PeerConnection::AddTransceiver(
1339 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1340 return AddTransceiver(track, RtpTransceiverInit());
1341}
1342
1343RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1344PeerConnection::AddTransceiver(
1345 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1346 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001347 RTC_CHECK(IsUnifiedPlan())
1348 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001349 if (!track) {
1350 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1351 }
1352 cricket::MediaType media_type;
1353 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1354 media_type = cricket::MEDIA_TYPE_AUDIO;
1355 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1356 media_type = cricket::MEDIA_TYPE_VIDEO;
1357 } else {
1358 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1359 "Track kind is not audio or video");
1360 }
1361 return AddTransceiver(media_type, track, init);
1362}
1363
1364RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1365PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1366 return AddTransceiver(media_type, RtpTransceiverInit());
1367}
1368
1369RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1370PeerConnection::AddTransceiver(cricket::MediaType media_type,
1371 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001372 RTC_CHECK(IsUnifiedPlan())
1373 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001374 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1375 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1376 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1377 "media type is not audio or video");
1378 }
1379 return AddTransceiver(media_type, nullptr, init);
1380}
1381
1382RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1383PeerConnection::AddTransceiver(
1384 cricket::MediaType media_type,
1385 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001386 const RtpTransceiverInit& init,
1387 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001388 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1389 media_type == cricket::MEDIA_TYPE_VIDEO));
1390 if (track) {
1391 RTC_DCHECK_EQ(media_type,
1392 (track->kind() == MediaStreamTrackInterface::kAudioKind
1393 ? cricket::MEDIA_TYPE_AUDIO
1394 : cricket::MEDIA_TYPE_VIDEO));
1395 }
1396
1397 // TODO(bugs.webrtc.org/7600): Verify init.
1398
Steve Anton3d954a62018-04-02 11:27:23 -07001399 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1400 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 16:31:36 -07001401 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001402 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1403 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1404 transceiver->internal()->set_direction(init.direction);
1405
Steve Anton22da89f2018-01-25 13:58:07 -08001406 if (fire_callback) {
1407 observer_->OnRenegotiationNeeded();
1408 }
Steve Antonf9381f02017-12-14 10:23:57 -08001409
1410 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1411}
1412
Steve Anton02ee47c2018-01-10 16:26:06 -08001413rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1414PeerConnection::CreateSender(
1415 cricket::MediaType media_type,
1416 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001417 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001418 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001419 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1420 RTC_DCHECK(!track ||
1421 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1422 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1423 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001424 new AudioRtpSender(worker_thread(),
1425 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001426 stream_ids, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001427 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001428 } else {
1429 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1430 RTC_DCHECK(!track ||
1431 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1432 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1433 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001434 new VideoRtpSender(worker_thread(),
1435 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001436 stream_ids));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001437 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001438 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001439 return sender;
1440}
1441
1442rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1443PeerConnection::CreateReceiver(cricket::MediaType media_type,
1444 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001445 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1446 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001447 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001448 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001449 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001450 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001451 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001452 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001453 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001454 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1455 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001456 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001457 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001458 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001459 return receiver;
1460}
1461
1462rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1463PeerConnection::CreateAndAddTransceiver(
1464 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1465 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1466 receiver) {
1467 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1468 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001469 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001470 transceiver->internal()->SignalNegotiationNeeded.connect(
1471 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001472 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001473}
1474
Steve Anton52d86772018-02-20 15:48:12 -08001475void PeerConnection::OnNegotiationNeeded() {
1476 RTC_DCHECK_RUN_ON(signaling_thread());
1477 RTC_DCHECK(!IsClosed());
1478 observer_->OnRenegotiationNeeded();
1479}
1480
deadbeeffac06552015-11-25 11:26:01 -08001481rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001482 const std::string& kind,
1483 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001484 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1485 "Plan SdpSemantics. Please use AddTransceiver "
1486 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001487 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001488 if (IsClosed()) {
1489 return nullptr;
1490 }
Steve Anton4171afb2017-11-20 10:20:22 -08001491
Seth Hampson5b4f0752018-04-02 16:31:36 -07001492 // Internally we need to have one stream with Plan B semantics, so we
1493 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001494 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001495 if (stream_id.empty()) {
1496 stream_ids.push_back(rtc::CreateRandomUuid());
1497 RTC_LOG(LS_INFO)
1498 << "No stream_id specified for sender. Generated stream ID: "
1499 << stream_ids[0];
1500 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001501 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001502 }
1503
Steve Anton4171afb2017-11-20 10:20:22 -08001504 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001505 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001506 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001507 auto* audio_sender =
1508 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001509 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001510 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001511 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001512 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001513 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001514 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001515 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001516 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001517 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001518 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001519 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001520 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001521 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001522 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001523 }
Steve Anton4171afb2017-11-20 10:20:22 -08001524
deadbeefe1f9d832016-01-14 15:35:42 -08001525 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001526}
1527
deadbeef70ab1a12015-09-28 16:53:55 -07001528std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1529 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001530 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001531 for (auto sender : GetSendersInternal()) {
1532 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001533 }
1534 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001535}
1536
Steve Anton4171afb2017-11-20 10:20:22 -08001537std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1538PeerConnection::GetSendersInternal() const {
1539 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1540 all_senders;
1541 for (auto transceiver : transceivers_) {
1542 auto senders = transceiver->internal()->senders();
1543 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1544 }
1545 return all_senders;
1546}
1547
deadbeef70ab1a12015-09-28 16:53:55 -07001548std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1549PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001550 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001551 for (const auto& receiver : GetReceiversInternal()) {
1552 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001553 }
1554 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001555}
1556
Steve Anton4171afb2017-11-20 10:20:22 -08001557std::vector<
1558 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1559PeerConnection::GetReceiversInternal() const {
1560 std::vector<
1561 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1562 all_receivers;
1563 for (auto transceiver : transceivers_) {
1564 auto receivers = transceiver->internal()->receivers();
1565 all_receivers.insert(all_receivers.end(), receivers.begin(),
1566 receivers.end());
1567 }
1568 return all_receivers;
1569}
1570
Steve Anton9158ef62017-11-27 13:01:52 -08001571std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1572PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001573 RTC_CHECK(IsUnifiedPlan())
1574 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001575 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1576 for (auto transceiver : transceivers_) {
1577 all_transceivers.push_back(transceiver);
1578 }
1579 return all_transceivers;
1580}
1581
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001583 MediaStreamTrackInterface* track,
1584 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001585 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001586 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001587 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001588 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001589 return false;
1590 }
1591
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001592 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001593 // The StatsCollector is used to tell if a track is valid because it may
1594 // remember tracks that the PeerConnection previously removed.
1595 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001596 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1597 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001598 return false;
1599 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001600 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001601 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001602 return true;
1603}
1604
hbos74e1a4f2016-09-15 23:33:01 -07001605void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001606 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001607 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001608 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001609 stats_collector_->GetStatsReport(callback);
1610}
1611
Henrik Boström1df1bf82018-03-20 13:24:20 +01001612void PeerConnection::GetStats(
1613 rtc::scoped_refptr<RtpSenderInterface> selector,
1614 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1615 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1616 RTC_DCHECK(callback);
1617 RTC_DCHECK(stats_collector_);
1618 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1619 if (selector) {
1620 for (const auto& proxy_transceiver : transceivers_) {
1621 for (const auto& proxy_sender :
1622 proxy_transceiver->internal()->senders()) {
1623 if (proxy_sender == selector) {
1624 internal_sender = proxy_sender->internal();
1625 break;
1626 }
1627 }
1628 if (internal_sender)
1629 break;
1630 }
1631 }
1632 // If there is no |internal_sender| then |selector| is either null or does not
1633 // belong to the PeerConnection (in Plan B, senders can be removed from the
1634 // PeerConnection). This means that "all the stats objects representing the
1635 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1636 // produces an empty stats report.
1637 stats_collector_->GetStatsReport(internal_sender, callback);
1638}
1639
1640void PeerConnection::GetStats(
1641 rtc::scoped_refptr<RtpReceiverInterface> selector,
1642 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1643 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1644 RTC_DCHECK(callback);
1645 RTC_DCHECK(stats_collector_);
1646 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1647 if (selector) {
1648 for (const auto& proxy_transceiver : transceivers_) {
1649 for (const auto& proxy_receiver :
1650 proxy_transceiver->internal()->receivers()) {
1651 if (proxy_receiver == selector) {
1652 internal_receiver = proxy_receiver->internal();
1653 break;
1654 }
1655 }
1656 if (internal_receiver)
1657 break;
1658 }
1659 }
1660 // If there is no |internal_receiver| then |selector| is either null or does
1661 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1662 // the PeerConnection). This means that "all the stats objects representing
1663 // the selector" is an empty set. Invoking GetStatsReport() with a null
1664 // selector produces an empty stats report.
1665 stats_collector_->GetStatsReport(internal_receiver, callback);
1666}
1667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001668PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1669 return signaling_state_;
1670}
1671
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672PeerConnectionInterface::IceConnectionState
1673PeerConnection::ice_connection_state() {
1674 return ice_connection_state_;
1675}
1676
1677PeerConnectionInterface::IceGatheringState
1678PeerConnection::ice_gathering_state() {
1679 return ice_gathering_state_;
1680}
1681
Yves Gerey665174f2018-06-19 15:03:05 +02001682rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683 const std::string& label,
1684 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001685 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001686
deadbeefab9b2d12015-10-14 11:33:11 -07001687 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001688
kwibergd1fe2812016-04-27 06:47:29 -07001689 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001690 if (config) {
1691 internal_config.reset(new InternalDataChannelInit(*config));
1692 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001693 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001694 InternalCreateDataChannel(label, internal_config.get()));
1695 if (!channel.get()) {
1696 return nullptr;
1697 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001699 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1700 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001701 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001702 observer_->OnRenegotiationNeeded();
1703 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001704 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705 return DataChannelProxy::Create(signaling_thread(), channel.get());
1706}
1707
1708void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1709 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001710 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001711
zhihuang1c378ed2017-08-17 14:10:50 -07001712 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1713 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1714 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1715 // compares the mandatory fields parsed with the mandatory fields added in the
1716 // |constraints| and some downstream applications might create offers with
1717 // mandatory fields which would not be parsed in the helper method. For
1718 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1719 // |constraints| as a mandatory field but it is not parsed.
1720 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001721
zhihuang1c378ed2017-08-17 14:10:50 -07001722 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001723}
1724
1725void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1726 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001727 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001728
nisse7ce109a2017-01-31 00:57:56 -08001729 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001730 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001731 return;
1732 }
deadbeefab9b2d12015-10-14 11:33:11 -07001733
Steve Anton8d3444d2017-10-20 15:30:51 -07001734 if (IsClosed()) {
1735 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001736 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001737 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001738 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001739 return;
1740 }
1741
zhihuang1c378ed2017-08-17 14:10:50 -07001742 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001743 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001744 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001745 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001746 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001747 return;
1748 }
1749
Steve Anton22da89f2018-01-25 13:58:07 -08001750 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1751 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1752 if (IsUnifiedPlan()) {
1753 RTCError error = HandleLegacyOfferOptions(options);
1754 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001755 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001756 return;
1757 }
1758 }
1759
zhihuang1c378ed2017-08-17 14:10:50 -07001760 cricket::MediaSessionOptions session_options;
1761 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001762 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763}
1764
Steve Anton22da89f2018-01-25 13:58:07 -08001765RTCError PeerConnection::HandleLegacyOfferOptions(
1766 const RTCOfferAnswerOptions& options) {
1767 RTC_DCHECK(IsUnifiedPlan());
1768
1769 if (options.offer_to_receive_audio == 0) {
1770 RemoveRecvDirectionFromReceivingTransceiversOfType(
1771 cricket::MEDIA_TYPE_AUDIO);
1772 } else if (options.offer_to_receive_audio == 1) {
1773 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1774 } else if (options.offer_to_receive_audio > 1) {
1775 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1776 "offer_to_receive_audio > 1 is not supported.");
1777 }
1778
1779 if (options.offer_to_receive_video == 0) {
1780 RemoveRecvDirectionFromReceivingTransceiversOfType(
1781 cricket::MEDIA_TYPE_VIDEO);
1782 } else if (options.offer_to_receive_video == 1) {
1783 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1784 } else if (options.offer_to_receive_video > 1) {
1785 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1786 "offer_to_receive_video > 1 is not supported.");
1787 }
1788
1789 return RTCError::OK();
1790}
1791
1792void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1793 cricket::MediaType media_type) {
1794 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001795 RtpTransceiverDirection new_direction =
1796 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1797 if (new_direction != transceiver->direction()) {
1798 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1799 << " transceiver (MID="
1800 << transceiver->mid().value_or("<not set>") << ") from "
1801 << RtpTransceiverDirectionToString(
1802 transceiver->direction())
1803 << " to "
1804 << RtpTransceiverDirectionToString(new_direction)
1805 << " since CreateOffer specified offer_to_receive=0";
1806 transceiver->internal()->set_direction(new_direction);
1807 }
Steve Anton22da89f2018-01-25 13:58:07 -08001808 }
1809}
1810
1811void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1812 cricket::MediaType media_type) {
1813 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001814 RTC_LOG(LS_INFO)
1815 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1816 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001817 RtpTransceiverInit init;
1818 init.direction = RtpTransceiverDirection::kRecvOnly;
1819 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1820 }
1821}
1822
1823std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1824PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1825 std::vector<
1826 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1827 receiving_transceivers;
1828 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001829 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001830 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1831 receiving_transceivers.push_back(transceiver);
1832 }
1833 }
1834 return receiving_transceivers;
1835}
1836
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001837void PeerConnection::CreateAnswer(
1838 CreateSessionDescriptionObserver* observer,
1839 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001840 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001841
nisse7ce109a2017-01-31 00:57:56 -08001842 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001843 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844 return;
1845 }
deadbeefab9b2d12015-10-14 11:33:11 -07001846
zhihuang1c378ed2017-08-17 14:10:50 -07001847 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1848 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1849 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001850 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001851 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001852 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001853 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001854 return;
1855 }
1856
Steve Anton8d3444d2017-10-20 15:30:51 -07001857 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001858}
1859
1860void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1861 const RTCOfferAnswerOptions& options) {
1862 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001863 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001864 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001865 return;
1866 }
1867
Steve Antondffead82018-02-06 10:31:29 -08001868 if (!(signaling_state_ == kHaveRemoteOffer ||
1869 signaling_state_ == kHaveLocalPrAnswer)) {
1870 std::string error =
1871 "PeerConnection cannot create an answer in a state other than "
1872 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001873 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001874 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001875 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001876 return;
1877 }
1878
Steve Antondffead82018-02-06 10:31:29 -08001879 // The remote description should be set if we're in the right state.
1880 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001881
Steve Anton22da89f2018-01-25 13:58:07 -08001882 if (IsUnifiedPlan()) {
1883 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1884 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1885 "supported with Unified Plan semantics. Use the "
1886 "RtpTransceiver API instead.";
1887 }
1888 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1889 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1890 "supported with Unified Plan semantics. Use the "
1891 "RtpTransceiver API instead.";
1892 }
1893 }
1894
htaa2a49d92016-03-04 02:51:39 -08001895 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001896 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001897
Steve Antond25da372017-11-06 14:50:29 -08001898 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001899}
1900
1901void PeerConnection::SetLocalDescription(
1902 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001903 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001904 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001905
Steve Anton80dd7b52018-02-16 17:08:42 -08001906 // The SetLocalDescription contract is that we take ownership of the session
1907 // description regardless of the outcome, so wrap it in a unique_ptr right
1908 // away. Ideally, SetLocalDescription's signature will be changed to take the
1909 // description as a unique_ptr argument to formalize this agreement.
1910 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1911
nisse7ce109a2017-01-31 00:57:56 -08001912 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001913 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914 return;
1915 }
Steve Anton8a006912017-12-04 15:25:56 -08001916
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001917 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001918 PostSetSessionDescriptionFailure(
1919 observer,
1920 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001921 return;
1922 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001923
Steve Anton80dd7b52018-02-16 17:08:42 -08001924 // If a session error has occurred the PeerConnection is in a possibly
1925 // inconsistent state so fail right away.
1926 if (session_error() != SessionError::kNone) {
1927 std::string error_message = GetSessionErrorMsg();
1928 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001929 PostSetSessionDescriptionFailure(
1930 observer,
1931 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001932 return;
1933 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001934
Steve Anton80dd7b52018-02-16 17:08:42 -08001935 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1936 if (!error.ok()) {
1937 std::string error_message = GetSetDescriptionErrorMessage(
1938 cricket::CS_LOCAL, desc->GetType(), error);
1939 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001940 PostSetSessionDescriptionFailure(
1941 observer,
1942 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001943 return;
1944 }
1945
1946 // Grab the description type before moving ownership to ApplyLocalDescription,
1947 // which may destroy it before returning.
1948 const SdpType type = desc->GetType();
1949
1950 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001951 // |desc| may be destroyed at this point.
1952
1953 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001954 // If ApplyLocalDescription fails, the PeerConnection could be in an
1955 // inconsistent state, so act conservatively here and set the session error
1956 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1957 SetSessionError(SessionError::kContent, error.message());
1958 std::string error_message =
1959 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1960 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001961 PostSetSessionDescriptionFailure(
1962 observer,
1963 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001964 return;
1965 }
Steve Anton8a006912017-12-04 15:25:56 -08001966 RTC_DCHECK(local_description());
1967
1968 PostSetSessionDescriptionSuccess(observer);
1969
Steve Anton8a006912017-12-04 15:25:56 -08001970 // MaybeStartGathering needs to be called after posting
1971 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1972 // before signaling that SetLocalDescription completed.
1973 transport_controller_->MaybeStartGathering();
1974
Steve Antona3a92c22017-12-07 10:27:41 -08001975 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001976 // TODO(deadbeef): We already had to hop to the network thread for
1977 // MaybeStartGathering...
1978 network_thread()->Invoke<void>(
1979 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1980 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001981 // Make UMA notes about what was agreed to.
1982 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001983 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001984 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001985}
1986
1987RTCError PeerConnection::ApplyLocalDescription(
1988 std::unique_ptr<SessionDescriptionInterface> desc) {
1989 RTC_DCHECK_RUN_ON(signaling_thread());
1990 RTC_DCHECK(desc);
1991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 // Update stats here so that we have the most recent stats for tracks and
1993 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001994 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001995
Steve Antondcc3c022017-12-22 16:02:54 -08001996 // Take a reference to the old local description since it's used below to
1997 // compare against the new local description. When setting the new local
1998 // description, grab ownership of the replaced session description in case it
1999 // is the same as |old_local_description|, to keep it alive for the duration
2000 // of the method.
2001 const SessionDescriptionInterface* old_local_description =
2002 local_description();
2003 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002004 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002005 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002006 replaced_local_description = pending_local_description_
2007 ? std::move(pending_local_description_)
2008 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002009 current_local_description_ = std::move(desc);
2010 pending_local_description_ = nullptr;
2011 current_remote_description_ = std::move(pending_remote_description_);
2012 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002013 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002014 pending_local_description_ = std::move(desc);
2015 }
2016 // The session description to apply now must be accessed by
2017 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002018 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002019
Zhi Huange830e682018-03-30 10:48:35 -07002020 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2021 if (!error.ok()) {
2022 return error;
2023 }
2024
Steve Antondcc3c022017-12-22 16:02:54 -08002025 if (IsUnifiedPlan()) {
2026 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002027 cricket::CS_LOCAL, *local_description(), old_local_description,
2028 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002029 if (!error.ok()) {
2030 return error;
2031 }
Steve Antondcc3c022017-12-22 16:02:54 -08002032 for (auto transceiver : transceivers_) {
2033 const ContentInfo* content =
2034 FindMediaSectionForTransceiver(transceiver, local_description());
2035 if (!content) {
2036 continue;
2037 }
2038 const MediaContentDescription* media_desc = content->media_description();
2039 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2040 transceiver->internal()->set_current_direction(media_desc->direction());
2041 }
2042 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002043 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2044 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002045 transceiver->Stop();
2046 }
2047 }
2048 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002049 // Media channels will be created only when offer is set. These may use new
2050 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002051 if (type == SdpType::kOffer) {
2052 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2053 // description is applied. Restore back to old description.
2054 RTCError error = CreateChannels(*local_description()->description());
2055 if (!error.ok()) {
2056 return error;
2057 }
2058 }
Steve Antondcc3c022017-12-22 16:02:54 -08002059 // Remove unused channels if MediaContentDescription is rejected.
2060 RemoveUnusedChannels(local_description()->description());
2061 }
Steve Anton8a006912017-12-04 15:25:56 -08002062
Zhi Huange830e682018-03-30 10:48:35 -07002063 error = UpdateSessionState(type, cricket::CS_LOCAL,
2064 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002065 if (!error.ok()) {
2066 return error;
2067 }
Steve Antondcc3c022017-12-22 16:02:54 -08002068
Steve Anton8a006912017-12-04 15:25:56 -08002069 if (remote_description()) {
2070 // Now that we have a local description, we can push down remote candidates.
2071 UseCandidatesInSessionDescription(remote_description());
2072 }
2073
2074 pending_ice_restarts_.clear();
2075 if (session_error() != SessionError::kNone) {
2076 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2077 }
2078
deadbeefab9b2d12015-10-14 11:33:11 -07002079 // If setting the description decided our SSL role, allocate any necessary
2080 // SCTP sids.
2081 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002082 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002083 AllocateSctpSids(role);
2084 }
2085
Steve Antond3679212018-01-17 17:41:02 -08002086 if (IsUnifiedPlan()) {
2087 for (auto transceiver : transceivers_) {
2088 const ContentInfo* content =
2089 FindMediaSectionForTransceiver(transceiver, local_description());
2090 if (!content) {
2091 continue;
2092 }
Steve Anton74255ff2018-01-24 18:32:57 -08002093 const auto& streams = content->media_description()->streams();
2094 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002095 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002096 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002097 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002098 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002099 } else {
2100 // 0 is a special value meaning "this sender has no associated send
2101 // stream". Need to call this so the sender won't attempt to configure
2102 // a no longer existing stream and run into DCHECKs in the lower
2103 // layers.
2104 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002105 }
2106 }
2107 } else {
2108 // Plan B semantics.
2109
Steve Antondcc3c022017-12-22 16:02:54 -08002110 // Update state and SSRC of local MediaStreams and DataChannels based on the
2111 // local session description.
2112 const cricket::ContentInfo* audio_content =
2113 GetFirstAudioContent(local_description()->description());
2114 if (audio_content) {
2115 if (audio_content->rejected) {
2116 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2117 } else {
2118 const cricket::AudioContentDescription* audio_desc =
2119 audio_content->media_description()->as_audio();
2120 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2121 }
deadbeeffaac4972015-11-12 15:33:07 -08002122 }
deadbeefab9b2d12015-10-14 11:33:11 -07002123
Steve Antondcc3c022017-12-22 16:02:54 -08002124 const cricket::ContentInfo* video_content =
2125 GetFirstVideoContent(local_description()->description());
2126 if (video_content) {
2127 if (video_content->rejected) {
2128 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2129 } else {
2130 const cricket::VideoContentDescription* video_desc =
2131 video_content->media_description()->as_video();
2132 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2133 }
deadbeeffaac4972015-11-12 15:33:07 -08002134 }
deadbeefab9b2d12015-10-14 11:33:11 -07002135 }
2136
2137 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002138 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002139 if (data_content) {
2140 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002141 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002142 if (rtc::starts_with(data_desc->protocol().data(),
2143 cricket::kMediaProtocolRtpPrefix)) {
2144 UpdateLocalRtpDataChannels(data_desc->streams());
2145 }
2146 }
2147
Steve Anton8a006912017-12-04 15:25:56 -08002148 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149}
2150
2151void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002152 SetSessionDescriptionObserver* observer,
2153 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002154 SetRemoteDescription(
2155 std::unique_ptr<SessionDescriptionInterface>(desc),
2156 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2157 new SetRemoteDescriptionObserverAdapter(this, observer)));
2158}
2159
2160void PeerConnection::SetRemoteDescription(
2161 std::unique_ptr<SessionDescriptionInterface> desc,
2162 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002163 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002164
nisse7ce109a2017-01-31 00:57:56 -08002165 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002166 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002167 return;
2168 }
Steve Anton8a006912017-12-04 15:25:56 -08002169
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002170 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002171 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002172 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002173 return;
2174 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002175
Steve Anton80dd7b52018-02-16 17:08:42 -08002176 // If a session error has occurred the PeerConnection is in a possibly
2177 // inconsistent state so fail right away.
2178 if (session_error() != SessionError::kNone) {
2179 std::string error_message = GetSessionErrorMsg();
2180 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2181 observer->OnSetRemoteDescriptionComplete(
2182 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2183 return;
2184 }
Steve Anton71439a62018-02-15 11:53:06 -08002185
Steve Antonba42e992018-04-09 14:10:01 -07002186 if (desc->GetType() == SdpType::kOffer) {
2187 // Report to UMA the format of the received offer.
2188 ReportSdpFormatReceived(*desc);
2189 }
2190
Steve Anton80dd7b52018-02-16 17:08:42 -08002191 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002192 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002193 std::string error_message = GetSetDescriptionErrorMessage(
2194 cricket::CS_REMOTE, desc->GetType(), error);
2195 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002196 observer->OnSetRemoteDescriptionComplete(
2197 RTCError(error.type(), std::move(error_message)));
2198 return;
2199 }
Steve Anton71439a62018-02-15 11:53:06 -08002200
Steve Anton80dd7b52018-02-16 17:08:42 -08002201 // Grab the description type before moving ownership to
2202 // ApplyRemoteDescription, which may destroy it before returning.
2203 const SdpType type = desc->GetType();
2204
2205 error = ApplyRemoteDescription(std::move(desc));
2206 // |desc| may be destroyed at this point.
2207
2208 if (!error.ok()) {
2209 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2210 // inconsistent state, so act conservatively here and set the session error
2211 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2212 SetSessionError(SessionError::kContent, error.message());
2213 std::string error_message =
2214 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2215 RTC_LOG(LS_ERROR) << error_message;
2216 observer->OnSetRemoteDescriptionComplete(
2217 RTCError(error.type(), std::move(error_message)));
2218 return;
2219 }
2220 RTC_DCHECK(remote_description());
2221
2222 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002223 // TODO(deadbeef): We already had to hop to the network thread for
2224 // MaybeStartGathering...
2225 network_thread()->Invoke<void>(
2226 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2227 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002228 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002229 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002230 }
2231
2232 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002233 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002234}
2235
2236RTCError PeerConnection::ApplyRemoteDescription(
2237 std::unique_ptr<SessionDescriptionInterface> desc) {
2238 RTC_DCHECK_RUN_ON(signaling_thread());
2239 RTC_DCHECK(desc);
2240
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002241 // Update stats here so that we have the most recent stats for tracks and
2242 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002243 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002244
Steve Antondcc3c022017-12-22 16:02:54 -08002245 // Take a reference to the old remote description since it's used below to
2246 // compare against the new remote description. When setting the new remote
2247 // description, grab ownership of the replaced session description in case it
2248 // is the same as |old_remote_description|, to keep it alive for the duration
2249 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002250 const SessionDescriptionInterface* old_remote_description =
2251 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002252 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002253 SdpType type = desc->GetType();
2254 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002255 replaced_remote_description = pending_remote_description_
2256 ? std::move(pending_remote_description_)
2257 : std::move(current_remote_description_);
2258 current_remote_description_ = std::move(desc);
2259 pending_remote_description_ = nullptr;
2260 current_local_description_ = std::move(pending_local_description_);
2261 } else {
2262 replaced_remote_description = std::move(pending_remote_description_);
2263 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002264 }
Steve Anton8a006912017-12-04 15:25:56 -08002265 // The session description to apply now must be accessed by
2266 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002267 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002268
Zhi Huange830e682018-03-30 10:48:35 -07002269 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2270 if (!error.ok()) {
2271 return error;
2272 }
Steve Anton8a006912017-12-04 15:25:56 -08002273 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002274 if (IsUnifiedPlan()) {
2275 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002276 cricket::CS_REMOTE, *remote_description(), local_description(),
2277 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002278 if (!error.ok()) {
2279 return error;
2280 }
Steve Antondcc3c022017-12-22 16:02:54 -08002281 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002282 // Media channels will be created only when offer is set. These may use new
2283 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002284 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002285 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002286 // description is applied. Restore back to old description.
2287 RTCError error = CreateChannels(*remote_description()->description());
2288 if (!error.ok()) {
2289 return error;
2290 }
2291 }
Steve Antondcc3c022017-12-22 16:02:54 -08002292 // Remove unused channels if MediaContentDescription is rejected.
2293 RemoveUnusedChannels(remote_description()->description());
2294 }
Steve Anton8a006912017-12-04 15:25:56 -08002295
Zhi Huange830e682018-03-30 10:48:35 -07002296 // NOTE: Candidates allocation will be initiated only when
2297 // SetLocalDescription is called.
2298 error = UpdateSessionState(type, cricket::CS_REMOTE,
2299 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002300 if (!error.ok()) {
2301 return error;
2302 }
2303
2304 if (local_description() &&
2305 !UseCandidatesInSessionDescription(remote_description())) {
2306 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2307 }
2308
2309 if (old_remote_description) {
2310 for (const cricket::ContentInfo& content :
2311 old_remote_description->description()->contents()) {
2312 // Check if this new SessionDescription contains new ICE ufrag and
2313 // password that indicates the remote peer requests an ICE restart.
2314 // TODO(deadbeef): When we start storing both the current and pending
2315 // remote description, this should reset pending_ice_restarts and compare
2316 // against the current description.
2317 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2318 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002319 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002320 pending_ice_restarts_.insert(content.name);
2321 }
2322 } else {
2323 // We retain all received candidates only if ICE is not restarted.
2324 // When ICE is restarted, all previous candidates belong to an old
2325 // generation and should not be kept.
2326 // TODO(deadbeef): This goes against the W3C spec which says the remote
2327 // description should only contain candidates from the last set remote
2328 // description plus any candidates added since then. We should remove
2329 // this once we're sure it won't break anything.
2330 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2331 old_remote_description, content.name, mutable_remote_description());
2332 }
2333 }
2334 }
2335
2336 if (session_error() != SessionError::kNone) {
2337 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2338 }
2339
2340 // Set the the ICE connection state to connecting since the connection may
2341 // become writable with peer reflexive candidates before any remote candidate
2342 // is signaled.
2343 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2344 // is to have a new signal the indicates a change in checking state from the
2345 // transport and expose a new checking() member from transport that can be
2346 // read to determine the current checking state. The existing SignalConnecting
2347 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002348 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002349 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002350 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2351 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2352 }
2353
deadbeefab9b2d12015-10-14 11:33:11 -07002354 // If setting the description decided our SSL role, allocate any necessary
2355 // SCTP sids.
2356 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002357 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002358 AllocateSctpSids(role);
2359 }
2360
Steve Antondcc3c022017-12-22 16:02:54 -08002361 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002362 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002363 now_receiving_transceivers;
2364 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2365 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002366 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002367 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002368 for (auto transceiver : transceivers_) {
2369 const ContentInfo* content =
2370 FindMediaSectionForTransceiver(transceiver, remote_description());
2371 if (!content) {
2372 continue;
2373 }
2374 const MediaContentDescription* media_desc = content->media_description();
2375 RtpTransceiverDirection local_direction =
2376 RtpTransceiverDirectionReversed(media_desc->direction());
2377 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2378 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2379 // transceiver's current direction is neither sendrecv nor recvonly,
2380 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002381 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002382 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002383 // The remote description has signaled the stream IDs.
2384 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002385 }
Steve Antondcc3c022017-12-22 16:02:54 -08002386 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2387 (!transceiver->current_direction() ||
2388 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002389 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002390 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002391 << content->name << " (added to "
2392 << GetStreamIdsString(stream_ids) << ").";
2393
2394 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2395 for (const std::string& stream_id : stream_ids) {
2396 rtc::scoped_refptr<MediaStreamInterface> stream =
2397 remote_streams_->find(stream_id);
2398 if (!stream) {
2399 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2400 MediaStream::Create(stream_id));
2401 remote_streams_->AddStream(stream);
2402 added_streams.push_back(stream);
2403 }
2404 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002405 }
Steve Anton3172c032018-05-03 15:30:18 -07002406 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002407 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002408 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002409 }
2410 // If direction is sendonly or inactive, and transceiver's current
2411 // direction is neither sendonly nor inactive, process the removal of a
2412 // remote track for the media description.
2413 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002414 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002415 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002416 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2417 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002418 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2419 transceiver->internal()->receiver_internal()->streams();
2420 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002421 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002422 no_longer_receiving_transceivers.push_back(transceiver);
2423 // Remove any streams that no longer have tracks.
2424 for (auto stream : media_streams) {
2425 if (stream->GetAudioTracks().empty() &&
2426 stream->GetVideoTracks().empty()) {
2427 remote_streams_->RemoveStream(stream);
2428 removed_streams.push_back(stream);
2429 }
2430 }
Steve Antondcc3c022017-12-22 16:02:54 -08002431 }
2432 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2433 transceiver->internal()->set_current_direction(local_direction);
2434 }
2435 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002436 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2437 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002438 transceiver->Stop();
2439 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002440 if (!content->rejected &&
2441 RtpTransceiverDirectionHasRecv(local_direction)) {
2442 // Set ssrc to 0 in the case of an unsignalled ssrc.
2443 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002444 if (!media_desc->streams().empty() &&
2445 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002446 ssrc = media_desc->streams()[0].first_ssrc();
2447 }
2448 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002449 }
Steve Antondcc3c022017-12-22 16:02:54 -08002450 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002451 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002452 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002453 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002454 observer_->OnTrack(transceiver);
2455 observer_->OnAddTrack(transceiver->receiver(),
2456 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002457 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002458 for (auto stream : added_streams) {
2459 observer_->OnAddStream(stream);
2460 }
Steve Anton3172c032018-05-03 15:30:18 -07002461 for (auto transceiver : no_longer_receiving_transceivers) {
2462 observer_->OnRemoveTrack(transceiver->receiver());
2463 }
2464 for (auto stream : removed_streams) {
2465 observer_->OnRemoveStream(stream);
2466 }
Steve Antondcc3c022017-12-22 16:02:54 -08002467 }
2468
Henrik Boströmfdb92012017-11-09 19:55:44 +01002469 const cricket::ContentInfo* audio_content =
2470 GetFirstAudioContent(remote_description()->description());
2471 const cricket::ContentInfo* video_content =
2472 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002473 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002474 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002475 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002476 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002477 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002478 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002479
2480 // Check if the descriptions include streams, just in case the peer supports
2481 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002482 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002483 (audio_desc && !audio_desc->streams().empty()) ||
2484 (video_desc && !video_desc->streams().empty())) {
2485 remote_peer_supports_msid_ = true;
2486 }
deadbeefab9b2d12015-10-14 11:33:11 -07002487
2488 // We wait to signal new streams until we finish processing the description,
2489 // since only at that point will new streams have all their tracks.
2490 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2491
Steve Antondcc3c022017-12-22 16:02:54 -08002492 if (!IsUnifiedPlan()) {
2493 // TODO(steveanton): When removing RTP senders/receivers in response to a
2494 // rejected media section, there is some cleanup logic that expects the
2495 // voice/ video channel to still be set. But in this method the voice/video
2496 // channel would have been destroyed by the SetRemoteDescription caller
2497 // above so the cleanup that relies on them fails to run. The RemoveSenders
2498 // calls should be moved to right before the DestroyChannel calls to fix
2499 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002500
Steve Antondcc3c022017-12-22 16:02:54 -08002501 // Find all audio rtp streams and create corresponding remote AudioTracks
2502 // and MediaStreams.
2503 if (audio_content) {
2504 if (audio_content->rejected) {
2505 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2506 } else {
2507 bool default_audio_track_needed =
2508 !remote_peer_supports_msid_ &&
2509 RtpTransceiverDirectionHasSend(audio_desc->direction());
2510 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2511 default_audio_track_needed, audio_desc->type(),
2512 new_streams);
2513 }
deadbeeffaac4972015-11-12 15:33:07 -08002514 }
deadbeefab9b2d12015-10-14 11:33:11 -07002515
Steve Antondcc3c022017-12-22 16:02:54 -08002516 // Find all video rtp streams and create corresponding remote VideoTracks
2517 // and MediaStreams.
2518 if (video_content) {
2519 if (video_content->rejected) {
2520 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2521 } else {
2522 bool default_video_track_needed =
2523 !remote_peer_supports_msid_ &&
2524 RtpTransceiverDirectionHasSend(video_desc->direction());
2525 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2526 default_video_track_needed, video_desc->type(),
2527 new_streams);
2528 }
deadbeeffaac4972015-11-12 15:33:07 -08002529 }
deadbeefab9b2d12015-10-14 11:33:11 -07002530
Steve Antondcc3c022017-12-22 16:02:54 -08002531 // Update the DataChannels with the information from the remote peer.
2532 if (data_desc) {
2533 if (rtc::starts_with(data_desc->protocol().data(),
2534 cricket::kMediaProtocolRtpPrefix)) {
2535 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2536 }
deadbeefab9b2d12015-10-14 11:33:11 -07002537 }
deadbeefab9b2d12015-10-14 11:33:11 -07002538
Steve Antondcc3c022017-12-22 16:02:54 -08002539 // Iterate new_streams and notify the observer about new MediaStreams.
2540 for (size_t i = 0; i < new_streams->count(); ++i) {
2541 MediaStreamInterface* new_stream = new_streams->at(i);
2542 stats_->AddStream(new_stream);
2543 observer_->OnAddStream(
2544 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2545 }
deadbeefab9b2d12015-10-14 11:33:11 -07002546
Steve Antondcc3c022017-12-22 16:02:54 -08002547 UpdateEndedRemoteMediaStreams();
2548 }
deadbeefab9b2d12015-10-14 11:33:11 -07002549
Steve Anton8a006912017-12-04 15:25:56 -08002550 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002551}
2552
Steve Antondcc3c022017-12-22 16:02:54 -08002553RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2554 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002555 const SessionDescriptionInterface& new_session,
2556 const SessionDescriptionInterface* old_local_description,
2557 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002558 RTC_DCHECK(IsUnifiedPlan());
2559
Steve Anton7464fca2018-01-19 11:10:37 -08002560 const cricket::ContentGroup* bundle_group = nullptr;
2561 if (new_session.GetType() == SdpType::kOffer) {
2562 auto bundle_group_or_error =
2563 GetEarlyBundleGroup(*new_session.description());
2564 if (!bundle_group_or_error.ok()) {
2565 return bundle_group_or_error.MoveError();
2566 }
2567 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002568 }
Steve Antondcc3c022017-12-22 16:02:54 -08002569
Steve Antondcc3c022017-12-22 16:02:54 -08002570 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002571 for (size_t i = 0; i < new_contents.size(); ++i) {
2572 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002573 cricket::MediaType media_type = new_content.media_description()->type();
2574 seen_mids_.insert(new_content.name);
2575 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2576 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002577 const cricket::ContentInfo* old_local_content = nullptr;
2578 if (old_local_description &&
2579 i < old_local_description->description()->contents().size()) {
2580 old_local_content =
2581 &old_local_description->description()->contents()[i];
2582 }
2583 const cricket::ContentInfo* old_remote_content = nullptr;
2584 if (old_remote_description &&
2585 i < old_remote_description->description()->contents().size()) {
2586 old_remote_content =
2587 &old_remote_description->description()->contents()[i];
2588 }
Steve Antondcc3c022017-12-22 16:02:54 -08002589 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002590 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2591 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002592 if (!transceiver_or_error.ok()) {
2593 return transceiver_or_error.MoveError();
2594 }
2595 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002596 RTCError error =
2597 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2598 if (!error.ok()) {
2599 return error;
2600 }
2601 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002602 if (GetDataMid() && new_content.name != *GetDataMid()) {
2603 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002604 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2605 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002606 continue;
2607 }
2608 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2609 if (!error.ok()) {
2610 return error;
2611 }
Steve Antondcc3c022017-12-22 16:02:54 -08002612 } else {
2613 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2614 "Unknown section type.");
2615 }
2616 }
2617
2618 return RTCError::OK();
2619}
2620
2621RTCError PeerConnection::UpdateTransceiverChannel(
2622 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2623 transceiver,
2624 const cricket::ContentInfo& content,
2625 const cricket::ContentGroup* bundle_group) {
2626 RTC_DCHECK(IsUnifiedPlan());
2627 RTC_DCHECK(transceiver);
2628 cricket::BaseChannel* channel = transceiver->internal()->channel();
2629 if (content.rejected) {
2630 if (channel) {
2631 transceiver->internal()->SetChannel(nullptr);
2632 DestroyBaseChannel(channel);
2633 }
2634 } else {
2635 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002636 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002637 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002638 } else {
Steve Anton69470252018-02-09 11:43:08 -08002639 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002640 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002641 }
2642 if (!channel) {
2643 LOG_AND_RETURN_ERROR(
2644 RTCErrorType::INTERNAL_ERROR,
2645 "Failed to create channel for mid=" + content.name);
2646 }
2647 transceiver->internal()->SetChannel(channel);
2648 }
2649 }
2650 return RTCError::OK();
2651}
2652
Steve Antonfa2260d2017-12-28 16:38:23 -08002653RTCError PeerConnection::UpdateDataChannel(
2654 cricket::ContentSource source,
2655 const cricket::ContentInfo& content,
2656 const cricket::ContentGroup* bundle_group) {
2657 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002658 // If data channels are disabled, ignore this media section. CreateAnswer
2659 // will take care of rejecting it.
2660 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002661 }
2662 if (content.rejected) {
2663 DestroyDataChannel();
2664 } else {
2665 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002666 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002667 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2668 "Failed to create data channel.");
2669 }
2670 }
2671 if (source == cricket::CS_REMOTE) {
2672 const MediaContentDescription* data_desc = content.media_description();
2673 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2674 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2675 }
2676 }
2677 }
2678 return RTCError::OK();
2679}
2680
Steve Antondcc3c022017-12-22 16:02:54 -08002681RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2682PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002683 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002684 size_t mline_index,
2685 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002686 const ContentInfo* old_local_content,
2687 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002688 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002689 // If this is an offer then the m= section might be recycled. If the m=
2690 // section is being recycled (defined as: rejected in the current local or
2691 // remote description and not rejected in new description), dissociate the
2692 // currently associated RtpTransceiver by setting its mid property to null,
2693 // and discard the mapping between the transceiver and its m= section index.
2694 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2695 old_remote_content)) {
2696 // We want to dissociate the transceiver that has the rejected mid.
2697 const std::string& old_mid =
2698 (old_local_content && old_local_content->rejected)
2699 ? old_local_content->name
2700 : old_remote_content->name;
2701 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002702 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002703 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2704 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002705 old_transceiver->internal()->set_mid(absl::nullopt);
2706 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002707 }
2708 }
2709 const MediaContentDescription* media_desc = content.media_description();
2710 auto transceiver = GetAssociatedTransceiver(content.name);
2711 if (source == cricket::CS_LOCAL) {
2712 // Find the RtpTransceiver that corresponds to this m= section, using the
2713 // mapping between transceivers and m= section indices established when
2714 // creating the offer.
2715 if (!transceiver) {
2716 transceiver = GetTransceiverByMLineIndex(mline_index);
2717 }
2718 if (!transceiver) {
2719 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2720 "Unknown transceiver");
2721 }
2722 } else {
2723 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2724 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2725 // of the same type...
2726 if (!transceiver &&
2727 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2728 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2729 }
2730 // If no RtpTransceiver was found in the previous step, create one with a
2731 // recvonly direction.
2732 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002733 RTC_LOG(LS_INFO) << "Adding "
2734 << cricket::MediaTypeToString(media_desc->type())
2735 << " transceiver for MID=" << content.name
2736 << " at i=" << mline_index
2737 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002738 auto sender =
2739 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002740 std::string receiver_id;
2741 if (!media_desc->streams().empty()) {
2742 receiver_id = media_desc->streams()[0].id;
2743 } else {
2744 receiver_id = rtc::CreateRandomUuid();
2745 }
2746 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002747 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002748 transceiver->internal()->set_direction(
2749 RtpTransceiverDirection::kRecvOnly);
2750 }
2751 }
2752 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002753 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002754 LOG_AND_RETURN_ERROR(
2755 RTCErrorType::INVALID_PARAMETER,
2756 "Transceiver type does not match media description type.");
2757 }
2758 // Associate the found or created RtpTransceiver with the m= section by
2759 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2760 // section, and establish a mapping between the transceiver and the index of
2761 // the m= section.
2762 transceiver->internal()->set_mid(content.name);
2763 transceiver->internal()->set_mline_index(mline_index);
2764 return std::move(transceiver);
2765}
2766
2767rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2768PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2769 RTC_DCHECK(IsUnifiedPlan());
2770 for (auto transceiver : transceivers_) {
2771 if (transceiver->mid() == mid) {
2772 return transceiver;
2773 }
2774 }
2775 return nullptr;
2776}
2777
2778rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2779PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2780 RTC_DCHECK(IsUnifiedPlan());
2781 for (auto transceiver : transceivers_) {
2782 if (transceiver->internal()->mline_index() == mline_index) {
2783 return transceiver;
2784 }
2785 }
2786 return nullptr;
2787}
2788
2789rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2790PeerConnection::FindAvailableTransceiverToReceive(
2791 cricket::MediaType media_type) const {
2792 RTC_DCHECK(IsUnifiedPlan());
2793 // From JSEP section 5.10 (Applying a Remote Description):
2794 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2795 // the same type that were added to the PeerConnection by addTrack and are not
2796 // associated with any m= section and are not stopped, find the first such
2797 // RtpTransceiver.
2798 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002799 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002800 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2801 !transceiver->stopped()) {
2802 return transceiver;
2803 }
2804 }
2805 return nullptr;
2806}
2807
Steve Antoned10bd92017-12-05 10:52:59 -08002808const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2809 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2810 transceiver,
2811 const SessionDescriptionInterface* sdesc) const {
2812 RTC_DCHECK(transceiver);
2813 RTC_DCHECK(sdesc);
2814 if (IsUnifiedPlan()) {
2815 if (!transceiver->internal()->mid()) {
2816 // This transceiver is not associated with a media section yet.
2817 return nullptr;
2818 }
2819 return sdesc->description()->GetContentByName(
2820 *transceiver->internal()->mid());
2821 } else {
2822 // Plan B only allows at most one audio and one video section, so use the
2823 // first media section of that type.
2824 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002825 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002826 }
2827}
2828
deadbeef46c73892016-11-16 19:42:04 -08002829PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2830 return configuration_;
2831}
2832
deadbeef293e9262017-01-11 12:28:30 -08002833bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2834 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002835 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002836 if (IsClosed()) {
2837 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2838 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2839 }
2840
Qingsi Wanga2d60672018-04-11 16:57:45 -07002841 // According to JSEP, after setLocalDescription, changing the candidate pool
2842 // size is not allowed, and changing the set of ICE servers will not result
2843 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002844 if (local_description() && configuration.ice_candidate_pool_size !=
2845 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002846 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2847 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002848 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002849 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002850
deadbeef293e9262017-01-11 12:28:30 -08002851 // The simplest (and most future-compatible) way to tell if the config was
2852 // modified in an invalid way is to copy each property we do support
2853 // modifying, then use operator==. There are far more properties we don't
2854 // support modifying than those we do, and more could be added.
2855 RTCConfiguration modified_config = configuration_;
2856 modified_config.servers = configuration.servers;
2857 modified_config.type = configuration.type;
2858 modified_config.ice_candidate_pool_size =
2859 configuration.ice_candidate_pool_size;
2860 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002861 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002862 modified_config.ice_check_interval_strong_connectivity =
2863 configuration.ice_check_interval_strong_connectivity;
2864 modified_config.ice_check_interval_weak_connectivity =
2865 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002866 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2867 modified_config.ice_unwritable_min_checks =
2868 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002869 modified_config.stun_candidate_keepalive_interval =
2870 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002871 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002872 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002873 modified_config.active_reset_srtp_params =
2874 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002875 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002876 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002877 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2878 }
2879
Steve Anton038834f2017-07-14 15:59:59 -07002880 // Validate the modified configuration.
2881 RTCError validate_error = ValidateConfiguration(modified_config);
2882 if (!validate_error.ok()) {
2883 return SafeSetError(std::move(validate_error), error);
2884 }
2885
deadbeef293e9262017-01-11 12:28:30 -08002886 // Note that this isn't possible through chromium, since it's an unsigned
2887 // short in WebIDL.
2888 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002889 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002890 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2891 }
2892
2893 // Parse ICE servers before hopping to network thread.
2894 cricket::ServerAddresses stun_servers;
2895 std::vector<cricket::RelayServerConfig> turn_servers;
2896 RTCErrorType parse_error =
2897 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2898 if (parse_error != RTCErrorType::NONE) {
2899 return SafeSetError(parse_error, error);
2900 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002901 // Note if STUN or TURN servers were supplied.
2902 if (!stun_servers.empty()) {
2903 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2904 }
2905 if (!turn_servers.empty()) {
2906 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2907 }
deadbeef293e9262017-01-11 12:28:30 -08002908
2909 // In theory this shouldn't fail.
2910 if (!network_thread()->Invoke<bool>(
2911 RTC_FROM_HERE,
2912 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2913 stun_servers, turn_servers, modified_config.type,
2914 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002915 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002916 modified_config.turn_customizer,
2917 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002918 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002919 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2920 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002921
deadbeefd1a38b52016-12-10 13:15:33 -08002922 // As described in JSEP, calling setConfiguration with new ICE servers or
2923 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2924 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002925 if (modified_config.servers != configuration_.servers ||
2926 modified_config.type != configuration_.type ||
2927 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002928 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002929 }
skvladd1f5fda2017-02-03 16:54:05 -08002930
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002931 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002932
Zhi Huangb57e1692018-06-12 11:41:11 -07002933 if (configuration_.active_reset_srtp_params !=
2934 modified_config.active_reset_srtp_params) {
2935 transport_controller_->SetActiveResetSrtpParams(
2936 modified_config.active_reset_srtp_params);
2937 }
2938
deadbeef293e9262017-01-11 12:28:30 -08002939 configuration_ = modified_config;
2940 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002941}
2942
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002943bool PeerConnection::AddIceCandidate(
2944 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002945 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002946 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002947 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002948 return false;
2949 }
Steve Antond25da372017-11-06 14:50:29 -08002950
2951 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002952 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002953 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002954 return false;
2955 }
2956
2957 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002958 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002959 return false;
2960 }
2961
2962 bool valid = false;
2963 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2964 if (!valid) {
2965 return false;
2966 }
2967
2968 // Add this candidate to the remote session description.
2969 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002970 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002971 return false;
2972 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002973 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002974
2975 if (ready) {
2976 return UseCandidate(ice_candidate);
2977 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002978 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002979 return true;
2980 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981}
2982
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002983bool PeerConnection::RemoveIceCandidates(
2984 const std::vector<cricket::Candidate>& candidates) {
2985 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002986 if (IsClosed()) {
2987 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2988 return false;
2989 }
2990
Steve Antond25da372017-11-06 14:50:29 -08002991 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002992 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2993 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002994 return false;
2995 }
2996
2997 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002998 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002999 return false;
3000 }
3001
3002 size_t number_removed =
3003 mutable_remote_description()->RemoveCandidates(candidates);
3004 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003005 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003006 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003007 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003008 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003009 }
3010
3011 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003012 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3013 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003014 RTC_LOG(LS_ERROR)
3015 << "RemoveIceCandidates: Error when removing remote candidates: "
3016 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003017 }
3018 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003019}
3020
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003021void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003022 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003023 network_thread()->Invoke<void>(
3024 RTC_FROM_HERE,
3025 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3026 // Send information about IPv4/IPv6 status.
3027 if (uma_observer_) {
3028 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3029 uma_observer_->IncrementEnumCounter(
3030 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3031 kPeerConnectionAddressFamilyCounter_Max);
3032 } else {
3033 uma_observer_->IncrementEnumCounter(
3034 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3035 kPeerConnectionAddressFamilyCounter_Max);
3036 }
3037 }
3038}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003039
Qingsi Wanga2d60672018-04-11 16:57:45 -07003040void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3041 RTC_DCHECK(network_thread()->IsCurrent());
3042 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003043 if (transport_controller_) {
3044 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003045 }
3046
3047 for (auto transceiver : transceivers_) {
3048 auto* channel = transceiver->internal()->channel();
3049 if (channel) {
3050 channel->SetMetricsObserver(uma_observer_);
3051 }
3052 }
3053
deadbeef293e9262017-01-11 12:28:30 -08003054 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003055 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003056 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003057}
3058
Niels Möller0c4f7be2018-05-07 14:01:37 +02003059RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003060 if (!worker_thread()->IsCurrent()) {
3061 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003062 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003063 }
3064
Niels Möller0c4f7be2018-05-07 14:01:37 +02003065 const bool has_min = bitrate.min_bitrate_bps.has_value();
3066 const bool has_start = bitrate.start_bitrate_bps.has_value();
3067 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003068 if (has_min && *bitrate.min_bitrate_bps < 0) {
3069 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3070 "min_bitrate_bps <= 0");
3071 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003072 if (has_start) {
3073 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003074 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003075 "start_bitrate_bps < min_bitrate_bps");
3076 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3078 "curent_bitrate_bps < 0");
3079 }
3080 }
3081 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003082 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003083 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003084 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003085 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3086 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3087 "max_bitrate_bps < min_bitrate_bps");
3088 } else if (*bitrate.max_bitrate_bps < 0) {
3089 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3090 "max_bitrate_bps < 0");
3091 }
3092 }
3093
zstein4b979802017-06-02 14:37:37 -07003094 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003095 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003096
3097 return RTCError::OK();
3098}
3099
Alex Narest78609d52017-10-20 10:37:47 +02003100void PeerConnection::SetBitrateAllocationStrategy(
3101 std::unique_ptr<rtc::BitrateAllocationStrategy>
3102 bitrate_allocation_strategy) {
3103 rtc::Thread* worker_thread = factory_->worker_thread();
3104 if (!worker_thread->IsCurrent()) {
3105 rtc::BitrateAllocationStrategy* strategy_raw =
3106 bitrate_allocation_strategy.release();
3107 auto functor = [this, strategy_raw]() {
3108 call_->SetBitrateAllocationStrategy(
3109 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3110 };
3111 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3112 return;
3113 }
3114 RTC_DCHECK(call_.get());
3115 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3116}
3117
henrika5f6bf242017-11-01 11:06:56 +01003118void PeerConnection::SetAudioPlayout(bool playout) {
3119 if (!worker_thread()->IsCurrent()) {
3120 worker_thread()->Invoke<void>(
3121 RTC_FROM_HERE,
3122 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3123 return;
3124 }
3125 auto audio_state =
3126 factory_->channel_manager()->media_engine()->GetAudioState();
3127 audio_state->SetPlayout(playout);
3128}
3129
3130void PeerConnection::SetAudioRecording(bool recording) {
3131 if (!worker_thread()->IsCurrent()) {
3132 worker_thread()->Invoke<void>(
3133 RTC_FROM_HERE,
3134 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3135 return;
3136 }
3137 auto audio_state =
3138 factory_->channel_manager()->media_engine()->GetAudioState();
3139 audio_state->SetRecording(recording);
3140}
3141
Steve Anton8c0f7a72017-10-03 10:03:10 -07003142std::unique_ptr<rtc::SSLCertificate>
3143PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003144 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3145 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003146 return nullptr;
3147 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003148 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003149}
3150
Zhi Huang70b820f2018-01-27 14:16:15 -08003151std::unique_ptr<rtc::SSLCertChain>
3152PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003153 auto audio_transceiver = GetFirstAudioTransceiver();
3154 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003155 return nullptr;
3156 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003157 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003158 audio_transceiver->internal()->channel()->transport_name());
3159}
3160
3161rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3162PeerConnection::GetFirstAudioTransceiver() const {
3163 for (auto transceiver : transceivers_) {
3164 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3165 return transceiver;
3166 }
3167 }
3168 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003169}
3170
ivoc14d5dbe2016-07-04 07:06:55 -07003171bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3172 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003173 // TODO(eladalon): It would be better to not allow negative values into PC.
3174 const size_t max_size = (max_size_bytes < 0)
3175 ? RtcEventLog::kUnlimitedOutput
3176 : rtc::saturated_cast<size_t>(max_size_bytes);
3177 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003178 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3179 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003180}
3181
Bjorn Tereliusde939432017-11-20 17:38:14 +01003182bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3183 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003184 // TODO(eladalon): In C++14, this can be done with a lambda.
3185 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003186 bool operator()() {
3187 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3188 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003189 PeerConnection* const pc;
3190 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003191 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003192 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003193 return worker_thread()->Invoke<bool>(
3194 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003195}
3196
3197void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003198 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003199 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3200}
3201
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003202const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003203 return pending_local_description_ ? pending_local_description_.get()
3204 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003205}
3206
3207const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003208 return pending_remote_description_ ? pending_remote_description_.get()
3209 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003210}
3211
deadbeeffe4a8a42016-12-20 17:56:17 -08003212const SessionDescriptionInterface* PeerConnection::current_local_description()
3213 const {
Steve Anton75737c02017-11-06 10:37:17 -08003214 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003215}
3216
3217const SessionDescriptionInterface* PeerConnection::current_remote_description()
3218 const {
Steve Anton75737c02017-11-06 10:37:17 -08003219 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003220}
3221
3222const SessionDescriptionInterface* PeerConnection::pending_local_description()
3223 const {
Steve Anton75737c02017-11-06 10:37:17 -08003224 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003225}
3226
3227const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3228 const {
Steve Anton75737c02017-11-06 10:37:17 -08003229 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003230}
3231
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003232void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003233 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234 // Update stats here so that we have the most recent stats for tracks and
3235 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003236 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003237
Steve Anton75737c02017-11-06 10:37:17 -08003238 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003239 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003240
Steve Anton8af21862017-12-15 11:20:13 -08003241 for (auto transceiver : transceivers_) {
3242 transceiver->Stop();
3243 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003244
3245 // Ensure that all asynchronous stats requests are completed before destroying
3246 // the transport controller below.
3247 if (stats_collector_) {
3248 stats_collector_->WaitForPendingRequest();
3249 }
3250
3251 // Don't destroy BaseChannels until after stats has been cleaned up so that
3252 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003253 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003254
Qingsi Wang93a84392018-01-30 17:13:09 -08003255 // The event log is used in the transport controller, which must be outlived
3256 // by the former. CreateOffer by the peer connection is implemented
3257 // asynchronously and if the peer connection is closed without resetting the
3258 // WebRTC session description factory, the session description factory would
3259 // call the transport controller.
3260 webrtc_session_desc_factory_.reset();
3261 transport_controller_.reset();
3262
deadbeef42a42632017-03-10 15:18:00 -08003263 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003264 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3265 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003266
Steve Anton978b8762017-09-29 12:15:02 -07003267 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003268 call_.reset();
3269 // The event log must outlive call (and any other object that uses it).
3270 event_log_.reset();
3271 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003272 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003273}
3274
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003275void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3278 SetSessionDescriptionMsg* param =
3279 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3280 param->observer->OnSuccess();
3281 delete param;
3282 break;
3283 }
3284 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3285 SetSessionDescriptionMsg* param =
3286 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003287 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003288 delete param;
3289 break;
3290 }
deadbeefab9b2d12015-10-14 11:33:11 -07003291 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3292 CreateSessionDescriptionMsg* param =
3293 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003294 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003295 delete param;
3296 break;
3297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003298 case MSG_GETSTATS: {
3299 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003300 StatsReports reports;
3301 stats_->GetStats(param->track, &reports);
3302 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303 delete param;
3304 break;
3305 }
deadbeefbd292462015-12-14 18:15:29 -08003306 case MSG_FREE_DATACHANNELS: {
3307 sctp_data_channels_to_free_.clear();
3308 break;
3309 }
Harald Alvestrand19793842018-06-25 12:03:50 +02003310 case MSG_REPORT_USAGE_PATTERN: {
3311 ReportUsagePattern();
3312 break;
3313 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003314 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003315 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003316 break;
3317 }
3318}
3319
Steve Antonafb0bb72018-02-20 11:35:37 -08003320cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3321 RTC_DCHECK(!IsUnifiedPlan());
3322 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3323 GetAudioTransceiver()->internal()->channel());
3324 if (voice_channel) {
3325 return voice_channel->media_channel();
3326 } else {
3327 return nullptr;
3328 }
3329}
3330
3331cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3332 RTC_DCHECK(!IsUnifiedPlan());
3333 auto* video_channel = static_cast<cricket::VideoChannel*>(
3334 GetVideoTransceiver()->internal()->channel());
3335 if (video_channel) {
3336 return video_channel->media_channel();
3337 } else {
3338 return nullptr;
3339 }
3340}
3341
Steve Anton4171afb2017-11-20 10:20:22 -08003342void PeerConnection::CreateAudioReceiver(
3343 MediaStreamInterface* stream,
3344 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003345 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3346 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003347 auto* audio_receiver = new AudioRtpReceiver(
3348 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003349 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003350 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3351 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3352 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003353 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003354 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003355 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003356}
3357
Steve Anton4171afb2017-11-20 10:20:22 -08003358void PeerConnection::CreateVideoReceiver(
3359 MediaStreamInterface* stream,
3360 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003361 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3362 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003363 auto* video_receiver = new VideoRtpReceiver(
3364 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003365 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003366 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3367 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3368 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003369 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003370 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003371 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003372}
3373
deadbeef70ab1a12015-09-28 16:53:55 -07003374// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3375// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003376rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003377 const RtpSenderInfo& remote_sender_info) {
3378 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3379 if (!receiver) {
3380 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3381 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003382 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003383 }
Steve Anton4171afb2017-11-20 10:20:22 -08003384 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3385 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3386 } else {
3387 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3388 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003389 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390}
3391
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003392void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3393 MediaStreamInterface* stream) {
3394 RTC_DCHECK(!IsClosed());
3395 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003396 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003397 // We already have a sender for this track, so just change the stream_id
3398 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003399 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003400 return;
3401 }
3402
3403 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003404 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003405 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003406 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003407 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003408 // If the sender has already been configured in SDP, we call SetSsrc,
3409 // which will connect the sender to the underlying transport. This can
3410 // occur if a local session description that contains the ID of the sender
3411 // is set before AddStream is called. It can also occur if the local
3412 // session description is not changed and RemoveStream is called, and
3413 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003414 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003415 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003416 if (sender_info) {
3417 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003418 }
3419}
3420
3421// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3422// indefinitely, when we have unified plan SDP.
3423void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3424 MediaStreamInterface* stream) {
3425 RTC_DCHECK(!IsClosed());
3426 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003427 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003428 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3429 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003430 return;
3431 }
Steve Anton4171afb2017-11-20 10:20:22 -08003432 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003433}
3434
3435void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3436 MediaStreamInterface* stream) {
3437 RTC_DCHECK(!IsClosed());
3438 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003439 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003440 // We already have a sender for this track, so just change the stream_id
3441 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003442 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003443 return;
3444 }
3445
3446 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003447 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003448 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003449 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003450 GetVideoTransceiver()->internal()->AddSender(new_sender);
3451 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003452 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003453 if (sender_info) {
3454 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003455 }
3456}
3457
3458void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3459 MediaStreamInterface* stream) {
3460 RTC_DCHECK(!IsClosed());
3461 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003462 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003463 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3464 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003465 return;
3466 }
Steve Anton4171afb2017-11-20 10:20:22 -08003467 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003468}
3469
Steve Antonba818672017-11-06 10:21:57 -08003470void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003471 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003472 if (ice_connection_state_ == new_state) {
3473 return;
3474 }
3475
deadbeefcbecd352015-09-23 11:50:27 -07003476 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003477 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003478 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003479 return;
3480 }
Steve Antonba818672017-11-06 10:21:57 -08003481
Mirko Bonadei675513b2017-11-09 11:09:25 +01003482 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3483 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003484 RTC_DCHECK(ice_connection_state_ !=
3485 PeerConnectionInterface::kIceConnectionClosed);
3486
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003487 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003488 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003489}
3490
3491void PeerConnection::OnIceGatheringChange(
3492 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003493 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003494 if (IsClosed()) {
3495 return;
3496 }
3497 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003498 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003499}
3500
jbauch81bf7b02017-03-25 08:31:12 -07003501void PeerConnection::OnIceCandidate(
3502 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003503 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003504 if (IsClosed()) {
3505 return;
3506 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003507 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003508 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003509}
3510
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003511void PeerConnection::OnIceCandidatesRemoved(
3512 const std::vector<cricket::Candidate>& candidates) {
3513 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003514 if (IsClosed()) {
3515 return;
3516 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003517 observer_->OnIceCandidatesRemoved(candidates);
3518}
3519
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520void PeerConnection::ChangeSignalingState(
3521 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003522 RTC_DCHECK(signaling_thread()->IsCurrent());
3523 if (signaling_state_ == signaling_state) {
3524 return;
3525 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003526 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3527 << GetSignalingStateString(signaling_state_)
3528 << " New state: "
3529 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003530 signaling_state_ = signaling_state;
3531 if (signaling_state == kClosed) {
3532 ice_connection_state_ = kIceConnectionClosed;
3533 observer_->OnIceConnectionChange(ice_connection_state_);
3534 if (ice_gathering_state_ != kIceGatheringComplete) {
3535 ice_gathering_state_ = kIceGatheringComplete;
3536 observer_->OnIceGatheringChange(ice_gathering_state_);
3537 }
3538 }
3539 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003540}
3541
deadbeefeb459812015-12-15 19:24:43 -08003542void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3543 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003544 if (IsClosed()) {
3545 return;
3546 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003547 AddAudioTrack(track, stream);
3548 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003549}
3550
deadbeefeb459812015-12-15 19:24:43 -08003551void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3552 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003553 if (IsClosed()) {
3554 return;
3555 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003556 RemoveAudioTrack(track, stream);
3557 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003558}
3559
3560void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3561 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003562 if (IsClosed()) {
3563 return;
3564 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003565 AddVideoTrack(track, stream);
3566 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003567}
3568
3569void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3570 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003571 if (IsClosed()) {
3572 return;
3573 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003574 RemoveVideoTrack(track, stream);
3575 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003576}
3577
Henrik Boström31638672017-11-23 17:48:32 +01003578void PeerConnection::PostSetSessionDescriptionSuccess(
3579 SetSessionDescriptionObserver* observer) {
3580 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3581 signaling_thread()->Post(RTC_FROM_HERE, this,
3582 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3583}
3584
deadbeefab9b2d12015-10-14 11:33:11 -07003585void PeerConnection::PostSetSessionDescriptionFailure(
3586 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003587 RTCError&& error) {
3588 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003589 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003590 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003591 signaling_thread()->Post(RTC_FROM_HERE, this,
3592 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003593}
3594
3595void PeerConnection::PostCreateSessionDescriptionFailure(
3596 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003597 RTCError error) {
3598 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003599 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003600 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003601 signaling_thread()->Post(RTC_FROM_HERE, this,
3602 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003603}
3604
zhihuang1c378ed2017-08-17 14:10:50 -07003605void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003606 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003607 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003608 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003609
Steve Antondcc3c022017-12-22 16:02:54 -08003610 if (IsUnifiedPlan()) {
3611 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3612 } else {
3613 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3614 }
3615
Steve Antonfa2260d2017-12-28 16:38:23 -08003616 // Intentionally unset the data channel type for RTP data channel with the
3617 // second condition. Otherwise the RTP data channels would be successfully
3618 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3619 // when building with chromium. We want to leave RTP data channels broken, so
3620 // people won't try to use them.
3621 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3622 session_options->data_channel_type = data_channel_type();
3623 }
3624
Steve Antondcc3c022017-12-22 16:02:54 -08003625 // Apply ICE restart flag and renomination flag.
3626 for (auto& options : session_options->media_description_options) {
3627 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3628 options.transport_options.enable_ice_renomination =
3629 configuration_.enable_ice_renomination;
3630 }
3631
3632 session_options->rtcp_cname = rtcp_cname_;
3633 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003634 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003635}
3636
3637void PeerConnection::GetOptionsForPlanBOffer(
3638 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3639 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003640 // Figure out transceiver directional preferences.
3641 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3642 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3643
3644 // By default, generate sendrecv/recvonly m= sections.
3645 bool recv_audio = true;
3646 bool recv_video = true;
3647
3648 // By default, only offer a new m= section if we have media to send with it.
3649 bool offer_new_audio_description = send_audio;
3650 bool offer_new_video_description = send_video;
3651 bool offer_new_data_description = HasDataChannels();
3652
3653 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003654 if (offer_answer_options.offer_to_receive_audio !=
3655 RTCOfferAnswerOptions::kUndefined) {
3656 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003657 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003658 offer_new_audio_description ||
3659 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003660 }
Steve Antondcc3c022017-12-22 16:02:54 -08003661 if (offer_answer_options.offer_to_receive_video !=
3662 RTCOfferAnswerOptions::kUndefined) {
3663 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003664 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003665 offer_new_video_description ||
3666 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003667 }
3668
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003669 absl::optional<size_t> audio_index;
3670 absl::optional<size_t> video_index;
3671 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003672 // If a current description exists, generate m= sections in the same order,
3673 // using the first audio/video/data section that appears and rejecting
3674 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003675 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003676 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003677 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003678 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3679 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3680 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003681 }
3682
zhihuang1c378ed2017-08-17 14:10:50 -07003683 // Add audio/video/data m= sections to the end if needed.
3684 if (!audio_index && offer_new_audio_description) {
3685 session_options->media_description_options.push_back(
3686 cricket::MediaDescriptionOptions(
3687 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003688 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3689 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003690 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003691 }
zhihuang1c378ed2017-08-17 14:10:50 -07003692 if (!video_index && offer_new_video_description) {
3693 session_options->media_description_options.push_back(
3694 cricket::MediaDescriptionOptions(
3695 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003696 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3697 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003698 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003699 }
zhihuang1c378ed2017-08-17 14:10:50 -07003700 if (!data_index && offer_new_data_description) {
3701 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003702 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003703 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003704 }
3705
3706 cricket::MediaDescriptionOptions* audio_media_description_options =
3707 !audio_index ? nullptr
3708 : &session_options->media_description_options[*audio_index];
3709 cricket::MediaDescriptionOptions* video_media_description_options =
3710 !video_index ? nullptr
3711 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003712
Steve Anton4171afb2017-11-20 10:20:22 -08003713 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003714 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003715}
3716
3717// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3718// and return a reference to it.
3719// Generated MIDs should be no more than 3 bytes long to take up less space in
3720// the RTP packet.
3721static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3722 RTC_DCHECK(used_mids);
3723 // We're boring: just generate MIDs 0, 1, 2, ...
3724 size_t i = 0;
3725 std::set<std::string>::iterator it;
3726 bool inserted;
3727 do {
3728 std::string mid = rtc::ToString(i++);
3729 auto insert_result = used_mids->insert(mid);
3730 it = insert_result.first;
3731 inserted = insert_result.second;
3732 } while (!inserted);
3733 return *it;
3734}
3735
3736static cricket::MediaDescriptionOptions
3737GetMediaDescriptionOptionsForTransceiver(
3738 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3739 transceiver,
3740 const std::string& mid) {
3741 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003742 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003743 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003744 // This behavior is specified in JSEP. The gist is that:
3745 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3746 // sendrecv.
3747 // 2. If the MSID is included, then it must be included in any subsequent
3748 // offer/answer exactly the same until the RtpTransceiver is stopped.
3749 if (!transceiver->stopped() &&
3750 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3751 transceiver->internal()->has_ever_been_used_to_send())) {
3752 cricket::SenderOptions sender_options;
3753 sender_options.track_id = transceiver->sender()->id();
3754 sender_options.stream_ids = transceiver->sender()->stream_ids();
3755 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3756 // set in the RTP parameters when the transceiver was added.
3757 sender_options.num_sim_layers = 1;
3758 media_description_options.sender_options.push_back(sender_options);
3759 }
Steve Antondcc3c022017-12-22 16:02:54 -08003760 return media_description_options;
3761}
3762
3763void PeerConnection::GetOptionsForUnifiedPlanOffer(
3764 const RTCOfferAnswerOptions& offer_answer_options,
3765 cricket::MediaSessionOptions* session_options) {
3766 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3767 // Offers) and 5.2.2 (Subsequent Offers).
3768 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3769 const ContentInfos& local_contents =
3770 (local_description() ? local_description()->description()->contents()
3771 : ContentInfos());
3772 const ContentInfos& remote_contents =
3773 (remote_description() ? remote_description()->description()->contents()
3774 : ContentInfos());
3775 // The mline indices that can be recycled. New transceivers should reuse these
3776 // slots first.
3777 std::queue<size_t> recycleable_mline_indices;
3778 // Track the MIDs used in previous offer/answer exchanges and the current
3779 // offer so that new, unique MIDs are generated.
3780 std::set<std::string> used_mids = seen_mids_;
3781 // First, go through each media section that exists in either the local or
3782 // remote description and generate a media section in this offer for the
3783 // associated transceiver. If a media section can be recycled, generate a
3784 // default, rejected media section here that can be later overwritten.
3785 for (size_t i = 0;
3786 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3787 // Either |local_content| or |remote_content| is non-null.
3788 const ContentInfo* local_content =
3789 (i < local_contents.size() ? &local_contents[i] : nullptr);
3790 const ContentInfo* remote_content =
3791 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3792 bool had_been_rejected = (local_content && local_content->rejected) ||
3793 (remote_content && remote_content->rejected);
3794 const std::string& mid =
3795 (local_content ? local_content->name : remote_content->name);
3796 cricket::MediaType media_type =
3797 (local_content ? local_content->media_description()->type()
3798 : remote_content->media_description()->type());
3799 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3800 media_type == cricket::MEDIA_TYPE_VIDEO) {
3801 auto transceiver = GetAssociatedTransceiver(mid);
3802 RTC_CHECK(transceiver);
3803 // A media section is considered eligible for recycling if it is marked as
3804 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003805 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003806 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003807 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3808 RtpTransceiverDirection::kInactive,
3809 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003810 recycleable_mline_indices.push(i);
3811 } else {
3812 session_options->media_description_options.push_back(
3813 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3814 // CreateOffer shouldn't really cause any state changes in
3815 // PeerConnection, but we need a way to match new transceivers to new
3816 // media sections in SetLocalDescription and JSEP specifies this is done
3817 // by recording the index of the media section generated for the
3818 // transceiver in the offer.
3819 transceiver->internal()->set_mline_index(i);
3820 }
3821 } else {
3822 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003823 RTC_CHECK(GetDataMid());
3824 if (had_been_rejected || mid != *GetDataMid()) {
3825 session_options->media_description_options.push_back(
3826 GetMediaDescriptionOptionsForRejectedData(mid));
3827 } else {
3828 session_options->media_description_options.push_back(
3829 GetMediaDescriptionOptionsForActiveData(mid));
3830 }
Steve Antondcc3c022017-12-22 16:02:54 -08003831 }
3832 }
3833 // Next, look for transceivers that are newly added (that is, are not stopped
3834 // and not associated). Reuse media sections marked as recyclable first,
3835 // otherwise append to the end of the offer. New media sections should be
3836 // added in the order they were added to the PeerConnection.
3837 for (auto transceiver : transceivers_) {
3838 if (transceiver->mid() || transceiver->stopped()) {
3839 continue;
3840 }
3841 size_t mline_index;
3842 if (!recycleable_mline_indices.empty()) {
3843 mline_index = recycleable_mline_indices.front();
3844 recycleable_mline_indices.pop();
3845 session_options->media_description_options[mline_index] =
3846 GetMediaDescriptionOptionsForTransceiver(transceiver,
3847 AllocateMid(&used_mids));
3848 } else {
3849 mline_index = session_options->media_description_options.size();
3850 session_options->media_description_options.push_back(
3851 GetMediaDescriptionOptionsForTransceiver(transceiver,
3852 AllocateMid(&used_mids)));
3853 }
3854 // See comment above for why CreateOffer changes the transceiver's state.
3855 transceiver->internal()->set_mline_index(mline_index);
3856 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003857 // Lastly, add a m-section if we have local data channels and an m section
3858 // does not already exist.
3859 if (!GetDataMid() && HasDataChannels()) {
3860 session_options->media_description_options.push_back(
3861 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3862 }
Steve Antondcc3c022017-12-22 16:02:54 -08003863}
3864
3865void PeerConnection::GetOptionsForAnswer(
3866 const RTCOfferAnswerOptions& offer_answer_options,
3867 cricket::MediaSessionOptions* session_options) {
3868 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3869
3870 if (IsUnifiedPlan()) {
3871 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3872 } else {
3873 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3874 }
3875
Steve Antonfa2260d2017-12-28 16:38:23 -08003876 // Intentionally unset the data channel type for RTP data channel. Otherwise
3877 // the RTP data channels would be successfully negotiated by default and the
3878 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3879 // We want to leave RTP data channels broken, so people won't try to use them.
3880 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3881 session_options->data_channel_type = data_channel_type();
3882 }
3883
Steve Antondcc3c022017-12-22 16:02:54 -08003884 // Apply ICE renomination flag.
3885 for (auto& options : session_options->media_description_options) {
3886 options.transport_options.enable_ice_renomination =
3887 configuration_.enable_ice_renomination;
3888 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003889
3890 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003891 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003892 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003893}
3894
Steve Antondcc3c022017-12-22 16:02:54 -08003895void PeerConnection::GetOptionsForPlanBAnswer(
3896 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003897 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003898 // Figure out transceiver directional preferences.
3899 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3900 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3901
3902 // By default, generate sendrecv/recvonly m= sections. The direction is also
3903 // restricted by the direction in the offer.
3904 bool recv_audio = true;
3905 bool recv_video = true;
3906
3907 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003908 if (offer_answer_options.offer_to_receive_audio !=
3909 RTCOfferAnswerOptions::kUndefined) {
3910 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003911 }
Steve Antondcc3c022017-12-22 16:02:54 -08003912 if (offer_answer_options.offer_to_receive_video !=
3913 RTCOfferAnswerOptions::kUndefined) {
3914 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003915 }
3916
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003917 absl::optional<size_t> audio_index;
3918 absl::optional<size_t> video_index;
3919 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003920
3921 // Generate m= sections that match those in the offer.
3922 // Note that mediasession.cc will handle intersection our preferred
3923 // direction with the offered direction.
3924 GenerateMediaDescriptionOptions(
3925 remote_description(),
3926 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3927 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3928 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003929
3930 cricket::MediaDescriptionOptions* audio_media_description_options =
3931 !audio_index ? nullptr
3932 : &session_options->media_description_options[*audio_index];
3933 cricket::MediaDescriptionOptions* video_media_description_options =
3934 !video_index ? nullptr
3935 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003936
Steve Anton4171afb2017-11-20 10:20:22 -08003937 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003938 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003939}
zhihuangaf388472016-11-02 16:49:48 -07003940
Steve Antondcc3c022017-12-22 16:02:54 -08003941void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3942 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3943 cricket::MediaSessionOptions* session_options) {
3944 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3945 // Answers) and 5.3.2 (Subsequent Answers).
3946 RTC_DCHECK(remote_description());
3947 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3948 for (const ContentInfo& content :
3949 remote_description()->description()->contents()) {
3950 cricket::MediaType media_type = content.media_description()->type();
3951 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3952 media_type == cricket::MEDIA_TYPE_VIDEO) {
3953 auto transceiver = GetAssociatedTransceiver(content.name);
3954 RTC_CHECK(transceiver);
3955 session_options->media_description_options.push_back(
3956 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3957 } else {
3958 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003959 // Reject all data sections if data channels are disabled.
3960 // Reject a data section if it has already been rejected.
3961 // Reject all data sections except for the first one.
3962 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3963 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003964 session_options->media_description_options.push_back(
3965 GetMediaDescriptionOptionsForRejectedData(content.name));
3966 } else {
3967 session_options->media_description_options.push_back(
3968 GetMediaDescriptionOptionsForActiveData(content.name));
3969 }
Steve Antondcc3c022017-12-22 16:02:54 -08003970 }
3971 }
htaa2a49d92016-03-04 02:51:39 -08003972}
3973
zhihuang1c378ed2017-08-17 14:10:50 -07003974void PeerConnection::GenerateMediaDescriptionOptions(
3975 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003976 RtpTransceiverDirection audio_direction,
3977 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003978 absl::optional<size_t>* audio_index,
3979 absl::optional<size_t>* video_index,
3980 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003981 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003982 for (const cricket::ContentInfo& content :
3983 session_desc->description()->contents()) {
3984 if (IsAudioContent(&content)) {
3985 // If we already have an audio m= section, reject this extra one.
3986 if (*audio_index) {
3987 session_options->media_description_options.push_back(
3988 cricket::MediaDescriptionOptions(
3989 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003990 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003991 } else {
3992 session_options->media_description_options.push_back(
3993 cricket::MediaDescriptionOptions(
3994 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003995 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003996 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003997 }
3998 } else if (IsVideoContent(&content)) {
3999 // If we already have an video m= section, reject this extra one.
4000 if (*video_index) {
4001 session_options->media_description_options.push_back(
4002 cricket::MediaDescriptionOptions(
4003 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004004 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004005 } else {
4006 session_options->media_description_options.push_back(
4007 cricket::MediaDescriptionOptions(
4008 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004009 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004010 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004011 }
4012 } else {
4013 RTC_DCHECK(IsDataContent(&content));
4014 // If we already have an data m= section, reject this extra one.
4015 if (*data_index) {
4016 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004017 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004018 } else {
4019 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004020 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004021 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004022 }
4023 }
htaa2a49d92016-03-04 02:51:39 -08004024 }
deadbeefab9b2d12015-10-14 11:33:11 -07004025}
4026
Steve Antonfa2260d2017-12-28 16:38:23 -08004027cricket::MediaDescriptionOptions
4028PeerConnection::GetMediaDescriptionOptionsForActiveData(
4029 const std::string& mid) const {
4030 // Direction for data sections is meaningless, but legacy endpoints might
4031 // expect sendrecv.
4032 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4033 RtpTransceiverDirection::kSendRecv,
4034 /*stopped=*/false);
4035 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4036 return options;
4037}
4038
4039cricket::MediaDescriptionOptions
4040PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4041 const std::string& mid) const {
4042 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4043 RtpTransceiverDirection::kInactive,
4044 /*stopped=*/true);
4045 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4046 return options;
4047}
4048
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004049absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004050 switch (data_channel_type_) {
4051 case cricket::DCT_RTP:
4052 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004053 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004054 }
4055 return rtp_data_channel_->content_name();
4056 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004057 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004058 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004059 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004060 }
4061}
4062
Steve Anton4171afb2017-11-20 10:20:22 -08004063void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4064 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4065 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004066 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004067}
4068
Steve Anton4171afb2017-11-20 10:20:22 -08004069void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004070 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004071 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004072 cricket::MediaType media_type,
4073 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004074 RTC_DCHECK(!IsUnifiedPlan());
4075
Steve Anton4171afb2017-11-20 10:20:22 -08004076 std::vector<RtpSenderInfo>* current_senders =
4077 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004078
Steve Anton4171afb2017-11-20 10:20:22 -08004079 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004080 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004081 for (auto sender_it = current_senders->begin();
4082 sender_it != current_senders->end();
4083 /* incremented manually */) {
4084 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004085 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004086 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004087 std::string params_stream_id;
4088 if (params) {
4089 params_stream_id =
4090 (!params->first_stream_id().empty() ? params->first_stream_id()
4091 : kDefaultStreamId);
4092 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004093 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004094 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004095 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004096 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004097 sender_exists) {
4098 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004099 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004100 OnRemoteSenderRemoved(info, media_type);
4101 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004102 }
4103 }
4104
Steve Anton4171afb2017-11-20 10:20:22 -08004105 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004106 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004107 if (!params.has_ssrcs()) {
4108 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4109 // sender, this means it is coming from a Unified Plan endpoint,so we just
4110 // create a default.
4111 default_sender_needed = true;
4112 break;
4113 }
4114
Seth Hampson845e8782018-03-02 11:34:10 -08004115 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004116 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004117 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4118 // not supported in Plan B, we just take the first here and create the
4119 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004120 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004121 (!params.first_stream_id().empty() ? params.first_stream_id()
4122 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004123 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004124 uint32_t ssrc = params.first_ssrc();
4125
4126 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004127 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004128 if (!stream) {
4129 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004130 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004131 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004132 remote_streams_->AddStream(stream);
4133 new_streams->AddStream(stream);
4134 }
4135
Steve Anton4171afb2017-11-20 10:20:22 -08004136 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004137 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004138 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004139 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004140 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004141 }
4142 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004143
Steve Anton4171afb2017-11-20 10:20:22 -08004144 // Add default sender if necessary.
4145 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004146 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004147 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004148 if (!default_stream) {
4149 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004150 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004151 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004152 remote_streams_->AddStream(default_stream);
4153 new_streams->AddStream(default_stream);
4154 }
Steve Anton4171afb2017-11-20 10:20:22 -08004155 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4156 ? kDefaultAudioSenderId
4157 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004158 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004159 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004160 if (!default_sender_info) {
4161 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004162 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004163 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004164 }
4165 }
deadbeefab9b2d12015-10-14 11:33:11 -07004166}
4167
Steve Anton4171afb2017-11-20 10:20:22 -08004168void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4169 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004170 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4171 << " receiver for track_id=" << sender_info.sender_id
4172 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004173
Steve Anton3d954a62018-04-02 11:27:23 -07004174 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004175 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004176 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004177 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004178 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004179 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004180 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004181 }
4182}
4183
Steve Anton4171afb2017-11-20 10:20:22 -08004184void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4185 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004186 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4187 << " receiver for track_id=" << sender_info.sender_id
4188 << " and stream_id=" << sender_info.stream_id;
4189
Seth Hampson845e8782018-03-02 11:34:10 -08004190 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004191
Henrik Boström933d8b02017-10-10 10:05:16 -07004192 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004193 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004194 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4195 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004196 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004197 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004198 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004199 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004200 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004201 }
4202 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004203 // Stopping or destroying a VideoRtpReceiver will end the
4204 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004205 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004206 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004207 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004208 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004209 // There's no guarantee the track is still available, e.g. the track may
4210 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004211 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004212 }
4213 } else {
nisseede5da42017-01-12 05:15:36 -08004214 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004215 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004216 if (receiver) {
4217 observer_->OnRemoveTrack(receiver);
4218 }
deadbeefab9b2d12015-10-14 11:33:11 -07004219}
4220
4221void PeerConnection::UpdateEndedRemoteMediaStreams() {
4222 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4223 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4224 MediaStreamInterface* stream = remote_streams_->at(i);
4225 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4226 streams_to_remove.push_back(stream);
4227 }
4228 }
4229
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004230 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004231 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004232 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004233 }
4234}
4235
Steve Anton4171afb2017-11-20 10:20:22 -08004236void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004237 const std::vector<cricket::StreamParams>& streams,
4238 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004239 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004240
Seth Hampson845e8782018-03-02 11:34:10 -08004241 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004242 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004243 for (auto sender_it = current_senders->begin();
4244 sender_it != current_senders->end();
4245 /* incremented manually */) {
4246 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004247 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004248 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4249 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004250 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004251 OnLocalSenderRemoved(info, media_type);
4252 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004253 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004254 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004255 }
4256 }
4257
Steve Anton4171afb2017-11-20 10:20:22 -08004258 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004259 for (const cricket::StreamParams& params : streams) {
4260 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004261 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004262 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004263 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004264 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004265 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004266 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004267 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004268 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004269 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004270 }
4271 }
4272}
4273
Steve Anton4171afb2017-11-20 10:20:22 -08004274void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4275 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004276 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004277 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004278 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004279 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4280 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004281 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004282 return;
4283 }
4284
deadbeeffac06552015-11-25 11:26:01 -08004285 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004286 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004287 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004288 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004289 }
deadbeeffac06552015-11-25 11:26:01 -08004290
Seth Hampson5b4f0752018-04-02 16:31:36 -07004291 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004292 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004293}
4294
Steve Anton4171afb2017-11-20 10:20:22 -08004295void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4296 cricket::MediaType media_type) {
4297 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004298 if (!sender) {
4299 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004300 // SessionDescriptions has been renegotiated.
4301 return;
4302 }
deadbeeffac06552015-11-25 11:26:01 -08004303
4304 // A sender has been removed from the SessionDescription but it's still
4305 // associated with the PeerConnection. This only occurs if the SDP doesn't
4306 // match with the calls to CreateSender, AddStream and RemoveStream.
4307 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004308 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004309 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004310 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004311 }
deadbeeffac06552015-11-25 11:26:01 -08004312
Steve Anton4171afb2017-11-20 10:20:22 -08004313 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004314}
4315
4316void PeerConnection::UpdateLocalRtpDataChannels(
4317 const cricket::StreamParamsVec& streams) {
4318 std::vector<std::string> existing_channels;
4319
4320 // Find new and active data channels.
4321 for (const cricket::StreamParams& params : streams) {
4322 // |it->sync_label| is actually the data channel label. The reason is that
4323 // we use the same naming of data channels as we do for
4324 // MediaStreams and Tracks.
4325 // For MediaStreams, the sync_label is the MediaStream label and the
4326 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004327 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004328 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004329 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004330 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004331 continue;
4332 }
4333 // Set the SSRC the data channel should use for sending.
4334 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4335 existing_channels.push_back(data_channel_it->first);
4336 }
4337
4338 UpdateClosingRtpDataChannels(existing_channels, true);
4339}
4340
4341void PeerConnection::UpdateRemoteRtpDataChannels(
4342 const cricket::StreamParamsVec& streams) {
4343 std::vector<std::string> existing_channels;
4344
4345 // Find new and active data channels.
4346 for (const cricket::StreamParams& params : streams) {
4347 // The data channel label is either the mslabel or the SSRC if the mslabel
4348 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004349 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004350 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004351 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004352 auto data_channel_it = rtp_data_channels_.find(label);
4353 if (data_channel_it == rtp_data_channels_.end()) {
4354 // This is a new data channel.
4355 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4356 } else {
4357 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4358 }
4359 existing_channels.push_back(label);
4360 }
4361
4362 UpdateClosingRtpDataChannels(existing_channels, false);
4363}
4364
4365void PeerConnection::UpdateClosingRtpDataChannels(
4366 const std::vector<std::string>& active_channels,
4367 bool is_local_update) {
4368 auto it = rtp_data_channels_.begin();
4369 while (it != rtp_data_channels_.end()) {
4370 DataChannel* data_channel = it->second;
4371 if (std::find(active_channels.begin(), active_channels.end(),
4372 data_channel->label()) != active_channels.end()) {
4373 ++it;
4374 continue;
4375 }
4376
4377 if (is_local_update) {
4378 data_channel->SetSendSsrc(0);
4379 } else {
4380 data_channel->RemotePeerRequestClose();
4381 }
4382
4383 if (data_channel->state() == DataChannel::kClosed) {
4384 rtp_data_channels_.erase(it);
4385 it = rtp_data_channels_.begin();
4386 } else {
4387 ++it;
4388 }
4389 }
4390}
4391
4392void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4393 uint32_t remote_ssrc) {
4394 rtc::scoped_refptr<DataChannel> channel(
4395 InternalCreateDataChannel(label, nullptr));
4396 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004397 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004398 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004399 return;
4400 }
4401 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004402 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4403 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004404 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004405}
4406
4407rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4408 const std::string& label,
4409 const InternalDataChannelInit* config) {
4410 if (IsClosed()) {
4411 return nullptr;
4412 }
Steve Anton75737c02017-11-06 10:37:17 -08004413 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004414 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004415 << "InternalCreateDataChannel: Data is not supported in this call.";
4416 return nullptr;
4417 }
4418 InternalDataChannelInit new_config =
4419 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004420 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004421 if (new_config.id < 0) {
4422 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004423 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004424 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004425 RTC_LOG(LS_ERROR)
4426 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004427 return nullptr;
4428 }
4429 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004430 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004431 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004432 return nullptr;
4433 }
4434 }
4435
Steve Anton75737c02017-11-06 10:37:17 -08004436 rtc::scoped_refptr<DataChannel> channel(
4437 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004438 if (!channel) {
4439 sid_allocator_.ReleaseSid(new_config.id);
4440 return nullptr;
4441 }
4442
4443 if (channel->data_channel_type() == cricket::DCT_RTP) {
4444 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004445 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4446 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004447 return nullptr;
4448 }
4449 rtp_data_channels_[channel->label()] = channel;
4450 } else {
4451 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4452 sctp_data_channels_.push_back(channel);
4453 channel->SignalClosed.connect(this,
4454 &PeerConnection::OnSctpDataChannelClosed);
4455 }
4456
Steve Anton2d8609c2018-01-23 16:38:46 -08004457 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004458 return channel;
4459}
4460
4461bool PeerConnection::HasDataChannels() const {
4462 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4463}
4464
4465void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4466 for (const auto& channel : sctp_data_channels_) {
4467 if (channel->id() < 0) {
4468 int sid;
4469 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004470 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004471 continue;
4472 }
4473 channel->SetSctpSid(sid);
4474 }
4475 }
4476}
4477
4478void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004479 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004480 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4481 ++it) {
4482 if (it->get() == channel) {
4483 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004484 // After the closing procedure is done, it's safe to use this ID for
4485 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004486 sid_allocator_.ReleaseSid(channel->id());
4487 }
deadbeefbd292462015-12-14 18:15:29 -08004488 // Since this method is triggered by a signal from the DataChannel,
4489 // we can't free it directly here; we need to free it asynchronously.
4490 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004491 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004492 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4493 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004494 return;
4495 }
4496 }
4497}
4498
deadbeefab9b2d12015-10-14 11:33:11 -07004499void PeerConnection::OnDataChannelDestroyed() {
4500 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4501 // DataChannel may callback to us and try to modify the list.
4502 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4503 temp_rtp_dcs.swap(rtp_data_channels_);
4504 for (const auto& kv : temp_rtp_dcs) {
4505 kv.second->OnTransportChannelDestroyed();
4506 }
4507
4508 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4509 temp_sctp_dcs.swap(sctp_data_channels_);
4510 for (const auto& channel : temp_sctp_dcs) {
4511 channel->OnTransportChannelDestroyed();
4512 }
4513}
4514
4515void PeerConnection::OnDataChannelOpenMessage(
4516 const std::string& label,
4517 const InternalDataChannelInit& config) {
4518 rtc::scoped_refptr<DataChannel> channel(
4519 InternalCreateDataChannel(label, &config));
4520 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004521 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004522 return;
4523 }
4524
deadbeefa601f5c2016-06-06 14:27:39 -07004525 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4526 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004527 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004528}
4529
Steve Anton4171afb2017-11-20 10:20:22 -08004530rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4531PeerConnection::GetAudioTransceiver() const {
4532 // This method only works with Plan B SDP, where there is a single
4533 // audio/video transceiver.
4534 RTC_DCHECK(!IsUnifiedPlan());
4535 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004536 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004537 return transceiver;
4538 }
4539 }
4540 RTC_NOTREACHED();
4541 return nullptr;
4542}
4543
4544rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4545PeerConnection::GetVideoTransceiver() const {
4546 // This method only works with Plan B SDP, where there is a single
4547 // audio/video transceiver.
4548 RTC_DCHECK(!IsUnifiedPlan());
4549 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004550 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004551 return transceiver;
4552 }
4553 }
4554 RTC_NOTREACHED();
4555 return nullptr;
4556}
4557
4558// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4559// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004560bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004561 switch (type) {
4562 case cricket::MEDIA_TYPE_AUDIO:
4563 return !GetAudioTransceiver()->internal()->senders().empty();
4564 case cricket::MEDIA_TYPE_VIDEO:
4565 return !GetVideoTransceiver()->internal()->senders().empty();
4566 case cricket::MEDIA_TYPE_DATA:
4567 return false;
4568 }
4569 RTC_NOTREACHED();
4570 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004571}
4572
Steve Anton4171afb2017-11-20 10:20:22 -08004573rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4574PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4575 for (auto transceiver : transceivers_) {
4576 for (auto sender : transceiver->internal()->senders()) {
4577 if (sender->track() == track) {
4578 return sender;
4579 }
4580 }
4581 }
4582 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004583}
4584
Steve Anton4171afb2017-11-20 10:20:22 -08004585rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4586PeerConnection::FindSenderById(const std::string& sender_id) const {
4587 for (auto transceiver : transceivers_) {
4588 for (auto sender : transceiver->internal()->senders()) {
4589 if (sender->id() == sender_id) {
4590 return sender;
4591 }
4592 }
4593 }
4594 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004595}
4596
Steve Anton4171afb2017-11-20 10:20:22 -08004597rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4598PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4599 for (auto transceiver : transceivers_) {
4600 for (auto receiver : transceiver->internal()->receivers()) {
4601 if (receiver->id() == receiver_id) {
4602 return receiver;
4603 }
4604 }
4605 }
4606 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004607}
4608
Steve Anton4171afb2017-11-20 10:20:22 -08004609std::vector<PeerConnection::RtpSenderInfo>*
4610PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4611 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4612 media_type == cricket::MEDIA_TYPE_VIDEO);
4613 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4614 ? &remote_audio_sender_infos_
4615 : &remote_video_sender_infos_;
4616}
4617
4618std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004619 cricket::MediaType media_type) {
4620 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4621 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004622 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4623 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004624}
4625
Steve Anton4171afb2017-11-20 10:20:22 -08004626const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4627 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004628 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004629 const std::string sender_id) const {
4630 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004631 if (sender_info.stream_id == stream_id &&
4632 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004633 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004634 }
4635 }
4636 return nullptr;
4637}
4638
4639DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4640 for (const auto& channel : sctp_data_channels_) {
4641 if (channel->id() == sid) {
4642 return channel;
4643 }
4644 }
4645 return nullptr;
4646}
4647
deadbeef91dd5672016-05-18 16:55:30 -07004648bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004649 const RTCConfiguration& configuration) {
4650 cricket::ServerAddresses stun_servers;
4651 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004652 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4653 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004654 return false;
4655 }
4656
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004657 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004658 // To handle both internal and externally created port allocator, we will
4659 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004660 port_allocator_flags_ = port_allocator_->flags();
4661 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4662 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4663 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004664 // If the disable-IPv6 flag was specified, we'll not override it
4665 // by experiment.
4666 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004667 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004668 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4669 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004670 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004671 }
4672
zhihuangb09b3f92017-03-07 14:40:51 -08004673 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004674 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004675 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004676 }
4677
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004678 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004679 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004680 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004681 }
4682
honghaiz60347052016-05-31 18:29:12 -07004683 if (configuration.candidate_network_policy ==
4684 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004685 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004686 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004687 }
4688
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004689 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004690 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004691 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4692 }
4693
Qingsi Wanga2d60672018-04-11 16:57:45 -07004694 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004695 // No step delay is used while allocating ports.
4696 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4697 port_allocator_->set_candidate_filter(
4698 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004699 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004700
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004701 if (tls_cert_verifier_ != nullptr) {
4702 for (auto& turn_server : turn_servers) {
4703 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4704 }
4705 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004706 // Call this last since it may create pooled allocator sessions using the
4707 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004708 port_allocator_->SetConfiguration(
4709 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4710 configuration.prune_turn_ports, configuration.turn_customizer,
4711 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004712 return true;
4713}
4714
deadbeef91dd5672016-05-18 16:55:30 -07004715bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004716 const cricket::ServerAddresses& stun_servers,
4717 const std::vector<cricket::RelayServerConfig>& turn_servers,
4718 IceTransportsType type,
4719 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004720 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004721 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004722 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004723 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004724 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004725 // According to JSEP, after setLocalDescription, changing the candidate pool
4726 // size is not allowed, and changing the set of ICE servers will not result
4727 // in new candidates being gathered.
4728 if (local_description()) {
4729 port_allocator_->FreezeCandidatePool();
4730 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004731 // Call this last since it may create pooled allocator sessions using the
4732 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004733 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004734 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004735 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004736}
4737
Steve Antonba818672017-11-06 10:21:57 -08004738cricket::ChannelManager* PeerConnection::channel_manager() const {
4739 return factory_->channel_manager();
4740}
4741
4742MetricsObserverInterface* PeerConnection::metrics_observer() const {
4743 return uma_observer_;
4744}
4745
Elad Alon99c3fe52017-10-13 16:29:40 +02004746bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004747 std::unique_ptr<RtcEventLogOutput> output,
4748 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004749 if (!event_log_) {
4750 return false;
4751 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004752 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004753}
4754
4755void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004756 if (event_log_) {
4757 event_log_->StopLogging();
4758 }
ivoc14d5dbe2016-07-04 07:06:55 -07004759}
nisseeaabdf62017-05-05 02:23:02 -07004760
Steve Anton75737c02017-11-06 10:37:17 -08004761cricket::BaseChannel* PeerConnection::GetChannel(
4762 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004763 for (auto transceiver : transceivers_) {
4764 cricket::BaseChannel* channel = transceiver->internal()->channel();
4765 if (channel && channel->content_name() == content_name) {
4766 return channel;
4767 }
Steve Anton75737c02017-11-06 10:37:17 -08004768 }
4769 if (rtp_data_channel() &&
4770 rtp_data_channel()->content_name() == content_name) {
4771 return rtp_data_channel();
4772 }
4773 return nullptr;
4774}
4775
4776bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4777 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004778 RTC_LOG(LS_INFO)
4779 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004780 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004781 return false;
4782 }
4783 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004784 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004785 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004786 return false;
4787 }
4788
Zhi Huange830e682018-03-30 10:48:35 -07004789 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4790 if (dtls_role) {
4791 *role = *dtls_role;
4792 return true;
4793 }
4794 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004795}
4796
4797bool PeerConnection::GetSslRole(const std::string& content_name,
4798 rtc::SSLRole* role) {
4799 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004800 RTC_LOG(LS_INFO)
4801 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004802 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004803 return false;
4804 }
4805
Zhi Huange830e682018-03-30 10:48:35 -07004806 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4807 if (dtls_role) {
4808 *role = *dtls_role;
4809 return true;
4810 }
4811 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004812}
4813
Steve Antonf8470812017-12-04 10:46:21 -08004814void PeerConnection::SetSessionError(SessionError error,
4815 const std::string& error_desc) {
4816 RTC_DCHECK_RUN_ON(signaling_thread());
4817 if (error != session_error_) {
4818 session_error_ = error;
4819 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004820 }
4821}
4822
Zhi Huange830e682018-03-30 10:48:35 -07004823RTCError PeerConnection::UpdateSessionState(
4824 SdpType type,
4825 cricket::ContentSource source,
4826 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004827 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004828
4829 // If there's already a pending error then no state transition should happen.
4830 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004831 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004832
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004833 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004834 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004835 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004836 }
4837
4838 // Update the signaling state according to the specified state machine (see
4839 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004840 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004841 ChangeSignalingState(source == cricket::CS_LOCAL
4842 ? PeerConnectionInterface::kHaveLocalOffer
4843 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004844 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004845 ChangeSignalingState(source == cricket::CS_LOCAL
4846 ? PeerConnectionInterface::kHaveLocalPrAnswer
4847 : PeerConnectionInterface::kHaveRemotePrAnswer);
4848 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004849 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004850 ChangeSignalingState(PeerConnectionInterface::kStable);
4851 }
4852
4853 // Update internal objects according to the session description's media
4854 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004855 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004856 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004857 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004858 }
4859
Steve Anton8a006912017-12-04 15:25:56 -08004860 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004861}
4862
Steve Anton8a006912017-12-04 15:25:56 -08004863RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004864 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004865 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004866 const SessionDescriptionInterface* sdesc =
4867 (source == cricket::CS_LOCAL ? local_description()
4868 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004869 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004870
4871 // Push down the new SDP media section for each audio/video transceiver.
4872 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004873 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004874 FindMediaSectionForTransceiver(transceiver, sdesc);
4875 cricket::BaseChannel* channel = transceiver->internal()->channel();
4876 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004877 continue;
4878 }
4879 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004880 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004881 if (!content_desc) {
4882 continue;
4883 }
4884 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004885 bool success = (source == cricket::CS_LOCAL)
4886 ? channel->SetLocalContent(content_desc, type, &error)
4887 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004888 if (!success) {
4889 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4890 }
4891 }
4892
4893 // If using the RtpDataChannel, push down the new SDP section for it too.
4894 if (rtp_data_channel_) {
4895 const ContentInfo* data_content =
4896 cricket::GetFirstDataContent(sdesc->description());
4897 if (data_content && !data_content->rejected) {
4898 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004899 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004900 if (data_desc) {
4901 std::string error;
4902 bool success =
4903 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004904 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004905 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004906 if (!success) {
4907 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4908 std::move(error));
4909 }
Steve Anton75737c02017-11-06 10:37:17 -08004910 }
4911 }
4912 }
Steve Antoned10bd92017-12-05 10:52:59 -08004913
Steve Anton75737c02017-11-06 10:37:17 -08004914 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4915 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4916 if (sctp_transport_ && local_description() && remote_description() &&
4917 cricket::GetFirstDataContent(local_description()->description()) &&
4918 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004919 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004920 RTC_FROM_HERE,
4921 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004922 if (!success) {
4923 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4924 "Failed to push down SCTP parameters.");
4925 }
Steve Anton75737c02017-11-06 10:37:17 -08004926 }
Steve Antoned10bd92017-12-05 10:52:59 -08004927
Steve Anton8a006912017-12-04 15:25:56 -08004928 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004929}
4930
4931bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4932 RTC_DCHECK(network_thread()->IsCurrent());
4933 RTC_DCHECK(local_description());
4934 RTC_DCHECK(remote_description());
4935 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4936 // When we support "max-message-size", that would also be pushed down here.
4937 return sctp_transport_->Start(
4938 GetSctpPort(local_description()->description()),
4939 GetSctpPort(remote_description()->description()));
4940}
4941
Steve Anton8a006912017-12-04 15:25:56 -08004942RTCError PeerConnection::PushdownTransportDescription(
4943 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004944 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004945 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004946
Zhi Huange830e682018-03-30 10:48:35 -07004947 if (source == cricket::CS_LOCAL) {
4948 const SessionDescriptionInterface* sdesc = local_description();
4949 RTC_DCHECK(sdesc);
4950 return transport_controller_->SetLocalDescription(type,
4951 sdesc->description());
4952 } else {
4953 const SessionDescriptionInterface* sdesc = remote_description();
4954 RTC_DCHECK(sdesc);
4955 return transport_controller_->SetRemoteDescription(type,
4956 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004957 }
Steve Anton75737c02017-11-06 10:37:17 -08004958}
4959
4960bool PeerConnection::GetTransportDescription(
4961 const SessionDescription* description,
4962 const std::string& content_name,
4963 cricket::TransportDescription* tdesc) {
4964 if (!description || !tdesc) {
4965 return false;
4966 }
4967 const TransportInfo* transport_info =
4968 description->GetTransportInfoByName(content_name);
4969 if (!transport_info) {
4970 return false;
4971 }
4972 *tdesc = transport_info->description;
4973 return true;
4974}
4975
Steve Anton75737c02017-11-06 10:37:17 -08004976cricket::IceConfig PeerConnection::ParseIceConfig(
4977 const PeerConnectionInterface::RTCConfiguration& config) const {
4978 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004979 switch (config.continual_gathering_policy) {
4980 case PeerConnectionInterface::GATHER_ONCE:
4981 gathering_policy = cricket::GATHER_ONCE;
4982 break;
4983 case PeerConnectionInterface::GATHER_CONTINUALLY:
4984 gathering_policy = cricket::GATHER_CONTINUALLY;
4985 break;
4986 default:
4987 RTC_NOTREACHED();
4988 gathering_policy = cricket::GATHER_ONCE;
4989 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004990
Steve Anton75737c02017-11-06 10:37:17 -08004991 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004992 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4993 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004994 ice_config.prioritize_most_likely_candidate_pairs =
4995 config.prioritize_most_likely_ice_candidate_pairs;
4996 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004997 RTCConfigurationToIceConfigOptionalInt(
4998 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004999 ice_config.continual_gathering_policy = gathering_policy;
5000 ice_config.presume_writable_when_fully_relayed =
5001 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005002 ice_config.ice_check_interval_strong_connectivity =
5003 config.ice_check_interval_strong_connectivity;
5004 ice_config.ice_check_interval_weak_connectivity =
5005 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005006 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005007 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005008 ice_config.regather_all_networks_interval_range =
5009 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005010 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005011 return ice_config;
5012}
5013
Steve Anton75737c02017-11-06 10:37:17 -08005014bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5015 std::string* track_id) {
5016 if (!local_description()) {
5017 return false;
5018 }
5019 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5020 track_id);
5021}
5022
5023bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5024 std::string* track_id) {
5025 if (!remote_description()) {
5026 return false;
5027 }
5028 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5029 track_id);
5030}
5031
5032bool PeerConnection::SendData(const cricket::SendDataParams& params,
5033 const rtc::CopyOnWriteBuffer& payload,
5034 cricket::SendDataResult* result) {
5035 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005036 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005037 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005038 return false;
5039 }
5040 return rtp_data_channel_
5041 ? rtp_data_channel_->SendData(params, payload, result)
5042 : network_thread()->Invoke<bool>(
5043 RTC_FROM_HERE,
5044 Bind(&cricket::SctpTransportInternal::SendData,
5045 sctp_transport_.get(), params, payload, result));
5046}
5047
5048bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5049 if (!rtp_data_channel_ && !sctp_transport_) {
5050 // Don't log an error here, because DataChannels are expected to call
5051 // ConnectDataChannel in this state. It's the only way to initially tell
5052 // whether or not the underlying transport is ready.
5053 return false;
5054 }
5055 if (rtp_data_channel_) {
5056 rtp_data_channel_->SignalReadyToSendData.connect(
5057 webrtc_data_channel, &DataChannel::OnChannelReady);
5058 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5059 &DataChannel::OnDataReceived);
5060 } else {
5061 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5062 &DataChannel::OnChannelReady);
5063 SignalSctpDataReceived.connect(webrtc_data_channel,
5064 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005065 SignalSctpClosingProcedureStartedRemotely.connect(
5066 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5067 SignalSctpClosingProcedureComplete.connect(
5068 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005069 }
5070 return true;
5071}
5072
5073void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5074 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005075 RTC_LOG(LS_ERROR)
5076 << "DisconnectDataChannel called when rtp_data_channel_ and "
5077 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005078 return;
5079 }
5080 if (rtp_data_channel_) {
5081 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5082 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5083 } else {
5084 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5085 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005086 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5087 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005088 }
5089}
5090
5091void PeerConnection::AddSctpDataStream(int sid) {
5092 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005093 RTC_LOG(LS_ERROR)
5094 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005095 return;
5096 }
5097 network_thread()->Invoke<void>(
5098 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5099 sctp_transport_.get(), sid));
5100}
5101
5102void PeerConnection::RemoveSctpDataStream(int sid) {
5103 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005104 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005105 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005106 return;
5107 }
5108 network_thread()->Invoke<void>(
5109 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5110 sctp_transport_.get(), sid));
5111}
5112
5113bool PeerConnection::ReadyToSendData() const {
5114 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5115 sctp_ready_to_send_data_;
5116}
5117
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005118absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005119 if (sctp_mid_ && transport_controller_) {
5120 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5121 if (dtls_transport) {
5122 return dtls_transport->transport_name();
5123 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005124 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005125 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005126 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005127}
5128
Qingsi Wang72a43a12018-02-20 16:03:18 -08005129cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5130 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005131 network_thread()->Invoke<void>(
5132 RTC_FROM_HERE,
5133 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5134 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005135 return candidate_states_list;
5136}
5137
Steve Anton5dfde182018-02-06 10:34:40 -08005138std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5139 const {
5140 std::map<std::string, std::string> transport_names_by_mid;
5141 for (auto transceiver : transceivers_) {
5142 cricket::BaseChannel* channel = transceiver->internal()->channel();
5143 if (channel) {
5144 transport_names_by_mid[channel->content_name()] =
5145 channel->transport_name();
5146 }
Steve Anton75737c02017-11-06 10:37:17 -08005147 }
Steve Anton5dfde182018-02-06 10:34:40 -08005148 if (rtp_data_channel_) {
5149 transport_names_by_mid[rtp_data_channel_->content_name()] =
5150 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005151 }
5152 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005153 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005154 RTC_DCHECK(transport_name);
5155 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005156 }
Steve Anton5dfde182018-02-06 10:34:40 -08005157 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005158}
5159
Steve Anton5dfde182018-02-06 10:34:40 -08005160std::map<std::string, cricket::TransportStats>
5161PeerConnection::GetTransportStatsByNames(
5162 const std::set<std::string>& transport_names) {
5163 if (!network_thread()->IsCurrent()) {
5164 return network_thread()
5165 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5166 RTC_FROM_HERE,
5167 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005168 }
Steve Anton5dfde182018-02-06 10:34:40 -08005169 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5170 for (const std::string& transport_name : transport_names) {
5171 cricket::TransportStats transport_stats;
5172 bool success =
5173 transport_controller_->GetStats(transport_name, &transport_stats);
5174 if (success) {
5175 transport_stats_by_name[transport_name] = std::move(transport_stats);
5176 } else {
5177 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5178 << transport_name;
5179 }
5180 }
5181 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005182}
5183
5184bool PeerConnection::GetLocalCertificate(
5185 const std::string& transport_name,
5186 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005187 if (!certificate) {
5188 return false;
5189 }
5190 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5191 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005192}
5193
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005194std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005195 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005196 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005197}
5198
5199cricket::DataChannelType PeerConnection::data_channel_type() const {
5200 return data_channel_type_;
5201}
5202
5203bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5204 return pending_ice_restarts_.find(content_name) !=
5205 pending_ice_restarts_.end();
5206}
5207
Steve Anton75737c02017-11-06 10:37:17 -08005208bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5209 return transport_controller_->NeedsIceRestart(content_name);
5210}
5211
5212void PeerConnection::OnCertificateReady(
5213 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5214 transport_controller_->SetLocalCertificate(certificate);
5215}
5216
5217void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005218 SetSessionError(SessionError::kTransport,
5219 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005220}
5221
5222void PeerConnection::OnTransportControllerConnectionState(
5223 cricket::IceConnectionState state) {
5224 switch (state) {
5225 case cricket::kIceConnectionConnecting:
5226 // If the current state is Connected or Completed, then there were
5227 // writable channels but now there are not, so the next state must
5228 // be Disconnected.
5229 // kIceConnectionConnecting is currently used as the default,
5230 // un-connected state by the TransportController, so its only use is
5231 // detecting disconnections.
5232 if (ice_connection_state_ ==
5233 PeerConnectionInterface::kIceConnectionConnected ||
5234 ice_connection_state_ ==
5235 PeerConnectionInterface::kIceConnectionCompleted) {
5236 SetIceConnectionState(
5237 PeerConnectionInterface::kIceConnectionDisconnected);
5238 }
5239 break;
5240 case cricket::kIceConnectionFailed:
5241 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5242 break;
5243 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005244 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005245 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005246 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005247 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005248 break;
5249 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005250 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005251 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005252 if (ice_connection_state_ !=
5253 PeerConnectionInterface::kIceConnectionConnected) {
5254 // If jumping directly from "checking" to "connected",
5255 // signal "connected" first.
5256 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5257 }
5258 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005259 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005260 if (metrics_observer()) {
5261 ReportTransportStats();
5262 }
5263 break;
5264 default:
5265 RTC_NOTREACHED();
5266 }
5267}
5268
5269void PeerConnection::OnTransportControllerCandidatesGathered(
5270 const std::string& transport_name,
5271 const cricket::Candidates& candidates) {
5272 RTC_DCHECK(signaling_thread()->IsCurrent());
5273 int sdp_mline_index;
5274 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005275 RTC_LOG(LS_ERROR)
5276 << "OnTransportControllerCandidatesGathered: content name "
5277 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005278 return;
5279 }
5280
5281 for (cricket::Candidates::const_iterator citer = candidates.begin();
5282 citer != candidates.end(); ++citer) {
5283 // Use transport_name as the candidate media id.
5284 std::unique_ptr<JsepIceCandidate> candidate(
5285 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5286 if (local_description()) {
5287 mutable_local_description()->AddCandidate(candidate.get());
5288 }
5289 OnIceCandidate(std::move(candidate));
5290 }
5291}
5292
5293void PeerConnection::OnTransportControllerCandidatesRemoved(
5294 const std::vector<cricket::Candidate>& candidates) {
5295 RTC_DCHECK(signaling_thread()->IsCurrent());
5296 // Sanity check.
5297 for (const cricket::Candidate& candidate : candidates) {
5298 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005299 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005300 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005301 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005302 return;
5303 }
5304 }
5305
5306 if (local_description()) {
5307 mutable_local_description()->RemoveCandidates(candidates);
5308 }
5309 OnIceCandidatesRemoved(candidates);
5310}
5311
5312void PeerConnection::OnTransportControllerDtlsHandshakeError(
5313 rtc::SSLHandshakeError error) {
5314 if (metrics_observer()) {
5315 metrics_observer()->IncrementEnumCounter(
5316 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5317 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5318 }
5319}
5320
Steve Antoned10bd92017-12-05 10:52:59 -08005321void PeerConnection::EnableSending() {
5322 for (auto transceiver : transceivers_) {
5323 cricket::BaseChannel* channel = transceiver->internal()->channel();
5324 if (channel && !channel->enabled()) {
5325 channel->Enable(true);
5326 }
Steve Anton75737c02017-11-06 10:37:17 -08005327 }
5328
Steve Anton4171afb2017-11-20 10:20:22 -08005329 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005330 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005331 }
Steve Anton75737c02017-11-06 10:37:17 -08005332}
5333
5334// Returns the media index for a local ice candidate given the content name.
5335bool PeerConnection::GetLocalCandidateMediaIndex(
5336 const std::string& content_name,
5337 int* sdp_mline_index) {
5338 if (!local_description() || !sdp_mline_index) {
5339 return false;
5340 }
5341
5342 bool content_found = false;
5343 const ContentInfos& contents = local_description()->description()->contents();
5344 for (size_t index = 0; index < contents.size(); ++index) {
5345 if (contents[index].name == content_name) {
5346 *sdp_mline_index = static_cast<int>(index);
5347 content_found = true;
5348 break;
5349 }
5350 }
5351 return content_found;
5352}
5353
5354bool PeerConnection::UseCandidatesInSessionDescription(
5355 const SessionDescriptionInterface* remote_desc) {
5356 if (!remote_desc) {
5357 return true;
5358 }
5359 bool ret = true;
5360
5361 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5362 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5363 for (size_t n = 0; n < candidates->count(); ++n) {
5364 const IceCandidateInterface* candidate = candidates->at(n);
5365 bool valid = false;
5366 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5367 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005368 RTC_LOG(LS_INFO)
5369 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005370 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005371 }
5372 continue;
5373 }
5374 ret = UseCandidate(candidate);
5375 if (!ret) {
5376 break;
5377 }
5378 }
5379 }
5380 return ret;
5381}
5382
5383bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5384 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5385 size_t remote_content_size =
5386 remote_description()->description()->contents().size();
5387 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005388 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005389 return false;
5390 }
5391
5392 cricket::ContentInfo content =
5393 remote_description()->description()->contents()[mediacontent_index];
5394 std::vector<cricket::Candidate> candidates;
5395 candidates.push_back(candidate->candidate());
5396 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005397 RTCError error =
5398 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005399 if (error.ok()) {
5400 // Candidates successfully submitted for checking.
5401 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5402 ice_connection_state_ ==
5403 PeerConnectionInterface::kIceConnectionDisconnected) {
5404 // If state is New, then the session has just gotten its first remote ICE
5405 // candidates, so go to Checking.
5406 // If state is Disconnected, the session is re-using old candidates or
5407 // receiving additional ones, so go to Checking.
5408 // If state is Connected, stay Connected.
5409 // TODO(bemasc): If state is Connected, and the new candidates are for a
5410 // newly added transport, then the state actually _should_ move to
5411 // checking. Add a way to distinguish that case.
5412 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5413 }
5414 // TODO(bemasc): If state is Completed, go back to Connected.
5415 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005416 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005417 }
5418 return true;
5419}
5420
5421void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005422 // Destroy video channel first since it may have a pointer to the
5423 // voice channel.
5424 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005425 if (!video_info || video_info->rejected) {
5426 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005427 }
5428
Steve Anton6fec8802017-12-04 10:37:29 -08005429 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5430 if (!audio_info || audio_info->rejected) {
5431 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005432 }
5433
5434 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5435 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005436 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005437 }
5438}
5439
Steve Antondcc3c022017-12-22 16:02:54 -08005440RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5441 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005442 const cricket::ContentGroup* bundle_group = nullptr;
5443 if (configuration_.bundle_policy ==
5444 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005445 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005446 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005447 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5448 "max-bundle configured but session description "
5449 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005450 }
5451 }
Steve Antondcc3c022017-12-22 16:02:54 -08005452 return std::move(bundle_group);
5453}
5454
5455RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005456 // Creating the media channels. Transports should already have been created
5457 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005458 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005459 if (voice && !voice->rejected &&
5460 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005461 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005462 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005463 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5464 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005465 }
5466 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5467 }
5468
Steve Antondcc3c022017-12-22 16:02:54 -08005469 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005470 if (video && !video->rejected &&
5471 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005472 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005473 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005474 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5475 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005476 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005477 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005478 }
5479
Steve Antondcc3c022017-12-22 16:02:54 -08005480 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005481 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5482 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005483 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005484 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5485 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005486 }
5487 }
5488
Steve Anton8a006912017-12-04 15:25:56 -08005489 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005490}
5491
Steve Anton4171afb2017-11-20 10:20:22 -08005492// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005493cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005494 const std::string& mid) {
5495 RtpTransportInternal* rtp_transport =
5496 transport_controller_->GetRtpTransport(mid);
5497 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005498 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005499 call_.get(), configuration_.media_config, rtp_transport,
5500 signaling_thread(), mid, SrtpRequired(),
5501 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005502 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005503 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005504 }
Steve Anton75737c02017-11-06 10:37:17 -08005505 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5506 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005507 voice_channel->SignalSentPacket.connect(this,
5508 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005509 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005510 if (uma_observer_) {
5511 voice_channel->SetMetricsObserver(uma_observer_);
5512 }
Steve Anton4171afb2017-11-20 10:20:22 -08005513
Steve Antoneda6ccd2017-12-04 10:21:55 -08005514 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005515}
5516
Steve Anton4171afb2017-11-20 10:20:22 -08005517// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005518cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005519 const std::string& mid) {
5520 RtpTransportInternal* rtp_transport =
5521 transport_controller_->GetRtpTransport(mid);
5522 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005523 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005524 call_.get(), configuration_.media_config, rtp_transport,
5525 signaling_thread(), mid, SrtpRequired(),
5526 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005527 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005528 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005529 }
Steve Anton75737c02017-11-06 10:37:17 -08005530 video_channel->SignalDtlsSrtpSetupFailure.connect(
5531 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005532 video_channel->SignalSentPacket.connect(this,
5533 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005534 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005535 if (uma_observer_) {
5536 video_channel->SetMetricsObserver(uma_observer_);
5537 }
Steve Anton4171afb2017-11-20 10:20:22 -08005538
Steve Antoneda6ccd2017-12-04 10:21:55 -08005539 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005540}
5541
Zhi Huange830e682018-03-30 10:48:35 -07005542bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005543 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5544 if (sctp) {
5545 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005546 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005547 << "Trying to create SCTP transport, but didn't compile with "
5548 "SCTP support (HAVE_SCTP)";
5549 return false;
5550 }
5551 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005552 RTC_FROM_HERE,
5553 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005554 return false;
5555 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005556 for (const auto& channel : sctp_data_channels_) {
5557 channel->OnTransportChannelCreated();
5558 }
Steve Anton75737c02017-11-06 10:37:17 -08005559 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005560 RtpTransportInternal* rtp_transport =
5561 transport_controller_->GetRtpTransport(mid);
5562 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005563 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005564 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5565 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005566 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005567 return false;
5568 }
Steve Anton75737c02017-11-06 10:37:17 -08005569 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5570 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5571 rtp_data_channel_->SignalSentPacket.connect(
5572 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005573 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005574 if (uma_observer_) {
5575 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5576 }
Steve Anton75737c02017-11-06 10:37:17 -08005577 }
5578
Steve Anton75737c02017-11-06 10:37:17 -08005579 return true;
5580}
5581
5582Call::Stats PeerConnection::GetCallStats() {
5583 if (!worker_thread()->IsCurrent()) {
5584 return worker_thread()->Invoke<Call::Stats>(
5585 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5586 }
5587 if (call_) {
5588 return call_->GetStats();
5589 } else {
5590 return Call::Stats();
5591 }
5592}
5593
Zhi Huange830e682018-03-30 10:48:35 -07005594bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005595 RTC_DCHECK(network_thread()->IsCurrent());
5596 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005597 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005598 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005599 RTC_DCHECK(dtls_transport);
5600 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005601 RTC_DCHECK(sctp_transport_);
5602 sctp_invoker_.reset(new rtc::AsyncInvoker());
5603 sctp_transport_->SignalReadyToSendData.connect(
5604 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5605 sctp_transport_->SignalDataReceived.connect(
5606 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005607 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5608 // another thread. Would be nice if there was a helper class similar to
5609 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5610 // code.
5611 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5612 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5613 sctp_transport_->SignalClosingProcedureComplete.connect(
5614 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005615 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005616 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005617 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005618}
5619
5620void PeerConnection::DestroySctpTransport_n() {
5621 RTC_DCHECK(network_thread()->IsCurrent());
5622 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005623 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005624 sctp_invoker_.reset(nullptr);
5625 sctp_ready_to_send_data_ = false;
5626}
5627
5628void PeerConnection::OnSctpTransportReadyToSendData_n() {
5629 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5630 RTC_DCHECK(network_thread()->IsCurrent());
5631 // Note: Cannot use rtc::Bind here because it will grab a reference to
5632 // PeerConnection and potentially cause PeerConnection to live longer than
5633 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5634 // be destroyed before PeerConnection is destroyed, and at that point all
5635 // pending tasks will be cleared.
5636 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5637 OnSctpTransportReadyToSendData_s(true);
5638 });
5639}
5640
5641void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5642 RTC_DCHECK(signaling_thread()->IsCurrent());
5643 sctp_ready_to_send_data_ = ready;
5644 SignalSctpReadyToSendData(ready);
5645}
5646
5647void PeerConnection::OnSctpTransportDataReceived_n(
5648 const cricket::ReceiveDataParams& params,
5649 const rtc::CopyOnWriteBuffer& payload) {
5650 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5651 RTC_DCHECK(network_thread()->IsCurrent());
5652 // Note: Cannot use rtc::Bind here because it will grab a reference to
5653 // PeerConnection and potentially cause PeerConnection to live longer than
5654 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5655 // be destroyed before PeerConnection is destroyed, and at that point all
5656 // pending tasks will be cleared.
5657 sctp_invoker_->AsyncInvoke<void>(
5658 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5659 OnSctpTransportDataReceived_s(params, payload);
5660 });
5661}
5662
5663void PeerConnection::OnSctpTransportDataReceived_s(
5664 const cricket::ReceiveDataParams& params,
5665 const rtc::CopyOnWriteBuffer& payload) {
5666 RTC_DCHECK(signaling_thread()->IsCurrent());
5667 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5668 // Received OPEN message; parse and signal that a new data channel should
5669 // be created.
5670 std::string label;
5671 InternalDataChannelInit config;
5672 config.id = params.ssrc;
5673 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005674 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5675 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005676 return;
5677 }
5678 config.open_handshake_role = InternalDataChannelInit::kAcker;
5679 OnDataChannelOpenMessage(label, config);
5680 } else {
5681 // Otherwise just forward the signal.
5682 SignalSctpDataReceived(params, payload);
5683 }
5684}
5685
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005686void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005687 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5688 RTC_DCHECK(network_thread()->IsCurrent());
5689 sctp_invoker_->AsyncInvoke<void>(
5690 RTC_FROM_HERE, signaling_thread(),
5691 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005692 &SignalSctpClosingProcedureStartedRemotely, sid));
5693}
5694
5695void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5696 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5697 RTC_DCHECK(network_thread()->IsCurrent());
5698 sctp_invoker_->AsyncInvoke<void>(
5699 RTC_FROM_HERE, signaling_thread(),
5700 rtc::Bind(&sigslot::signal1<int>::operator(),
5701 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005702}
5703
5704// Returns false if bundle is enabled and rtcp_mux is disabled.
5705bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5706 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5707 if (!bundle_enabled)
5708 return true;
5709
5710 const cricket::ContentGroup* bundle_group =
5711 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5712 RTC_DCHECK(bundle_group != NULL);
5713
5714 const cricket::ContentInfos& contents = desc->contents();
5715 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5716 citer != contents.end(); ++citer) {
5717 const cricket::ContentInfo* content = (&*citer);
5718 RTC_DCHECK(content != NULL);
5719 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005720 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005721 if (!HasRtcpMuxEnabled(content))
5722 return false;
5723 }
5724 }
5725 // RTCP-MUX is enabled in all the contents.
5726 return true;
5727}
5728
5729bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005730 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005731}
5732
Steve Anton8a006912017-12-04 15:25:56 -08005733RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005734 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005735 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005736 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005737 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005738 }
5739
5740 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005741 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005742 }
5743
Steve Anton3828c062017-12-06 10:34:51 -08005744 SdpType type = sdesc->GetType();
5745 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5746 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005747 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005748 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005749 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005750 }
5751
5752 // Verify crypto settings.
5753 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005754 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5755 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005756 RTCError crypto_error =
5757 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005758 if (!crypto_error.ok()) {
5759 return crypto_error;
5760 }
Steve Anton75737c02017-11-06 10:37:17 -08005761 }
5762
5763 // Verify ice-ufrag and ice-pwd.
5764 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005765 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5766 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005767 }
5768
5769 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005770 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5771 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005772 }
5773
5774 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5775 // m-lines that do not rtcp-mux enabled.
5776
5777 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005778 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005779 // With an answer we want to compare the new answer session description with
5780 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005781 const cricket::SessionDescription* offer_desc =
5782 (source == cricket::CS_LOCAL) ? remote_description()->description()
5783 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005784 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5785 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5786 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005787 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5788 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005789 }
5790 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005791 // The re-offers should respect the order of m= sections in current
5792 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005793 // With a re-offer, either the current local or current remote descriptions
5794 // could be the most up to date, so we would like to check against both of
5795 // them if they exist. It could be the case that one of them has a 0 port
5796 // for a media section, but the other does not. This is important to check
5797 // against in the case that we are recycling an m= section.
5798 const cricket::SessionDescription* current_desc = nullptr;
5799 const cricket::SessionDescription* secondary_current_desc = nullptr;
5800 if (local_description()) {
5801 current_desc = local_description()->description();
5802 if (remote_description()) {
5803 secondary_current_desc = remote_description()->description();
5804 }
5805 } else if (remote_description()) {
5806 current_desc = remote_description()->description();
5807 }
Steve Anton75737c02017-11-06 10:37:17 -08005808 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005809 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5810 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005811 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5812 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005813 }
5814 }
5815
Steve Antonba42e992018-04-09 14:10:01 -07005816 if (IsUnifiedPlan()) {
5817 // Ensure that each audio and video media section has at most one
5818 // "StreamParams". This will return an error if receiving a session
5819 // description from a "Plan B" endpoint which adds multiple tracks of the
5820 // same type. With Unified Plan, there can only be at most one track per
5821 // media section.
5822 for (const ContentInfo& content : sdesc->description()->contents()) {
5823 const MediaContentDescription& desc = *content.description;
5824 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5825 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5826 desc.streams().size() > 1u) {
5827 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5828 "Media section has more than one track specified "
5829 "with a=ssrc lines which is not supported with "
5830 "Unified Plan.");
5831 }
5832 }
5833 }
5834
Steve Anton8a006912017-12-04 15:25:56 -08005835 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005836}
5837
Steve Anton3828c062017-12-06 10:34:51 -08005838bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005839 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005840 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005841 return (state == PeerConnectionInterface::kStable) ||
5842 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005843 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005844 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005845 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5846 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5847 }
5848}
5849
Steve Anton3828c062017-12-06 10:34:51 -08005850bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005852 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005853 return (state == PeerConnectionInterface::kStable) ||
5854 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005855 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005856 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005857 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5858 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5859 }
5860}
5861
Steve Antonf8470812017-12-04 10:46:21 -08005862const char* PeerConnection::SessionErrorToString(SessionError error) const {
5863 switch (error) {
5864 case SessionError::kNone:
5865 return "ERROR_NONE";
5866 case SessionError::kContent:
5867 return "ERROR_CONTENT";
5868 case SessionError::kTransport:
5869 return "ERROR_TRANSPORT";
5870 }
5871 RTC_NOTREACHED();
5872 return "";
5873}
5874
Steve Anton75737c02017-11-06 10:37:17 -08005875std::string PeerConnection::GetSessionErrorMsg() {
5876 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005877 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5878 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005879 return desc.str();
5880}
5881
Steve Anton8e20f172018-03-06 10:55:04 -08005882void PeerConnection::ReportSdpFormatReceived(
5883 const SessionDescriptionInterface& remote_offer) {
5884 if (!uma_observer_) {
5885 return;
5886 }
5887 int num_audio_mlines = 0;
5888 int num_video_mlines = 0;
5889 int num_audio_tracks = 0;
5890 int num_video_tracks = 0;
5891 for (const ContentInfo& content : remote_offer.description()->contents()) {
5892 cricket::MediaType media_type = content.media_description()->type();
5893 int num_tracks = std::max(
5894 1, static_cast<int>(content.media_description()->streams().size()));
5895 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5896 num_audio_mlines += 1;
5897 num_audio_tracks += num_tracks;
5898 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5899 num_video_mlines += 1;
5900 num_video_tracks += num_tracks;
5901 }
5902 }
5903 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5904 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5905 format = kSdpFormatReceivedComplexUnifiedPlan;
5906 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5907 format = kSdpFormatReceivedComplexPlanB;
5908 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5909 format = kSdpFormatReceivedSimple;
5910 }
5911 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5912 kSdpFormatReceivedMax);
5913}
5914
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005915void PeerConnection::NoteUsageEvent(UsageEvent event) {
5916 RTC_DCHECK_RUN_ON(signaling_thread());
5917 usage_event_accumulator_ |= static_cast<int>(event);
5918}
5919
5920void PeerConnection::ReportUsagePattern() const {
5921 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5922 if (uma_observer_) {
5923 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5924 usage_event_accumulator_);
5925 }
5926}
5927
Steve Anton0ffaaa22018-02-23 10:31:30 -08005928void PeerConnection::ReportNegotiatedSdpSemantics(
5929 const SessionDescriptionInterface& answer) {
5930 if (!uma_observer_) {
5931 return;
5932 }
5933 switch (answer.description()->msid_signaling()) {
5934 case 0:
5935 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5936 kSdpSemanticNegotiatedNone,
5937 kSdpSemanticNegotiatedMax);
5938 break;
5939 case cricket::kMsidSignalingMediaSection:
5940 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5941 kSdpSemanticNegotiatedUnifiedPlan,
5942 kSdpSemanticNegotiatedMax);
5943 break;
5944 case cricket::kMsidSignalingSsrcAttribute:
5945 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5946 kSdpSemanticNegotiatedPlanB,
5947 kSdpSemanticNegotiatedMax);
5948 break;
5949 case cricket::kMsidSignalingMediaSection |
5950 cricket::kMsidSignalingSsrcAttribute:
5951 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5952 kSdpSemanticNegotiatedMixed,
5953 kSdpSemanticNegotiatedMax);
5954 break;
5955 default:
5956 RTC_NOTREACHED();
5957 }
5958}
5959
Steve Anton75737c02017-11-06 10:37:17 -08005960// We need to check the local/remote description for the Transport instead of
5961// the session, because a new Transport added during renegotiation may have
5962// them unset while the session has them set from the previous negotiation.
5963// Not doing so may trigger the auto generation of transport description and
5964// mess up DTLS identity information, ICE credential, etc.
5965bool PeerConnection::ReadyToUseRemoteCandidate(
5966 const IceCandidateInterface* candidate,
5967 const SessionDescriptionInterface* remote_desc,
5968 bool* valid) {
5969 *valid = true;
5970
5971 const SessionDescriptionInterface* current_remote_desc =
5972 remote_desc ? remote_desc : remote_description();
5973
5974 if (!current_remote_desc) {
5975 return false;
5976 }
5977
5978 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5979 size_t remote_content_size =
5980 current_remote_desc->description()->contents().size();
5981 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005982 RTC_LOG(LS_ERROR)
5983 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5984 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005985
5986 *valid = false;
5987 return false;
5988 }
5989
5990 cricket::ContentInfo content =
5991 current_remote_desc->description()->contents()[mediacontent_index];
5992
5993 const std::string transport_name = GetTransportName(content.name);
5994 if (transport_name.empty()) {
5995 return false;
5996 }
Zhi Huange830e682018-03-30 10:48:35 -07005997 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005998}
5999
6000bool PeerConnection::SrtpRequired() const {
6001 return dtls_enabled_ ||
6002 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6003}
6004
6005void PeerConnection::OnTransportControllerGatheringState(
6006 cricket::IceGatheringState state) {
6007 RTC_DCHECK(signaling_thread()->IsCurrent());
6008 if (state == cricket::kIceGatheringGathering) {
6009 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6010 } else if (state == cricket::kIceGatheringComplete) {
6011 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6012 }
6013}
6014
6015void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006016 std::map<std::string, std::set<cricket::MediaType>>
6017 media_types_by_transport_name;
6018 for (auto transceiver : transceivers_) {
6019 if (transceiver->internal()->channel()) {
6020 const std::string& transport_name =
6021 transceiver->internal()->channel()->transport_name();
6022 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006023 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006024 }
Steve Anton75737c02017-11-06 10:37:17 -08006025 }
6026 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006027 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6028 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006029 }
Zhi Huange830e682018-03-30 10:48:35 -07006030
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006031 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006032 if (transport_name) {
6033 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006034 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006035 }
Zhi Huange830e682018-03-30 10:48:35 -07006036
Steve Antonc7b964c2018-02-01 14:39:45 -08006037 for (const auto& entry : media_types_by_transport_name) {
6038 const std::string& transport_name = entry.first;
6039 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006040 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006041 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006042 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006043 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006044 }
6045 }
6046}
6047// Walk through the ConnectionInfos to gather best connection usage
6048// for IPv4 and IPv6.
6049void PeerConnection::ReportBestConnectionState(
6050 const cricket::TransportStats& stats) {
6051 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006052 for (const cricket::TransportChannelStats& channel_stats :
6053 stats.channel_stats) {
6054 for (const cricket::ConnectionInfo& connection_info :
6055 channel_stats.connection_infos) {
6056 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006057 continue;
6058 }
6059
6060 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006061 const cricket::Candidate& local = connection_info.local_candidate;
6062 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006063
6064 // Increment the counter for IceCandidatePairType.
6065 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6066 (local.type() == RELAY_PORT_TYPE &&
6067 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6068 type = kEnumCounterIceCandidatePairTypeTcp;
6069 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6070 type = kEnumCounterIceCandidatePairTypeUdp;
6071 } else {
6072 RTC_CHECK(0);
6073 }
6074 metrics_observer()->IncrementEnumCounter(
6075 type, GetIceCandidatePairCounter(local, remote),
6076 kIceCandidatePairMax);
6077
6078 // Increment the counter for IP type.
6079 if (local.address().family() == AF_INET) {
6080 metrics_observer()->IncrementEnumCounter(
6081 kEnumCounterAddressFamily, kBestConnections_IPv4,
6082 kPeerConnectionAddressFamilyCounter_Max);
6083
6084 } else if (local.address().family() == AF_INET6) {
6085 metrics_observer()->IncrementEnumCounter(
6086 kEnumCounterAddressFamily, kBestConnections_IPv6,
6087 kPeerConnectionAddressFamilyCounter_Max);
6088 } else {
6089 RTC_CHECK(0);
6090 }
6091
6092 return;
6093 }
6094 }
6095}
6096
6097void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006098 const cricket::TransportStats& stats,
6099 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006100 RTC_DCHECK(metrics_observer());
6101 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6102 return;
6103 }
6104
6105 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6106 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6107 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6108 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6109 return;
6110 }
6111
Steve Antonc7b964c2018-02-01 14:39:45 -08006112 for (cricket::MediaType media_type : media_types) {
6113 PeerConnectionEnumCounterType srtp_counter_type;
6114 PeerConnectionEnumCounterType ssl_counter_type;
6115 switch (media_type) {
6116 case cricket::MEDIA_TYPE_AUDIO:
6117 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6118 ssl_counter_type = kEnumCounterAudioSslCipher;
6119 break;
6120 case cricket::MEDIA_TYPE_VIDEO:
6121 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6122 ssl_counter_type = kEnumCounterVideoSslCipher;
6123 break;
6124 case cricket::MEDIA_TYPE_DATA:
6125 srtp_counter_type = kEnumCounterDataSrtpCipher;
6126 ssl_counter_type = kEnumCounterDataSslCipher;
6127 break;
6128 default:
6129 RTC_NOTREACHED();
6130 continue;
6131 }
6132 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6133 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6134 srtp_crypto_suite);
6135 }
6136 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6137 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6138 ssl_cipher_suite);
6139 }
Steve Anton75737c02017-11-06 10:37:17 -08006140 }
6141}
6142
6143void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6144 RTC_DCHECK(worker_thread()->IsCurrent());
6145 RTC_DCHECK(call_);
6146 call_->OnSentPacket(sent_packet);
6147}
6148
6149const std::string PeerConnection::GetTransportName(
6150 const std::string& content_name) {
6151 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006152 if (channel) {
6153 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006154 }
Steve Anton6fec8802017-12-04 10:37:29 -08006155 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006156 RTC_DCHECK(sctp_mid_);
6157 if (content_name == *sctp_mid_) {
6158 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006159 }
6160 }
6161 // Return an empty string if failed to retrieve the transport name.
6162 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006163}
6164
Steve Anton6fec8802017-12-04 10:37:29 -08006165void PeerConnection::DestroyTransceiverChannel(
6166 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6167 transceiver) {
6168 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006169
Steve Anton6fec8802017-12-04 10:37:29 -08006170 cricket::BaseChannel* channel = transceiver->internal()->channel();
6171 if (channel) {
6172 transceiver->internal()->SetChannel(nullptr);
6173 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006174 }
6175}
6176
6177void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006178 if (rtp_data_channel_) {
6179 OnDataChannelDestroyed();
6180 DestroyBaseChannel(rtp_data_channel_);
6181 rtp_data_channel_ = nullptr;
6182 }
6183
6184 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6185 // grab a reference to this PeerConnection. If this is called from the
6186 // PeerConnection destructor, the RefCountedObject vtable will have already
6187 // been destroyed (since it is a subclass of PeerConnection) and using
6188 // rtc::Bind will cause "Pure virtual function called" error to appear.
6189
6190 if (sctp_transport_) {
6191 OnDataChannelDestroyed();
6192 network_thread()->Invoke<void>(RTC_FROM_HERE,
6193 [this] { DestroySctpTransport_n(); });
6194 }
6195}
6196
6197void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6198 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006199 switch (channel->media_type()) {
6200 case cricket::MEDIA_TYPE_AUDIO:
6201 channel_manager()->DestroyVoiceChannel(
6202 static_cast<cricket::VoiceChannel*>(channel));
6203 break;
6204 case cricket::MEDIA_TYPE_VIDEO:
6205 channel_manager()->DestroyVideoChannel(
6206 static_cast<cricket::VideoChannel*>(channel));
6207 break;
6208 case cricket::MEDIA_TYPE_DATA:
6209 channel_manager()->DestroyRtpDataChannel(
6210 static_cast<cricket::RtpDataChannel*>(channel));
6211 break;
6212 default:
6213 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6214 break;
6215 }
Zhi Huange830e682018-03-30 10:48:35 -07006216}
Steve Anton6fec8802017-12-04 10:37:29 -08006217
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006218bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006219 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006220 RtpTransportInternal* rtp_transport,
6221 cricket::DtlsTransportInternal* dtls_transport) {
6222 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006223 auto base_channel = GetChannel(mid);
6224 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006225 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006226 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006227 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006228 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006229 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006230 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006231}
6232
Harald Alvestrand89061872018-01-02 14:08:34 +01006233void PeerConnection::ClearStatsCache() {
6234 if (stats_collector_) {
6235 stats_collector_->ClearCachedStatsReport();
6236 }
6237}
6238
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006239} // namespace webrtc