blob: a75585cfdf2a74b748c04f56b3f094c24099ad1a [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
Niels Mollerec4a0602018-08-27 11:26:30 +000023#include "api/mediaconstraintsinterface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
26#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070055#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
Steve Anton75737c02017-11-06 10:37:17 -080057using cricket::ContentInfo;
58using cricket::ContentInfos;
59using cricket::MediaContentDescription;
60using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080062using cricket::TransportInfo;
63
64using cricket::LOCAL_PORT_TYPE;
65using cricket::STUN_PORT_TYPE;
66using cricket::RELAY_PORT_TYPE;
67using cricket::PRFLX_PORT_TYPE;
68
Steve Antonba818672017-11-06 10:21:57 -080069namespace webrtc {
70
Steve Anton75737c02017-11-06 10:37:17 -080071// Error messages
72const char kBundleWithoutRtcpMux[] =
73 "rtcp-mux must be enabled when BUNDLE "
74 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080075const char kInvalidCandidates[] = "Description contains invalid candidates.";
76const char kInvalidSdp[] = "Invalid session description.";
77const char kMlineMismatchInAnswer[] =
78 "The order of m-lines in answer doesn't match order in offer. Rejecting "
79 "answer.";
80const char kMlineMismatchInSubsequentOffer[] =
81 "The order of m-lines in subsequent offer doesn't match order from "
82 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080083const char kSdpWithoutDtlsFingerprint[] =
84 "Called with SDP without DTLS fingerprint.";
85const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
86const char kSdpWithoutIceUfragPwd[] =
87 "Called with SDP without ice-ufrag and ice-pwd.";
88const char kSessionError[] = "Session error code: ";
89const char kSessionErrorDesc[] = "Session error description: ";
90const char kDtlsSrtpSetupFailureRtp[] =
91 "Couldn't set up DTLS-SRTP on RTP channel.";
92const char kDtlsSrtpSetupFailureRtcp[] =
93 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
Steve Anton75737c02017-11-06 10:37:17 -080095namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096
Seth Hampson845e8782018-03-02 11:34:10 -080097static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080098static const char kDefaultAudioSenderId[] = "defaulta0";
99static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700100
zhihuang8f65cdf2016-05-06 18:40:30 -0700101// The length of RTCP CNAMEs.
102static const int kRtcpCnameLength = 16;
103
Harald Alvestrand19793842018-06-25 12:03:50 +0200104static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
105
deadbeefab9b2d12015-10-14 11:33:11 -0700106// Check if we can send |new_stream| on a PeerConnection.
107bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
108 webrtc::MediaStreamInterface* new_stream) {
109 if (!new_stream || !current_streams) {
110 return false;
111 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700112 if (current_streams->find(new_stream->id()) != nullptr) {
113 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100114 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700115 return false;
116 }
117 return true;
118}
119
deadbeef5e97fb52015-10-15 12:49:08 -0700120// If the direction is "recvonly" or "inactive", treat the description
121// as containing no streams.
122// See: https://code.google.com/p/webrtc/issues/detail?id=5054
123std::vector<cricket::StreamParams> GetActiveStreams(
124 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800125 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700126 ? desc->streams()
127 : std::vector<cricket::StreamParams>();
128}
129
deadbeefab9b2d12015-10-14 11:33:11 -0700130bool IsValidOfferToReceiveMedia(int value) {
131 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
132 return (value >= Options::kUndefined) &&
133 (value <= Options::kMaxOfferToReceiveMedia);
134}
135
zhihuang1c378ed2017-08-17 14:10:50 -0700136// Add options to |[audio/video]_media_description_options| from |senders|.
137void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700138 const std::vector<rtc::scoped_refptr<
139 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700140 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200141 cricket::MediaDescriptionOptions* video_media_description_options,
142 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700143 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700144 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
145 if (audio_media_description_options) {
146 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700147 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700148 }
149 } else {
150 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
151 if (video_media_description_options) {
152 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200153 sender->id(), sender->internal()->stream_ids(),
154 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700155 }
156 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700157 }
zhihuang1c378ed2017-08-17 14:10:50 -0700158}
olka3c747662017-08-17 06:50:32 -0700159
zhihuang1c378ed2017-08-17 14:10:50 -0700160// Add options to |session_options| from |rtp_data_channels|.
161void AddRtpDataChannelOptions(
162 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
163 rtp_data_channels,
164 cricket::MediaDescriptionOptions* data_media_description_options) {
165 if (!data_media_description_options) {
166 return;
167 }
deadbeefab9b2d12015-10-14 11:33:11 -0700168 // Check for data channels.
169 for (const auto& kv : rtp_data_channels) {
170 const DataChannel* channel = kv.second;
171 if (channel->state() == DataChannel::kConnecting ||
172 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700173 // Legacy RTP data channels are signaled with the track/stream ID set to
174 // the data channel's label.
175 data_media_description_options->AddRtpDataChannel(channel->label(),
176 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700177 }
178 }
179}
180
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700181uint32_t ConvertIceTransportTypeToCandidateFilter(
182 PeerConnectionInterface::IceTransportsType type) {
183 switch (type) {
184 case PeerConnectionInterface::kNone:
185 return cricket::CF_NONE;
186 case PeerConnectionInterface::kRelay:
187 return cricket::CF_RELAY;
188 case PeerConnectionInterface::kNoHost:
189 return (cricket::CF_ALL & ~cricket::CF_HOST);
190 case PeerConnectionInterface::kAll:
191 return cricket::CF_ALL;
192 default:
nissec80e7412017-01-11 05:56:46 -0800193 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700194 }
195 return cricket::CF_NONE;
196}
197
deadbeef293e9262017-01-11 12:28:30 -0800198// Helper to set an error and return from a method.
199bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
200 if (error) {
201 error->set_type(type);
202 }
203 return type == webrtc::RTCErrorType::NONE;
204}
205
Steve Anton038834f2017-07-14 15:59:59 -0700206bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700207 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700208 if (error_out) {
209 *error_out = std::move(error);
210 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700211 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700212}
213
Steve Antonba818672017-11-06 10:21:57 -0800214std::string GetSignalingStateString(
215 PeerConnectionInterface::SignalingState state) {
216 switch (state) {
217 case PeerConnectionInterface::kStable:
218 return "kStable";
219 case PeerConnectionInterface::kHaveLocalOffer:
220 return "kHaveLocalOffer";
221 case PeerConnectionInterface::kHaveLocalPrAnswer:
222 return "kHavePrAnswer";
223 case PeerConnectionInterface::kHaveRemoteOffer:
224 return "kHaveRemoteOffer";
225 case PeerConnectionInterface::kHaveRemotePrAnswer:
226 return "kHaveRemotePrAnswer";
227 case PeerConnectionInterface::kClosed:
228 return "kClosed";
229 }
230 RTC_NOTREACHED();
231 return "";
232}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700233
Steve Anton75737c02017-11-06 10:37:17 -0800234IceCandidatePairType GetIceCandidatePairCounter(
235 const cricket::Candidate& local,
236 const cricket::Candidate& remote) {
237 const auto& l = local.type();
238 const auto& r = remote.type();
239 const auto& host = LOCAL_PORT_TYPE;
240 const auto& srflx = STUN_PORT_TYPE;
241 const auto& relay = RELAY_PORT_TYPE;
242 const auto& prflx = PRFLX_PORT_TYPE;
243 if (l == host && r == host) {
244 bool local_private = IPIsPrivate(local.address().ipaddr());
245 bool remote_private = IPIsPrivate(remote.address().ipaddr());
246 if (local_private) {
247 if (remote_private) {
248 return kIceCandidatePairHostPrivateHostPrivate;
249 } else {
250 return kIceCandidatePairHostPrivateHostPublic;
251 }
252 } else {
253 if (remote_private) {
254 return kIceCandidatePairHostPublicHostPrivate;
255 } else {
256 return kIceCandidatePairHostPublicHostPublic;
257 }
258 }
259 }
260 if (l == host && r == srflx)
261 return kIceCandidatePairHostSrflx;
262 if (l == host && r == relay)
263 return kIceCandidatePairHostRelay;
264 if (l == host && r == prflx)
265 return kIceCandidatePairHostPrflx;
266 if (l == srflx && r == host)
267 return kIceCandidatePairSrflxHost;
268 if (l == srflx && r == srflx)
269 return kIceCandidatePairSrflxSrflx;
270 if (l == srflx && r == relay)
271 return kIceCandidatePairSrflxRelay;
272 if (l == srflx && r == prflx)
273 return kIceCandidatePairSrflxPrflx;
274 if (l == relay && r == host)
275 return kIceCandidatePairRelayHost;
276 if (l == relay && r == srflx)
277 return kIceCandidatePairRelaySrflx;
278 if (l == relay && r == relay)
279 return kIceCandidatePairRelayRelay;
280 if (l == relay && r == prflx)
281 return kIceCandidatePairRelayPrflx;
282 if (l == prflx && r == host)
283 return kIceCandidatePairPrflxHost;
284 if (l == prflx && r == srflx)
285 return kIceCandidatePairPrflxSrflx;
286 if (l == prflx && r == relay)
287 return kIceCandidatePairPrflxRelay;
288 return kIceCandidatePairMax;
289}
290
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800291// Logic to decide if an m= section can be recycled. This means that the new
292// m= section is not rejected, but the old local or remote m= section is
293// rejected. |old_content_one| and |old_content_two| refer to the m= section
294// of the old remote and old local descriptions in no particular order.
295// We need to check both the old local and remote because either
296// could be the most current from the latest negotation.
297bool IsMediaSectionBeingRecycled(SdpType type,
298 const ContentInfo& content,
299 const ContentInfo* old_content_one,
300 const ContentInfo* old_content_two) {
301 return type == SdpType::kOffer && !content.rejected &&
302 ((old_content_one && old_content_one->rejected) ||
303 (old_content_two && old_content_two->rejected));
304}
305
Steve Anton75737c02017-11-06 10:37:17 -0800306// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800307// |current_desc|. The number of m= sections in |new_desc| should be no
308// less than |current_desc|. In the case of checking an answer's
309// |new_desc|, the |current_desc| is the last offer that was set as the
310// local or remote. In the case of checking an offer's |new_desc| we
311// check against the local and remote descriptions stored from the last
312// negotiation, because either of these could be the most up to date for
313// possible rejected m sections. These are the |current_desc| and
314// |secondary_current_desc|.
315bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
316 const SessionDescription* secondary_current_desc,
317 const SessionDescription& new_desc,
318 const SdpType type) {
319 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800320 return false;
321 }
322
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800323 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
324 const cricket::ContentInfo* secondary_content_info = nullptr;
325 if (secondary_current_desc &&
326 i < secondary_current_desc->contents().size()) {
327 secondary_content_info = &secondary_current_desc->contents()[i];
328 }
329 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
330 &current_desc.contents()[i],
331 secondary_content_info)) {
332 // For new offer descriptions, if the media section can be recycled, it's
333 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800334 continue;
335 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800336 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800337 return false;
338 }
339 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800340 new_desc.contents()[i].media_description();
341 const MediaContentDescription* current_desc_mdesc =
342 current_desc.contents()[i].media_description();
343 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800344 return false;
345 }
346 }
347 return true;
348}
349
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800350bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
351 const SessionDescription& desc2) {
352 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800353}
354
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700355void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
356 cricket::MediaType media_type) {
357 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
358 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100359 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
360 KeyExchangeProtocolMedia>
361 proto_media_counter_map = {
362 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
363 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
364 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
365 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
366 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
367 kEnumCounterKeyProtocolMediaTypeDtlsData},
368 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
369 kEnumCounterKeyProtocolMediaTypeSdesAudio},
370 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
371 kEnumCounterKeyProtocolMediaTypeSdesVideo},
372 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
373 kEnumCounterKeyProtocolMediaTypeSdesData}};
374
375 auto it = proto_media_counter_map.find({protocol_type, media_type});
376 if (it != proto_media_counter_map.end()) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700377 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
378 it->second, kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100379 }
380}
381
Harald Alvestrand76829d72018-07-18 23:24:36 +0200382void NoteAddIceCandidateResult(int result) {
383 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
384 kAddIceCandidateMax);
385}
386
Steve Anton75737c02017-11-06 10:37:17 -0800387// Checks that each non-rejected content has SDES crypto keys or a DTLS
388// fingerprint, unless it's in a BUNDLE group, in which case only the
389// BUNDLE-tag section (first media section/description in the BUNDLE group)
390// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
391// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
392// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700393RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800394 const cricket::ContentGroup* bundle =
395 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800396 for (const cricket::ContentInfo& content_info : desc->contents()) {
397 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800398 continue;
399 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100400 // Note what media is used with each crypto protocol, for all sections.
401 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
402 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700403 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800404 const std::string& mid = content_info.name;
405 if (bundle && bundle->HasContentName(mid) &&
406 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800407 // This isn't the first media section in the BUNDLE group, so it's not
408 // required to have crypto attributes, since only the crypto attributes
409 // from the first section actually get used.
410 continue;
411 }
412
413 // If the content isn't rejected or bundled into another m= section, crypto
414 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800415 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800416 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800417 if (!media || !tinfo) {
418 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800419 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800420 }
421 if (dtls_enabled) {
422 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100423 RTC_LOG(LS_WARNING)
424 << "Session description must have DTLS fingerprint if "
425 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800426 return RTCError(RTCErrorType::INVALID_PARAMETER,
427 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800428 }
429 } else {
430 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100431 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800432 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800433 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800434 }
435 }
436 }
Steve Anton8a006912017-12-04 15:25:56 -0800437 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800438}
439
440// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
441// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
442// media section/description in the BUNDLE group) needs a ufrag and pwd.
443bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
444 const cricket::ContentGroup* bundle =
445 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800446 for (const cricket::ContentInfo& content_info : desc->contents()) {
447 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800448 continue;
449 }
Steve Anton8a006912017-12-04 15:25:56 -0800450 const std::string& mid = content_info.name;
451 if (bundle && bundle->HasContentName(mid) &&
452 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800453 // This isn't the first media section in the BUNDLE group, so it's not
454 // required to have ufrag/password, since only the ufrag/password from
455 // the first section actually get used.
456 continue;
457 }
458
459 // If the content isn't rejected or bundled into another m= section,
460 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800462 if (!tinfo) {
463 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100464 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800465 return false;
466 }
467 if (tinfo->description.ice_ufrag.empty() ||
468 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100469 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800470 return false;
471 }
472 }
473 return true;
474}
475
476bool GetTrackIdBySsrc(const SessionDescription* session_description,
477 uint32_t ssrc,
478 std::string* track_id) {
479 RTC_DCHECK(track_id != NULL);
480
Steve Antonb1c1de12017-12-21 15:14:30 -0800481 const cricket::AudioContentDescription* audio_desc =
482 cricket::GetFirstAudioContentDescription(session_description);
483 if (audio_desc) {
484 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800485 if (found) {
486 *track_id = found->id;
487 return true;
488 }
489 }
490
Steve Antonb1c1de12017-12-21 15:14:30 -0800491 const cricket::VideoContentDescription* video_desc =
492 cricket::GetFirstVideoContentDescription(session_description);
493 if (video_desc) {
494 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800495 if (found) {
496 *track_id = found->id;
497 return true;
498 }
499 }
500 return false;
501}
502
503// Get the SCTP port out of a SessionDescription.
504// Return -1 if not found.
505int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800506 const cricket::DataContentDescription* data_desc =
507 GetFirstDataContentDescription(session_description);
508 RTC_DCHECK(data_desc);
509 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800510 return -1;
511 }
Steve Anton75737c02017-11-06 10:37:17 -0800512 std::string value;
513 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
514 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800516 if (!codec.Matches(match_pattern)) {
517 continue;
518 }
519 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
520 return rtc::FromString<int>(value);
521 }
522 }
523 return -1;
524}
525
Steve Anton75737c02017-11-06 10:37:17 -0800526// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
527bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
528 const SessionDescriptionInterface* new_desc,
529 const std::string& content_name) {
530 if (!old_desc) {
531 return false;
532 }
533 const SessionDescription* new_sd = new_desc->description();
534 const SessionDescription* old_sd = old_desc->description();
535 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
536 if (!cinfo || cinfo->rejected) {
537 return false;
538 }
539 // If the content isn't rejected, check if ufrag and password has changed.
540 const cricket::TransportDescription* new_transport_desc =
541 new_sd->GetTransportDescriptionByName(content_name);
542 const cricket::TransportDescription* old_transport_desc =
543 old_sd->GetTransportDescriptionByName(content_name);
544 if (!new_transport_desc || !old_transport_desc) {
545 // No transport description exists. This is not an ICE restart.
546 return false;
547 }
548 if (cricket::IceCredentialsChanged(
549 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
550 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100551 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
552 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800553 return true;
554 }
555 return false;
556}
557
Steve Anton80dd7b52018-02-16 17:08:42 -0800558// Generates a string error message for SetLocalDescription/SetRemoteDescription
559// from an RTCError.
560std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
561 SdpType type,
562 const RTCError& error) {
563 std::ostringstream oss;
564 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
565 << " " << SdpTypeToString(type) << " sdp: " << error.message();
566 return oss.str();
567}
568
Seth Hampson5b4f0752018-04-02 16:31:36 -0700569std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
570 std::string output = "streams=[";
571 const char* separator = "";
572 for (const auto& stream_id : stream_ids) {
573 output.append(separator).append(stream_id);
574 separator = ", ";
575 }
576 output.append("]");
577 return output;
578}
579
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200580absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700581 int rtc_configuration_parameter) {
582 if (rtc_configuration_parameter ==
583 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200584 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700585 }
586 return rtc_configuration_parameter;
587}
588
Steve Anton75737c02017-11-06 10:37:17 -0800589} // namespace
590
Henrik Boström31638672017-11-23 17:48:32 +0100591// Upon completion, posts a task to execute the callback of the
592// SetSessionDescriptionObserver asynchronously on the same thread. At this
593// point, the state of the peer connection might no longer reflect the effects
594// of the SetRemoteDescription operation, as the peer connection could have been
595// modified during the post.
596// TODO(hbos): Remove this class once we remove the version of
597// PeerConnectionInterface::SetRemoteDescription() that takes a
598// SetSessionDescriptionObserver as an argument.
599class PeerConnection::SetRemoteDescriptionObserverAdapter
600 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
601 public:
602 SetRemoteDescriptionObserverAdapter(
603 rtc::scoped_refptr<PeerConnection> pc,
604 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
605 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
606
607 // SetRemoteDescriptionObserverInterface implementation.
608 void OnSetRemoteDescriptionComplete(RTCError error) override {
609 if (error.ok())
610 pc_->PostSetSessionDescriptionSuccess(wrapper_);
611 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100612 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100613 }
614
615 private:
616 rtc::scoped_refptr<PeerConnection> pc_;
617 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
618};
619
deadbeef293e9262017-01-11 12:28:30 -0800620bool PeerConnectionInterface::RTCConfiguration::operator==(
621 const PeerConnectionInterface::RTCConfiguration& o) const {
622 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700623 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800624 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000625 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700626 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800627 BundlePolicy bundle_policy;
628 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700629 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
630 int ice_candidate_pool_size;
631 bool disable_ipv6;
632 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700633 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100634 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700635 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200636 absl::optional<int> screencast_min_bitrate;
637 absl::optional<bool> combined_audio_video_bwe;
638 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800639 TcpCandidatePolicy tcp_candidate_policy;
640 CandidateNetworkPolicy candidate_network_policy;
641 int audio_jitter_buffer_max_packets;
642 bool audio_jitter_buffer_fast_accelerate;
643 int ice_connection_receiving_timeout;
644 int ice_backup_candidate_pair_ping_interval;
645 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800646 bool prioritize_most_likely_ice_candidate_pairs;
647 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800648 bool prune_turn_ports;
649 bool presume_writable_when_fully_relayed;
650 bool enable_ice_renomination;
651 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200652 absl::optional<int> ice_check_interval_strong_connectivity;
653 absl::optional<int> ice_check_interval_weak_connectivity;
654 absl::optional<int> ice_check_min_interval;
655 absl::optional<int> ice_unwritable_timeout;
656 absl::optional<int> ice_unwritable_min_checks;
657 absl::optional<int> stun_candidate_keepalive_interval;
658 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200659 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800660 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200661 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700662 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800663 };
664 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
665 "Did you add something to RTCConfiguration and forget to "
666 "update operator==?");
667 return type == o.type && servers == o.servers &&
668 bundle_policy == o.bundle_policy &&
669 rtcp_mux_policy == o.rtcp_mux_policy &&
670 tcp_candidate_policy == o.tcp_candidate_policy &&
671 candidate_network_policy == o.candidate_network_policy &&
672 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
673 audio_jitter_buffer_fast_accelerate ==
674 o.audio_jitter_buffer_fast_accelerate &&
675 ice_connection_receiving_timeout ==
676 o.ice_connection_receiving_timeout &&
677 ice_backup_candidate_pair_ping_interval ==
678 o.ice_backup_candidate_pair_ping_interval &&
679 continual_gathering_policy == o.continual_gathering_policy &&
680 certificates == o.certificates &&
681 prioritize_most_likely_ice_candidate_pairs ==
682 o.prioritize_most_likely_ice_candidate_pairs &&
683 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800684 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700685 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100686 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800687 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800688 screencast_min_bitrate == o.screencast_min_bitrate &&
689 combined_audio_video_bwe == o.combined_audio_video_bwe &&
690 enable_dtls_srtp == o.enable_dtls_srtp &&
691 ice_candidate_pool_size == o.ice_candidate_pool_size &&
692 prune_turn_ports == o.prune_turn_ports &&
693 presume_writable_when_fully_relayed ==
694 o.presume_writable_when_fully_relayed &&
695 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800696 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800697 ice_check_interval_strong_connectivity ==
698 o.ice_check_interval_strong_connectivity &&
699 ice_check_interval_weak_connectivity ==
700 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700701 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700702 ice_unwritable_timeout == o.ice_unwritable_timeout &&
703 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800704 stun_candidate_keepalive_interval ==
705 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200706 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800707 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800708 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700709 network_preference == o.network_preference &&
710 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800711}
712
713bool PeerConnectionInterface::RTCConfiguration::operator!=(
714 const PeerConnectionInterface::RTCConfiguration& o) const {
715 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800716}
717
zhihuang8f65cdf2016-05-06 18:40:30 -0700718// Generate a RTCP CNAME when a PeerConnection is created.
719std::string GenerateRtcpCname() {
720 std::string cname;
721 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100722 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800723 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700724 }
725 return cname;
726}
727
zhihuang1c378ed2017-08-17 14:10:50 -0700728bool ValidateOfferAnswerOptions(
729 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
730 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
731 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700732}
733
zhihuang1c378ed2017-08-17 14:10:50 -0700734// From |rtc_options|, fill parts of |session_options| shared by all generated
735// m= sections (in other words, nothing that involves a map/array).
736void ExtractSharedMediaSessionOptions(
737 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
738 cricket::MediaSessionOptions* session_options) {
739 session_options->vad_enabled = rtc_options.voice_activity_detection;
740 session_options->bundle_enabled = rtc_options.use_rtp_mux;
741}
zhihuanga77e6bb2017-08-14 18:17:48 -0700742
zhihuang38ede132017-06-15 12:52:32 -0700743PeerConnection::PeerConnection(PeerConnectionFactory* factory,
744 std::unique_ptr<RtcEventLog> event_log,
745 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700747 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700748 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700749 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700750 remote_streams_(StreamCollection::Create()),
751 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000752
753PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100754 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800755 RTC_DCHECK_RUN_ON(signaling_thread());
756
Steve Anton8af21862017-12-15 11:20:13 -0800757 // Need to stop transceivers before destroying the stats collector because
758 // AudioRtpSender has a reference to the StatsCollector it will update when
759 // stopping.
760 for (auto transceiver : transceivers_) {
761 transceiver->Stop();
762 }
Steve Anton4171afb2017-11-20 10:20:22 -0800763
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700764 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800765 if (stats_collector_) {
766 stats_collector_->WaitForPendingRequest();
767 stats_collector_ = nullptr;
768 }
Steve Anton75737c02017-11-06 10:37:17 -0800769
Steve Anton8af21862017-12-15 11:20:13 -0800770 // Don't destroy BaseChannels until after stats has been cleaned up so that
771 // the last stats request can still read from the channels.
772 DestroyAllChannels();
773
Mirko Bonadei675513b2017-11-09 11:09:25 +0100774 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800775
776 webrtc_session_desc_factory_.reset();
777 sctp_invoker_.reset();
778 sctp_factory_.reset();
779 transport_controller_.reset();
780
deadbeef91dd5672016-05-18 16:55:30 -0700781 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700782 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700783 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700784 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700785 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700786 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800787 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700788 event_log_.reset();
789 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000790}
791
Steve Anton8af21862017-12-15 11:20:13 -0800792void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800793 // Destroy video channels first since they may have a pointer to a voice
794 // channel.
795 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800796 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800797 DestroyTransceiverChannel(transceiver);
798 }
799 }
800 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800801 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800802 DestroyTransceiverChannel(transceiver);
803 }
804 }
805 DestroyDataChannel();
806}
807
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000809 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700810 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100811 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700812
813 RTCError config_error = ValidateConfiguration(configuration);
814 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100815 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700816 return false;
817 }
818
Benjamin Wrightcab58882018-05-02 15:12:47 -0700819 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100820 RTC_LOG(LS_ERROR)
821 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100822 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800823 return false;
824 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200825
Benjamin Wrightcab58882018-05-02 15:12:47 -0700826 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800827 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100828 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100829 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800830 return false;
831 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700832
Benjamin Wrightcab58882018-05-02 15:12:47 -0700833 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700834 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700835 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700836 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800837
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200838 cricket::ServerAddresses stun_servers;
839 std::vector<cricket::RelayServerConfig> turn_servers;
840
841 RTCErrorType parse_error =
842 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
843 if (parse_error != RTCErrorType::NONE) {
844 return false;
845 }
846
deadbeef91dd5672016-05-18 16:55:30 -0700847 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700848 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700849 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200850 RTC_FROM_HERE,
851 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
852 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000853 return false;
854 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200855 // If initialization was successful, note if STUN or TURN servers
856 // were supplied.
857 if (!stun_servers.empty()) {
858 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
859 }
860 if (!turn_servers.empty()) {
861 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
862 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000863
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700864 // Send information about IPv4/IPv6 status.
865 PeerConnectionAddressFamilyCounter address_family;
866 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
867 address_family = kPeerConnection_IPv6;
868 } else {
869 address_family = kPeerConnection_IPv4;
870 }
871 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
872 kPeerConnectionAddressFamilyCounter_Max);
873
Zhi Huange830e682018-03-30 10:48:35 -0700874 const PeerConnectionFactoryInterface::Options& options = factory_->options();
875
Steve Anton75737c02017-11-06 10:37:17 -0800876 // RFC 3264: The numeric value of the session id and version in the
877 // o line MUST be representable with a "64 bit signed integer".
878 // Due to this constraint session id |session_id_| is max limited to
879 // LLONG_MAX.
880 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700881 JsepTransportController::Config config;
882 config.redetermine_role_on_ice_restart =
883 configuration.redetermine_role_on_ice_restart;
884 config.ssl_max_version = factory_->options().ssl_max_version;
885 config.disable_encryption = options.disable_encryption;
886 config.bundle_policy = configuration.bundle_policy;
887 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
888 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700889 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700890 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700891#if defined(ENABLE_EXTERNAL_AUTH)
892 config.enable_external_auth = true;
893#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700894 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700895 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700896 signaling_thread(), network_thread(), port_allocator_.get(),
897 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700898 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800899 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700900 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800901 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700902 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800903 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700904 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800905 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
906 transport_controller_->SignalDtlsHandshakeError.connect(
907 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
908
909 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700910
deadbeefab9b2d12015-10-14 11:33:11 -0700911 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700912 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913
Steve Antonba818672017-11-06 10:21:57 -0800914 configuration_ = configuration;
915
Steve Anton75737c02017-11-06 10:37:17 -0800916 // Obtain a certificate from RTCConfiguration if any were provided (optional).
917 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
918 if (!configuration.certificates.empty()) {
919 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
920 // just picking the first one. The decision should be made based on the DTLS
921 // handshake. The DTLS negotiations need to know about all certificates.
922 certificate = configuration.certificates[0];
923 }
924
Steve Antond25da372017-11-06 14:50:29 -0800925 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800926
927 if (options.disable_encryption) {
928 dtls_enabled_ = false;
929 } else {
930 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700931 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800932 // |configuration| can override the default |dtls_enabled_| value.
933 if (configuration.enable_dtls_srtp) {
934 dtls_enabled_ = *(configuration.enable_dtls_srtp);
935 }
936 }
937
938 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
939 // It takes precendence over the disable_sctp_data_channels
940 // PeerConnectionFactoryInterface::Options.
941 if (configuration.enable_rtp_data_channel) {
942 data_channel_type_ = cricket::DCT_RTP;
943 } else {
944 // DTLS has to be enabled to use SCTP.
945 if (!options.disable_sctp_data_channels && dtls_enabled_) {
946 data_channel_type_ = cricket::DCT_SCTP;
947 }
948 }
949
950 video_options_.screencast_min_bitrate_kbps =
951 configuration.screencast_min_bitrate;
952 audio_options_.combined_audio_video_bwe =
953 configuration.combined_audio_video_bwe;
954
955 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100956 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800957
958 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100959 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800960
961 // Whether the certificate generator/certificate is null or not determines
962 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
963 // the right instructions by clearing the variables if needed.
964 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -0700965 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800966 certificate = nullptr;
967 } else if (certificate) {
968 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700969 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800970 }
971
972 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
973 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -0700974 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -0800975 webrtc_session_desc_factory_->SignalCertificateReady.connect(
976 this, &PeerConnection::OnCertificateReady);
977
978 if (options.disable_encryption) {
979 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
980 }
981
982 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
983 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984
Steve Anton4171afb2017-11-20 10:20:22 -0800985 // Add default audio/video transceivers for Plan B SDP.
986 if (!IsUnifiedPlan()) {
987 transceivers_.push_back(
988 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
989 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
990 transceivers_.push_back(
991 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
992 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
993 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +0200994 int delay_ms =
995 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonbb192762018-08-31 11:57:02 -0700996 async_invoker_.AsyncInvokeDelayed<void>(RTC_FROM_HERE, signaling_thread(),
997 [this] { ReportUsagePattern(); },
998 delay_ms);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999 return true;
1000}
1001
Steve Anton038834f2017-07-14 15:59:59 -07001002RTCError PeerConnection::ValidateConfiguration(
1003 const RTCConfiguration& config) const {
1004 if (config.ice_regather_interval_range &&
1005 config.continual_gathering_policy == GATHER_ONCE) {
1006 return RTCError(RTCErrorType::INVALID_PARAMETER,
1007 "ice_regather_interval_range specified but continual "
1008 "gathering policy is GATHER_ONCE");
1009 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001010 auto result =
1011 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1012 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001013}
1014
Yves Gerey665174f2018-06-19 15:03:05 +02001015rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001016 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1017 "Plan SdpSemantics. Please use GetSenders "
1018 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001019 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020}
1021
Yves Gerey665174f2018-06-19 15:03:05 +02001022rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001023 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1024 "Plan SdpSemantics. Please use GetReceivers "
1025 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001026 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027}
1028
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001029bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001030 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1031 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001032 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033 if (IsClosed()) {
1034 return false;
1035 }
deadbeefab9b2d12015-10-14 11:33:11 -07001036 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 return false;
1038 }
deadbeefab9b2d12015-10-14 11:33:11 -07001039
1040 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001041 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1042 observer->SignalAudioTrackAdded.connect(this,
1043 &PeerConnection::OnAudioTrackAdded);
1044 observer->SignalAudioTrackRemoved.connect(
1045 this, &PeerConnection::OnAudioTrackRemoved);
1046 observer->SignalVideoTrackAdded.connect(this,
1047 &PeerConnection::OnVideoTrackAdded);
1048 observer->SignalVideoTrackRemoved.connect(
1049 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001050 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001051
deadbeefab9b2d12015-10-14 11:33:11 -07001052 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001053 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001054 }
1055 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001056 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001057 }
1058
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001059 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001060 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061 return true;
1062}
1063
1064void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001065 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1066 "Plan SdpSemantics. Please use RemoveTrack "
1067 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001068 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001069 if (!IsClosed()) {
1070 for (const auto& track : local_stream->GetAudioTracks()) {
1071 RemoveAudioTrack(track.get(), local_stream);
1072 }
1073 for (const auto& track : local_stream->GetVideoTracks()) {
1074 RemoveVideoTrack(track.get(), local_stream);
1075 }
deadbeefab9b2d12015-10-14 11:33:11 -07001076 }
deadbeefab9b2d12015-10-14 11:33:11 -07001077 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001078 stream_observers_.erase(
1079 std::remove_if(
1080 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001081 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001082 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001083 }),
1084 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001085
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086 if (IsClosed()) {
1087 return;
1088 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001089 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090}
1091
Steve Anton2d6c76a2018-01-05 17:10:52 -08001092RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001093 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001094 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001095 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001096 if (!track) {
1097 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1098 }
1099 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1100 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1101 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1102 "Track has invalid kind: " + track->kind());
1103 }
Steve Antonf9381f02017-12-14 10:23:57 -08001104 if (IsClosed()) {
1105 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1106 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001107 }
Steve Anton4171afb2017-11-20 10:20:22 -08001108 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001109 LOG_AND_RETURN_ERROR(
1110 RTCErrorType::INVALID_PARAMETER,
1111 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001112 }
Steve Antonf9381f02017-12-14 10:23:57 -08001113 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001114 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1115 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001116 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001117 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001118 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001119 }
1120 return sender_or_error;
1121}
deadbeefe1f9d832016-01-14 15:35:42 -08001122
Steve Antonf9381f02017-12-14 10:23:57 -08001123RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1124PeerConnection::AddTrackPlanB(
1125 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001126 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001127 if (stream_ids.size() > 1u) {
1128 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1129 "AddTrack with more than one stream is not "
1130 "supported with Plan B semantics.");
1131 }
1132 std::vector<std::string> adjusted_stream_ids = stream_ids;
1133 if (adjusted_stream_ids.empty()) {
1134 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1135 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001136 cricket::MediaType media_type =
1137 (track->kind() == MediaStreamTrackInterface::kAudioKind
1138 ? cricket::MEDIA_TYPE_AUDIO
1139 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001140 auto new_sender =
1141 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001142 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001143 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001144 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001145 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001146 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001147 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001148 if (sender_info) {
1149 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001150 }
Steve Antonf9381f02017-12-14 10:23:57 -08001151 } else {
1152 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001153 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001154 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001155 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001156 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001157 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001158 if (sender_info) {
1159 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001160 }
deadbeefe1f9d832016-01-14 15:35:42 -08001161 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001162 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001163}
deadbeefe1f9d832016-01-14 15:35:42 -08001164
Steve Antonf9381f02017-12-14 10:23:57 -08001165RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1166PeerConnection::AddTrackUnifiedPlan(
1167 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001168 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001169 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1170 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001171 RTC_LOG(LS_INFO) << "Reusing an existing "
1172 << cricket::MediaTypeToString(transceiver->media_type())
1173 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001174 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001175 transceiver->internal()->set_direction(
1176 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001177 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001178 transceiver->internal()->set_direction(
1179 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001180 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001181 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001182 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001183 } else {
1184 cricket::MediaType media_type =
1185 (track->kind() == MediaStreamTrackInterface::kAudioKind
1186 ? cricket::MEDIA_TYPE_AUDIO
1187 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001188 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1189 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001190 std::string sender_id = track->id();
1191 // Avoid creating a sender with an existing ID by generating a random ID.
1192 // This can happen if this is the second time AddTrack has created a sender
1193 // for this track.
1194 if (FindSenderById(sender_id)) {
1195 sender_id = rtc::CreateRandomUuid();
1196 }
1197 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001198 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1199 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001200 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001201 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001202 }
Steve Antonf9381f02017-12-14 10:23:57 -08001203 return transceiver->sender();
1204}
1205
1206rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1207PeerConnection::FindFirstTransceiverForAddedTrack(
1208 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1209 RTC_DCHECK(track);
1210 for (auto transceiver : transceivers_) {
1211 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001212 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001213 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001214 !transceiver->internal()->has_ever_been_used_to_send() &&
1215 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001216 return transceiver;
1217 }
1218 }
1219 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001220}
1221
1222bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1223 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001224 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001225}
1226
Steve Anton24db5732018-07-23 10:27:33 -07001227RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001228 rtc::scoped_refptr<RtpSenderInterface> sender) {
1229 if (!sender) {
1230 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1231 }
deadbeefe1f9d832016-01-14 15:35:42 -08001232 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001233 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1234 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001235 }
Steve Antonf9381f02017-12-14 10:23:57 -08001236 if (IsUnifiedPlan()) {
1237 auto transceiver = FindTransceiverBySender(sender);
1238 if (!transceiver || !sender->track()) {
1239 return RTCError::OK();
1240 }
1241 sender->SetTrack(nullptr);
1242 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001243 transceiver->internal()->set_direction(
1244 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001245 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001246 transceiver->internal()->set_direction(
1247 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001248 }
Steve Anton4171afb2017-11-20 10:20:22 -08001249 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001250 bool removed;
1251 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1252 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1253 } else {
1254 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1255 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1256 }
1257 if (!removed) {
1258 LOG_AND_RETURN_ERROR(
1259 RTCErrorType::INVALID_PARAMETER,
1260 "Couldn't find sender " + sender->id() + " to remove.");
1261 }
Steve Anton4171afb2017-11-20 10:20:22 -08001262 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001263 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001264 return RTCError::OK();
1265}
1266
1267rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1268PeerConnection::FindTransceiverBySender(
1269 rtc::scoped_refptr<RtpSenderInterface> sender) {
1270 for (auto transceiver : transceivers_) {
1271 if (transceiver->sender() == sender) {
1272 return transceiver;
1273 }
1274 }
1275 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001276}
1277
Steve Anton9158ef62017-11-27 13:01:52 -08001278RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1279PeerConnection::AddTransceiver(
1280 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1281 return AddTransceiver(track, RtpTransceiverInit());
1282}
1283
1284RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1285PeerConnection::AddTransceiver(
1286 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1287 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001288 RTC_CHECK(IsUnifiedPlan())
1289 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001290 if (!track) {
1291 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1292 }
1293 cricket::MediaType media_type;
1294 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1295 media_type = cricket::MEDIA_TYPE_AUDIO;
1296 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1297 media_type = cricket::MEDIA_TYPE_VIDEO;
1298 } else {
1299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1300 "Track kind is not audio or video");
1301 }
1302 return AddTransceiver(media_type, track, init);
1303}
1304
1305RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1306PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1307 return AddTransceiver(media_type, RtpTransceiverInit());
1308}
1309
1310RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1311PeerConnection::AddTransceiver(cricket::MediaType media_type,
1312 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001313 RTC_CHECK(IsUnifiedPlan())
1314 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001315 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1316 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1318 "media type is not audio or video");
1319 }
1320 return AddTransceiver(media_type, nullptr, init);
1321}
1322
1323RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1324PeerConnection::AddTransceiver(
1325 cricket::MediaType media_type,
1326 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001327 const RtpTransceiverInit& init,
1328 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001329 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1330 media_type == cricket::MEDIA_TYPE_VIDEO));
1331 if (track) {
1332 RTC_DCHECK_EQ(media_type,
1333 (track->kind() == MediaStreamTrackInterface::kAudioKind
1334 ? cricket::MEDIA_TYPE_AUDIO
1335 : cricket::MEDIA_TYPE_VIDEO));
1336 }
1337
1338 // TODO(bugs.webrtc.org/7600): Verify init.
1339
Steve Anton3d954a62018-04-02 11:27:23 -07001340 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1341 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001342 // Set the sender ID equal to the track ID if the track is specified unless
1343 // that sender ID is already in use.
1344 std::string sender_id =
1345 (track && !FindSenderById(track->id()) ? track->id()
1346 : rtc::CreateRandomUuid());
1347 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001348 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1349 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1350 transceiver->internal()->set_direction(init.direction);
1351
Steve Anton22da89f2018-01-25 13:58:07 -08001352 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001353 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001354 }
Steve Antonf9381f02017-12-14 10:23:57 -08001355
1356 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1357}
1358
Steve Anton02ee47c2018-01-10 16:26:06 -08001359rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1360PeerConnection::CreateSender(
1361 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001362 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001363 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001364 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001365 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001366 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1367 RTC_DCHECK(!track ||
1368 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1369 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1370 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001371 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001372 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001373 } else {
1374 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1375 RTC_DCHECK(!track ||
1376 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1377 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001378 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001379 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001380 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001381 bool set_track_succeeded = sender->SetTrack(track);
1382 RTC_DCHECK(set_track_succeeded);
1383 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001384 return sender;
1385}
1386
1387rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1388PeerConnection::CreateReceiver(cricket::MediaType media_type,
1389 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001390 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1391 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001392 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001393 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001394 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1395 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001396 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001397 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001399 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001400 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1401 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001402 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001403 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001404 return receiver;
1405}
1406
1407rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1408PeerConnection::CreateAndAddTransceiver(
1409 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1410 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1411 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001412 // Ensure that the new sender does not have an ID that is already in use by
1413 // another sender.
1414 // Allow receiver IDs to conflict since those come from remote SDP (which
1415 // could be invalid, but should not cause a crash).
1416 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001417 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1418 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001419 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001420 transceiver->internal()->SignalNegotiationNeeded.connect(
1421 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001422 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001423}
1424
Steve Anton52d86772018-02-20 15:48:12 -08001425void PeerConnection::OnNegotiationNeeded() {
1426 RTC_DCHECK_RUN_ON(signaling_thread());
1427 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001428 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001429}
1430
deadbeeffac06552015-11-25 11:26:01 -08001431rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001432 const std::string& kind,
1433 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001434 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1435 "Plan SdpSemantics. Please use AddTransceiver "
1436 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001437 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001438 if (IsClosed()) {
1439 return nullptr;
1440 }
Steve Anton4171afb2017-11-20 10:20:22 -08001441
Seth Hampson5b4f0752018-04-02 16:31:36 -07001442 // Internally we need to have one stream with Plan B semantics, so we
1443 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001444 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001445 if (stream_id.empty()) {
1446 stream_ids.push_back(rtc::CreateRandomUuid());
1447 RTC_LOG(LS_INFO)
1448 << "No stream_id specified for sender. Generated stream ID: "
1449 << stream_ids[0];
1450 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001451 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001452 }
1453
Steve Anton4171afb2017-11-20 10:20:22 -08001454 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001455 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001456 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001457 auto* audio_sender = new AudioRtpSender(
1458 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001459 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001460 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001461 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001462 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001463 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001464 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001465 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001466 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001467 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001468 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001469 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001470 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001471 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001472 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001473 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001474 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001475
deadbeefe1f9d832016-01-14 15:35:42 -08001476 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001477}
1478
deadbeef70ab1a12015-09-28 16:53:55 -07001479std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1480 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001481 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001482 for (auto sender : GetSendersInternal()) {
1483 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001484 }
1485 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001486}
1487
Steve Anton4171afb2017-11-20 10:20:22 -08001488std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1489PeerConnection::GetSendersInternal() const {
1490 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1491 all_senders;
1492 for (auto transceiver : transceivers_) {
1493 auto senders = transceiver->internal()->senders();
1494 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1495 }
1496 return all_senders;
1497}
1498
deadbeef70ab1a12015-09-28 16:53:55 -07001499std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1500PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001501 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001502 for (const auto& receiver : GetReceiversInternal()) {
1503 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001504 }
1505 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001506}
1507
Steve Anton4171afb2017-11-20 10:20:22 -08001508std::vector<
1509 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1510PeerConnection::GetReceiversInternal() const {
1511 std::vector<
1512 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1513 all_receivers;
1514 for (auto transceiver : transceivers_) {
1515 auto receivers = transceiver->internal()->receivers();
1516 all_receivers.insert(all_receivers.end(), receivers.begin(),
1517 receivers.end());
1518 }
1519 return all_receivers;
1520}
1521
Steve Anton9158ef62017-11-27 13:01:52 -08001522std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1523PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001524 RTC_CHECK(IsUnifiedPlan())
1525 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001526 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1527 for (auto transceiver : transceivers_) {
1528 all_transceivers.push_back(transceiver);
1529 }
1530 return all_transceivers;
1531}
1532
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001534 MediaStreamTrackInterface* track,
1535 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001536 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001537 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001538 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001539 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001540 return false;
1541 }
1542
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001543 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001544 // The StatsCollector is used to tell if a track is valid because it may
1545 // remember tracks that the PeerConnection previously removed.
1546 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001547 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1548 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001549 return false;
1550 }
Steve Antonbb192762018-08-31 11:57:02 -07001551 // Need to capture |observer| and |track| in scoped_refptrs to ensure they
1552 // live long enough.
1553 rtc::scoped_refptr<StatsObserver> observer_refptr(observer);
1554 rtc::scoped_refptr<MediaStreamTrackInterface> track_refptr(track);
1555 async_invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(),
1556 [this, observer_refptr, track_refptr] {
1557 StatsReports reports;
1558 stats_->GetStats(track_refptr, &reports);
1559 observer_refptr->OnComplete(reports);
1560 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001561 return true;
1562}
1563
hbos74e1a4f2016-09-15 23:33:01 -07001564void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001565 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001566 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001567 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001568 stats_collector_->GetStatsReport(callback);
1569}
1570
Henrik Boström1df1bf82018-03-20 13:24:20 +01001571void PeerConnection::GetStats(
1572 rtc::scoped_refptr<RtpSenderInterface> selector,
1573 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1574 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1575 RTC_DCHECK(callback);
1576 RTC_DCHECK(stats_collector_);
1577 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1578 if (selector) {
1579 for (const auto& proxy_transceiver : transceivers_) {
1580 for (const auto& proxy_sender :
1581 proxy_transceiver->internal()->senders()) {
1582 if (proxy_sender == selector) {
1583 internal_sender = proxy_sender->internal();
1584 break;
1585 }
1586 }
1587 if (internal_sender)
1588 break;
1589 }
1590 }
1591 // If there is no |internal_sender| then |selector| is either null or does not
1592 // belong to the PeerConnection (in Plan B, senders can be removed from the
1593 // PeerConnection). This means that "all the stats objects representing the
1594 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1595 // produces an empty stats report.
1596 stats_collector_->GetStatsReport(internal_sender, callback);
1597}
1598
1599void PeerConnection::GetStats(
1600 rtc::scoped_refptr<RtpReceiverInterface> selector,
1601 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1602 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1603 RTC_DCHECK(callback);
1604 RTC_DCHECK(stats_collector_);
1605 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1606 if (selector) {
1607 for (const auto& proxy_transceiver : transceivers_) {
1608 for (const auto& proxy_receiver :
1609 proxy_transceiver->internal()->receivers()) {
1610 if (proxy_receiver == selector) {
1611 internal_receiver = proxy_receiver->internal();
1612 break;
1613 }
1614 }
1615 if (internal_receiver)
1616 break;
1617 }
1618 }
1619 // If there is no |internal_receiver| then |selector| is either null or does
1620 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1621 // the PeerConnection). This means that "all the stats objects representing
1622 // the selector" is an empty set. Invoking GetStatsReport() with a null
1623 // selector produces an empty stats report.
1624 stats_collector_->GetStatsReport(internal_receiver, callback);
1625}
1626
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001627PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1628 return signaling_state_;
1629}
1630
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001631PeerConnectionInterface::IceConnectionState
1632PeerConnection::ice_connection_state() {
1633 return ice_connection_state_;
1634}
1635
1636PeerConnectionInterface::IceGatheringState
1637PeerConnection::ice_gathering_state() {
1638 return ice_gathering_state_;
1639}
1640
Yves Gerey665174f2018-06-19 15:03:05 +02001641rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001642 const std::string& label,
1643 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001644 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001645
deadbeefab9b2d12015-10-14 11:33:11 -07001646 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001647
kwibergd1fe2812016-04-27 06:47:29 -07001648 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001649 if (config) {
1650 internal_config.reset(new InternalDataChannelInit(*config));
1651 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001652 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001653 InternalCreateDataChannel(label, internal_config.get()));
1654 if (!channel.get()) {
1655 return nullptr;
1656 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001658 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1659 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001660 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001661 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001662 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001663 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001664 return DataChannelProxy::Create(signaling_thread(), channel.get());
1665}
1666
1667void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001668 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001669 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001670
nisse7ce109a2017-01-31 00:57:56 -08001671 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001672 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001673 return;
1674 }
deadbeefab9b2d12015-10-14 11:33:11 -07001675
Steve Anton8d3444d2017-10-20 15:30:51 -07001676 if (IsClosed()) {
1677 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001678 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001679 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001680 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001681 return;
1682 }
1683
zhihuang1c378ed2017-08-17 14:10:50 -07001684 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001685 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001686 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001687 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001688 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001689 return;
1690 }
1691
Steve Anton22da89f2018-01-25 13:58:07 -08001692 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1693 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1694 if (IsUnifiedPlan()) {
1695 RTCError error = HandleLegacyOfferOptions(options);
1696 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001697 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001698 return;
1699 }
1700 }
1701
zhihuang1c378ed2017-08-17 14:10:50 -07001702 cricket::MediaSessionOptions session_options;
1703 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001704 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705}
1706
Steve Anton22da89f2018-01-25 13:58:07 -08001707RTCError PeerConnection::HandleLegacyOfferOptions(
1708 const RTCOfferAnswerOptions& options) {
1709 RTC_DCHECK(IsUnifiedPlan());
1710
1711 if (options.offer_to_receive_audio == 0) {
1712 RemoveRecvDirectionFromReceivingTransceiversOfType(
1713 cricket::MEDIA_TYPE_AUDIO);
1714 } else if (options.offer_to_receive_audio == 1) {
1715 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1716 } else if (options.offer_to_receive_audio > 1) {
1717 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1718 "offer_to_receive_audio > 1 is not supported.");
1719 }
1720
1721 if (options.offer_to_receive_video == 0) {
1722 RemoveRecvDirectionFromReceivingTransceiversOfType(
1723 cricket::MEDIA_TYPE_VIDEO);
1724 } else if (options.offer_to_receive_video == 1) {
1725 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1726 } else if (options.offer_to_receive_video > 1) {
1727 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1728 "offer_to_receive_video > 1 is not supported.");
1729 }
1730
1731 return RTCError::OK();
1732}
1733
1734void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1735 cricket::MediaType media_type) {
1736 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001737 RtpTransceiverDirection new_direction =
1738 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1739 if (new_direction != transceiver->direction()) {
1740 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1741 << " transceiver (MID="
1742 << transceiver->mid().value_or("<not set>") << ") from "
1743 << RtpTransceiverDirectionToString(
1744 transceiver->direction())
1745 << " to "
1746 << RtpTransceiverDirectionToString(new_direction)
1747 << " since CreateOffer specified offer_to_receive=0";
1748 transceiver->internal()->set_direction(new_direction);
1749 }
Steve Anton22da89f2018-01-25 13:58:07 -08001750 }
1751}
1752
1753void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1754 cricket::MediaType media_type) {
1755 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001756 RTC_LOG(LS_INFO)
1757 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1758 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001759 RtpTransceiverInit init;
1760 init.direction = RtpTransceiverDirection::kRecvOnly;
1761 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1762 }
1763}
1764
1765std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1766PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1767 std::vector<
1768 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1769 receiving_transceivers;
1770 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001771 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001772 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1773 receiving_transceivers.push_back(transceiver);
1774 }
1775 }
1776 return receiving_transceivers;
1777}
1778
htaa2a49d92016-03-04 02:51:39 -08001779void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1780 const RTCOfferAnswerOptions& options) {
1781 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001782 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001783 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001784 return;
1785 }
1786
Steve Antondffead82018-02-06 10:31:29 -08001787 if (!(signaling_state_ == kHaveRemoteOffer ||
1788 signaling_state_ == kHaveLocalPrAnswer)) {
1789 std::string error =
1790 "PeerConnection cannot create an answer in a state other than "
1791 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001792 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001793 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001794 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001795 return;
1796 }
1797
Steve Antondffead82018-02-06 10:31:29 -08001798 // The remote description should be set if we're in the right state.
1799 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001800
Steve Anton22da89f2018-01-25 13:58:07 -08001801 if (IsUnifiedPlan()) {
1802 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1803 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1804 "supported with Unified Plan semantics. Use the "
1805 "RtpTransceiver API instead.";
1806 }
1807 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1808 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1809 "supported with Unified Plan semantics. Use the "
1810 "RtpTransceiver API instead.";
1811 }
1812 }
1813
htaa2a49d92016-03-04 02:51:39 -08001814 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001815 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001816
Steve Antond25da372017-11-06 14:50:29 -08001817 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001818}
1819
1820void PeerConnection::SetLocalDescription(
1821 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001822 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001823 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001824
Steve Anton80dd7b52018-02-16 17:08:42 -08001825 // The SetLocalDescription contract is that we take ownership of the session
1826 // description regardless of the outcome, so wrap it in a unique_ptr right
1827 // away. Ideally, SetLocalDescription's signature will be changed to take the
1828 // description as a unique_ptr argument to formalize this agreement.
1829 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1830
nisse7ce109a2017-01-31 00:57:56 -08001831 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001832 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001833 return;
1834 }
Steve Anton8a006912017-12-04 15:25:56 -08001835
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001836 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001837 PostSetSessionDescriptionFailure(
1838 observer,
1839 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001840 return;
1841 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001842
Steve Anton80dd7b52018-02-16 17:08:42 -08001843 // If a session error has occurred the PeerConnection is in a possibly
1844 // inconsistent state so fail right away.
1845 if (session_error() != SessionError::kNone) {
1846 std::string error_message = GetSessionErrorMsg();
1847 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001848 PostSetSessionDescriptionFailure(
1849 observer,
1850 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001851 return;
1852 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001853
Steve Anton80dd7b52018-02-16 17:08:42 -08001854 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1855 if (!error.ok()) {
1856 std::string error_message = GetSetDescriptionErrorMessage(
1857 cricket::CS_LOCAL, desc->GetType(), error);
1858 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001859 PostSetSessionDescriptionFailure(
1860 observer,
1861 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001862 return;
1863 }
1864
1865 // Grab the description type before moving ownership to ApplyLocalDescription,
1866 // which may destroy it before returning.
1867 const SdpType type = desc->GetType();
1868
1869 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001870 // |desc| may be destroyed at this point.
1871
1872 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001873 // If ApplyLocalDescription fails, the PeerConnection could be in an
1874 // inconsistent state, so act conservatively here and set the session error
1875 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1876 SetSessionError(SessionError::kContent, error.message());
1877 std::string error_message =
1878 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1879 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001880 PostSetSessionDescriptionFailure(
1881 observer,
1882 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001883 return;
1884 }
Steve Anton8a006912017-12-04 15:25:56 -08001885 RTC_DCHECK(local_description());
1886
1887 PostSetSessionDescriptionSuccess(observer);
1888
Steve Antonbb192762018-08-31 11:57:02 -07001889 // MaybeStartGathering needs to be called after posting OnSuccess to the
1890 // SetSessionDescriptionObserver so that we don't signal any candidates before
1891 // signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001892 transport_controller_->MaybeStartGathering();
1893
Steve Antona3a92c22017-12-07 10:27:41 -08001894 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001895 // TODO(deadbeef): We already had to hop to the network thread for
1896 // MaybeStartGathering...
1897 network_thread()->Invoke<void>(
1898 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1899 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001900 // Make UMA notes about what was agreed to.
1901 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001902 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001903 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001904}
1905
1906RTCError PeerConnection::ApplyLocalDescription(
1907 std::unique_ptr<SessionDescriptionInterface> desc) {
1908 RTC_DCHECK_RUN_ON(signaling_thread());
1909 RTC_DCHECK(desc);
1910
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911 // Update stats here so that we have the most recent stats for tracks and
1912 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001913 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001914
Steve Antondcc3c022017-12-22 16:02:54 -08001915 // Take a reference to the old local description since it's used below to
1916 // compare against the new local description. When setting the new local
1917 // description, grab ownership of the replaced session description in case it
1918 // is the same as |old_local_description|, to keep it alive for the duration
1919 // of the method.
1920 const SessionDescriptionInterface* old_local_description =
1921 local_description();
1922 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001923 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001924 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001925 replaced_local_description = pending_local_description_
1926 ? std::move(pending_local_description_)
1927 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001928 current_local_description_ = std::move(desc);
1929 pending_local_description_ = nullptr;
1930 current_remote_description_ = std::move(pending_remote_description_);
1931 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001932 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001933 pending_local_description_ = std::move(desc);
1934 }
1935 // The session description to apply now must be accessed by
1936 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001937 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001938
Zhi Huange830e682018-03-30 10:48:35 -07001939 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
1940 if (!error.ok()) {
1941 return error;
1942 }
1943
Steve Antondcc3c022017-12-22 16:02:54 -08001944 if (IsUnifiedPlan()) {
1945 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001946 cricket::CS_LOCAL, *local_description(), old_local_description,
1947 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001948 if (!error.ok()) {
1949 return error;
1950 }
Steve Anton0f5400a2018-07-17 14:25:36 -07001951 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
1952 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08001953 for (auto transceiver : transceivers_) {
1954 const ContentInfo* content =
1955 FindMediaSectionForTransceiver(transceiver, local_description());
1956 if (!content) {
1957 continue;
1958 }
1959 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07001960 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
1961 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08001962 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07001963 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
1964 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
1965 // "recvonly", process the removal of a remote track for the media
1966 // description, given transceiver, removeList, and muteTracks.
1967 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
1968 (transceiver->internal()->fired_direction() &&
1969 RtpTransceiverDirectionHasRecv(
1970 *transceiver->internal()->fired_direction()))) {
1971 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
1972 &removed_streams);
1973 }
1974 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
1975 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08001976 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07001977 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08001978 }
Steve Anton0f5400a2018-07-17 14:25:36 -07001979 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001980 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07001981 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001982 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07001983 }
1984 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001985 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08001986 }
1987 } else {
Zhi Huange830e682018-03-30 10:48:35 -07001988 // Media channels will be created only when offer is set. These may use new
1989 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08001990 if (type == SdpType::kOffer) {
1991 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1992 // description is applied. Restore back to old description.
1993 RTCError error = CreateChannels(*local_description()->description());
1994 if (!error.ok()) {
1995 return error;
1996 }
1997 }
Steve Antondcc3c022017-12-22 16:02:54 -08001998 // Remove unused channels if MediaContentDescription is rejected.
1999 RemoveUnusedChannels(local_description()->description());
2000 }
Steve Anton8a006912017-12-04 15:25:56 -08002001
Zhi Huange830e682018-03-30 10:48:35 -07002002 error = UpdateSessionState(type, cricket::CS_LOCAL,
2003 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002004 if (!error.ok()) {
2005 return error;
2006 }
Steve Antondcc3c022017-12-22 16:02:54 -08002007
Steve Anton8a006912017-12-04 15:25:56 -08002008 if (remote_description()) {
2009 // Now that we have a local description, we can push down remote candidates.
2010 UseCandidatesInSessionDescription(remote_description());
2011 }
2012
2013 pending_ice_restarts_.clear();
2014 if (session_error() != SessionError::kNone) {
2015 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2016 }
2017
deadbeefab9b2d12015-10-14 11:33:11 -07002018 // If setting the description decided our SSL role, allocate any necessary
2019 // SCTP sids.
2020 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002021 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002022 AllocateSctpSids(role);
2023 }
2024
Steve Antond3679212018-01-17 17:41:02 -08002025 if (IsUnifiedPlan()) {
2026 for (auto transceiver : transceivers_) {
2027 const ContentInfo* content =
2028 FindMediaSectionForTransceiver(transceiver, local_description());
2029 if (!content) {
2030 continue;
2031 }
Steve Anton74255ff2018-01-24 18:32:57 -08002032 const auto& streams = content->media_description()->streams();
2033 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002034 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002035 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002036 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002037 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002038 } else {
2039 // 0 is a special value meaning "this sender has no associated send
2040 // stream". Need to call this so the sender won't attempt to configure
2041 // a no longer existing stream and run into DCHECKs in the lower
2042 // layers.
2043 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002044 }
2045 }
2046 } else {
2047 // Plan B semantics.
2048
Steve Antondcc3c022017-12-22 16:02:54 -08002049 // Update state and SSRC of local MediaStreams and DataChannels based on the
2050 // local session description.
2051 const cricket::ContentInfo* audio_content =
2052 GetFirstAudioContent(local_description()->description());
2053 if (audio_content) {
2054 if (audio_content->rejected) {
2055 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2056 } else {
2057 const cricket::AudioContentDescription* audio_desc =
2058 audio_content->media_description()->as_audio();
2059 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2060 }
deadbeeffaac4972015-11-12 15:33:07 -08002061 }
deadbeefab9b2d12015-10-14 11:33:11 -07002062
Steve Antondcc3c022017-12-22 16:02:54 -08002063 const cricket::ContentInfo* video_content =
2064 GetFirstVideoContent(local_description()->description());
2065 if (video_content) {
2066 if (video_content->rejected) {
2067 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2068 } else {
2069 const cricket::VideoContentDescription* video_desc =
2070 video_content->media_description()->as_video();
2071 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2072 }
deadbeeffaac4972015-11-12 15:33:07 -08002073 }
deadbeefab9b2d12015-10-14 11:33:11 -07002074 }
2075
2076 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002077 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002078 if (data_content) {
2079 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002080 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002081 if (rtc::starts_with(data_desc->protocol().data(),
2082 cricket::kMediaProtocolRtpPrefix)) {
2083 UpdateLocalRtpDataChannels(data_desc->streams());
2084 }
2085 }
2086
Steve Anton8a006912017-12-04 15:25:56 -08002087 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002088}
2089
2090void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002091 SetSessionDescriptionObserver* observer,
2092 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002093 SetRemoteDescription(
2094 std::unique_ptr<SessionDescriptionInterface>(desc),
2095 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2096 new SetRemoteDescriptionObserverAdapter(this, observer)));
2097}
2098
2099void PeerConnection::SetRemoteDescription(
2100 std::unique_ptr<SessionDescriptionInterface> desc,
2101 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002102 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002103
nisse7ce109a2017-01-31 00:57:56 -08002104 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002105 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002106 return;
2107 }
Steve Anton8a006912017-12-04 15:25:56 -08002108
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002109 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002110 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002111 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002112 return;
2113 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002114
Steve Anton80dd7b52018-02-16 17:08:42 -08002115 // If a session error has occurred the PeerConnection is in a possibly
2116 // inconsistent state so fail right away.
2117 if (session_error() != SessionError::kNone) {
2118 std::string error_message = GetSessionErrorMsg();
2119 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2120 observer->OnSetRemoteDescriptionComplete(
2121 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2122 return;
2123 }
Steve Anton71439a62018-02-15 11:53:06 -08002124
Steve Antonba42e992018-04-09 14:10:01 -07002125 if (desc->GetType() == SdpType::kOffer) {
2126 // Report to UMA the format of the received offer.
2127 ReportSdpFormatReceived(*desc);
2128 }
2129
Steve Anton80dd7b52018-02-16 17:08:42 -08002130 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002131 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002132 std::string error_message = GetSetDescriptionErrorMessage(
2133 cricket::CS_REMOTE, desc->GetType(), error);
2134 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002135 observer->OnSetRemoteDescriptionComplete(
2136 RTCError(error.type(), std::move(error_message)));
2137 return;
2138 }
Steve Anton71439a62018-02-15 11:53:06 -08002139
Steve Anton80dd7b52018-02-16 17:08:42 -08002140 // Grab the description type before moving ownership to
2141 // ApplyRemoteDescription, which may destroy it before returning.
2142 const SdpType type = desc->GetType();
2143
2144 error = ApplyRemoteDescription(std::move(desc));
2145 // |desc| may be destroyed at this point.
2146
2147 if (!error.ok()) {
2148 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2149 // inconsistent state, so act conservatively here and set the session error
2150 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2151 SetSessionError(SessionError::kContent, error.message());
2152 std::string error_message =
2153 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2154 RTC_LOG(LS_ERROR) << error_message;
2155 observer->OnSetRemoteDescriptionComplete(
2156 RTCError(error.type(), std::move(error_message)));
2157 return;
2158 }
2159 RTC_DCHECK(remote_description());
2160
2161 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002162 // TODO(deadbeef): We already had to hop to the network thread for
2163 // MaybeStartGathering...
2164 network_thread()->Invoke<void>(
2165 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2166 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002167 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002168 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002169 }
2170
2171 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002172 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002173}
2174
2175RTCError PeerConnection::ApplyRemoteDescription(
2176 std::unique_ptr<SessionDescriptionInterface> desc) {
2177 RTC_DCHECK_RUN_ON(signaling_thread());
2178 RTC_DCHECK(desc);
2179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002180 // Update stats here so that we have the most recent stats for tracks and
2181 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002182 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002183
Steve Antondcc3c022017-12-22 16:02:54 -08002184 // Take a reference to the old remote description since it's used below to
2185 // compare against the new remote description. When setting the new remote
2186 // description, grab ownership of the replaced session description in case it
2187 // is the same as |old_remote_description|, to keep it alive for the duration
2188 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002189 const SessionDescriptionInterface* old_remote_description =
2190 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002191 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002192 SdpType type = desc->GetType();
2193 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002194 replaced_remote_description = pending_remote_description_
2195 ? std::move(pending_remote_description_)
2196 : std::move(current_remote_description_);
2197 current_remote_description_ = std::move(desc);
2198 pending_remote_description_ = nullptr;
2199 current_local_description_ = std::move(pending_local_description_);
2200 } else {
2201 replaced_remote_description = std::move(pending_remote_description_);
2202 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203 }
Steve Anton8a006912017-12-04 15:25:56 -08002204 // The session description to apply now must be accessed by
2205 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002206 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207
Zhi Huange830e682018-03-30 10:48:35 -07002208 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2209 if (!error.ok()) {
2210 return error;
2211 }
Steve Anton8a006912017-12-04 15:25:56 -08002212 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002213 if (IsUnifiedPlan()) {
2214 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002215 cricket::CS_REMOTE, *remote_description(), local_description(),
2216 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002217 if (!error.ok()) {
2218 return error;
2219 }
Steve Antondcc3c022017-12-22 16:02:54 -08002220 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002221 // Media channels will be created only when offer is set. These may use new
2222 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002223 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002224 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002225 // description is applied. Restore back to old description.
2226 RTCError error = CreateChannels(*remote_description()->description());
2227 if (!error.ok()) {
2228 return error;
2229 }
2230 }
Steve Antondcc3c022017-12-22 16:02:54 -08002231 // Remove unused channels if MediaContentDescription is rejected.
2232 RemoveUnusedChannels(remote_description()->description());
2233 }
Steve Anton8a006912017-12-04 15:25:56 -08002234
Zhi Huange830e682018-03-30 10:48:35 -07002235 // NOTE: Candidates allocation will be initiated only when
2236 // SetLocalDescription is called.
2237 error = UpdateSessionState(type, cricket::CS_REMOTE,
2238 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002239 if (!error.ok()) {
2240 return error;
2241 }
2242
2243 if (local_description() &&
2244 !UseCandidatesInSessionDescription(remote_description())) {
2245 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2246 }
2247
2248 if (old_remote_description) {
2249 for (const cricket::ContentInfo& content :
2250 old_remote_description->description()->contents()) {
2251 // Check if this new SessionDescription contains new ICE ufrag and
2252 // password that indicates the remote peer requests an ICE restart.
2253 // TODO(deadbeef): When we start storing both the current and pending
2254 // remote description, this should reset pending_ice_restarts and compare
2255 // against the current description.
2256 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2257 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002258 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002259 pending_ice_restarts_.insert(content.name);
2260 }
2261 } else {
2262 // We retain all received candidates only if ICE is not restarted.
2263 // When ICE is restarted, all previous candidates belong to an old
2264 // generation and should not be kept.
2265 // TODO(deadbeef): This goes against the W3C spec which says the remote
2266 // description should only contain candidates from the last set remote
2267 // description plus any candidates added since then. We should remove
2268 // this once we're sure it won't break anything.
2269 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2270 old_remote_description, content.name, mutable_remote_description());
2271 }
2272 }
2273 }
2274
2275 if (session_error() != SessionError::kNone) {
2276 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2277 }
2278
2279 // Set the the ICE connection state to connecting since the connection may
2280 // become writable with peer reflexive candidates before any remote candidate
2281 // is signaled.
2282 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2283 // is to have a new signal the indicates a change in checking state from the
2284 // transport and expose a new checking() member from transport that can be
2285 // read to determine the current checking state. The existing SignalConnecting
2286 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002287 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002288 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002289 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2290 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2291 }
2292
deadbeefab9b2d12015-10-14 11:33:11 -07002293 // If setting the description decided our SSL role, allocate any necessary
2294 // SCTP sids.
2295 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002296 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002297 AllocateSctpSids(role);
2298 }
2299
Steve Antondcc3c022017-12-22 16:02:54 -08002300 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002301 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002302 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002303 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002304 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002305 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002306 for (auto transceiver : transceivers_) {
2307 const ContentInfo* content =
2308 FindMediaSectionForTransceiver(transceiver, remote_description());
2309 if (!content) {
2310 continue;
2311 }
2312 const MediaContentDescription* media_desc = content->media_description();
2313 RtpTransceiverDirection local_direction =
2314 RtpTransceiverDirectionReversed(media_desc->direction());
2315 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2316 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2317 // transceiver's current direction is neither sendrecv nor recvonly,
2318 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002319 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002320 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002321 // The remote description has signaled the stream IDs.
2322 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002323 }
Steve Antondcc3c022017-12-22 16:02:54 -08002324 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002325 (!transceiver->fired_direction() ||
2326 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002327 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002328 << content->name << " (added to "
2329 << GetStreamIdsString(stream_ids) << ").";
2330
2331 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2332 for (const std::string& stream_id : stream_ids) {
2333 rtc::scoped_refptr<MediaStreamInterface> stream =
2334 remote_streams_->find(stream_id);
2335 if (!stream) {
2336 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2337 MediaStream::Create(stream_id));
2338 remote_streams_->AddStream(stream);
2339 added_streams.push_back(stream);
2340 }
2341 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002342 }
Steve Anton3172c032018-05-03 15:30:18 -07002343 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002344 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2345 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002346 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002347 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002348 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002349 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2350 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2351 // removal of a remote track for the media description, given transceiver,
2352 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002353 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002354 (transceiver->fired_direction() &&
2355 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2356 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2357 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002358 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002359 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2360 transceiver->internal()->set_fired_direction(local_direction);
2361 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2362 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002363 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002364 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2365 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002366 transceiver->internal()->set_current_direction(local_direction);
2367 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002368 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2369 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002370 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002371 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2372 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002373 transceiver->Stop();
2374 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002375 if (!content->rejected &&
2376 RtpTransceiverDirectionHasRecv(local_direction)) {
2377 // Set ssrc to 0 in the case of an unsignalled ssrc.
2378 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002379 if (!media_desc->streams().empty() &&
2380 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002381 ssrc = media_desc->streams()[0].first_ssrc();
2382 }
2383 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002384 }
Steve Antondcc3c022017-12-22 16:02:54 -08002385 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002386 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002387 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002388 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002389 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002390 observer->OnTrack(transceiver);
2391 observer->OnAddTrack(transceiver->receiver(),
2392 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002393 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002394 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002395 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002396 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002397 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002398 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002399 }
2400 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002401 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002402 }
Steve Antondcc3c022017-12-22 16:02:54 -08002403 }
2404
Henrik Boströmfdb92012017-11-09 19:55:44 +01002405 const cricket::ContentInfo* audio_content =
2406 GetFirstAudioContent(remote_description()->description());
2407 const cricket::ContentInfo* video_content =
2408 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002409 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002410 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002411 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002412 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002413 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002414 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002415
2416 // Check if the descriptions include streams, just in case the peer supports
2417 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002418 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002419 (audio_desc && !audio_desc->streams().empty()) ||
2420 (video_desc && !video_desc->streams().empty())) {
2421 remote_peer_supports_msid_ = true;
2422 }
deadbeefab9b2d12015-10-14 11:33:11 -07002423
2424 // We wait to signal new streams until we finish processing the description,
2425 // since only at that point will new streams have all their tracks.
2426 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2427
Steve Antondcc3c022017-12-22 16:02:54 -08002428 if (!IsUnifiedPlan()) {
2429 // TODO(steveanton): When removing RTP senders/receivers in response to a
2430 // rejected media section, there is some cleanup logic that expects the
2431 // voice/ video channel to still be set. But in this method the voice/video
2432 // channel would have been destroyed by the SetRemoteDescription caller
2433 // above so the cleanup that relies on them fails to run. The RemoveSenders
2434 // calls should be moved to right before the DestroyChannel calls to fix
2435 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002436
Steve Antondcc3c022017-12-22 16:02:54 -08002437 // Find all audio rtp streams and create corresponding remote AudioTracks
2438 // and MediaStreams.
2439 if (audio_content) {
2440 if (audio_content->rejected) {
2441 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2442 } else {
2443 bool default_audio_track_needed =
2444 !remote_peer_supports_msid_ &&
2445 RtpTransceiverDirectionHasSend(audio_desc->direction());
2446 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2447 default_audio_track_needed, audio_desc->type(),
2448 new_streams);
2449 }
deadbeeffaac4972015-11-12 15:33:07 -08002450 }
deadbeefab9b2d12015-10-14 11:33:11 -07002451
Steve Antondcc3c022017-12-22 16:02:54 -08002452 // Find all video rtp streams and create corresponding remote VideoTracks
2453 // and MediaStreams.
2454 if (video_content) {
2455 if (video_content->rejected) {
2456 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2457 } else {
2458 bool default_video_track_needed =
2459 !remote_peer_supports_msid_ &&
2460 RtpTransceiverDirectionHasSend(video_desc->direction());
2461 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2462 default_video_track_needed, video_desc->type(),
2463 new_streams);
2464 }
deadbeeffaac4972015-11-12 15:33:07 -08002465 }
deadbeefab9b2d12015-10-14 11:33:11 -07002466
Steve Antondcc3c022017-12-22 16:02:54 -08002467 // Update the DataChannels with the information from the remote peer.
2468 if (data_desc) {
2469 if (rtc::starts_with(data_desc->protocol().data(),
2470 cricket::kMediaProtocolRtpPrefix)) {
2471 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2472 }
deadbeefab9b2d12015-10-14 11:33:11 -07002473 }
deadbeefab9b2d12015-10-14 11:33:11 -07002474
Steve Antondcc3c022017-12-22 16:02:54 -08002475 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002476 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002477 for (size_t i = 0; i < new_streams->count(); ++i) {
2478 MediaStreamInterface* new_stream = new_streams->at(i);
2479 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002480 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002481 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2482 }
deadbeefab9b2d12015-10-14 11:33:11 -07002483
Steve Antondcc3c022017-12-22 16:02:54 -08002484 UpdateEndedRemoteMediaStreams();
2485 }
deadbeefab9b2d12015-10-14 11:33:11 -07002486
Steve Anton8a006912017-12-04 15:25:56 -08002487 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002488}
2489
Steve Anton0f5400a2018-07-17 14:25:36 -07002490void PeerConnection::ProcessRemovalOfRemoteTrack(
2491 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2492 transceiver,
2493 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2494 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2495 RTC_DCHECK(transceiver->mid());
2496 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2497 << *transceiver->mid();
2498 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2499 transceiver->internal()->receiver_internal()->streams();
2500 // This will remove the remote track from the streams.
2501 transceiver->internal()->receiver_internal()->set_stream_ids({});
2502 remove_list->push_back(transceiver);
2503 // Remove any streams that no longer have tracks.
2504 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2505 // of streams, see if the stream was removed by checking if this was the
2506 // last receiver with that stream ID.
2507 for (auto stream : media_streams) {
2508 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2509 remote_streams_->RemoveStream(stream);
2510 removed_streams->push_back(stream);
2511 }
2512 }
2513}
2514
Steve Antondcc3c022017-12-22 16:02:54 -08002515RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2516 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002517 const SessionDescriptionInterface& new_session,
2518 const SessionDescriptionInterface* old_local_description,
2519 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002520 RTC_DCHECK(IsUnifiedPlan());
2521
Steve Anton7464fca2018-01-19 11:10:37 -08002522 const cricket::ContentGroup* bundle_group = nullptr;
2523 if (new_session.GetType() == SdpType::kOffer) {
2524 auto bundle_group_or_error =
2525 GetEarlyBundleGroup(*new_session.description());
2526 if (!bundle_group_or_error.ok()) {
2527 return bundle_group_or_error.MoveError();
2528 }
2529 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002530 }
Steve Antondcc3c022017-12-22 16:02:54 -08002531
Steve Antondcc3c022017-12-22 16:02:54 -08002532 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002533 for (size_t i = 0; i < new_contents.size(); ++i) {
2534 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002535 cricket::MediaType media_type = new_content.media_description()->type();
2536 seen_mids_.insert(new_content.name);
2537 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2538 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002539 const cricket::ContentInfo* old_local_content = nullptr;
2540 if (old_local_description &&
2541 i < old_local_description->description()->contents().size()) {
2542 old_local_content =
2543 &old_local_description->description()->contents()[i];
2544 }
2545 const cricket::ContentInfo* old_remote_content = nullptr;
2546 if (old_remote_description &&
2547 i < old_remote_description->description()->contents().size()) {
2548 old_remote_content =
2549 &old_remote_description->description()->contents()[i];
2550 }
Steve Antondcc3c022017-12-22 16:02:54 -08002551 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002552 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2553 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002554 if (!transceiver_or_error.ok()) {
2555 return transceiver_or_error.MoveError();
2556 }
2557 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002558 RTCError error =
2559 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2560 if (!error.ok()) {
2561 return error;
2562 }
2563 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002564 if (GetDataMid() && new_content.name != *GetDataMid()) {
2565 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002566 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2567 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002568 continue;
2569 }
2570 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2571 if (!error.ok()) {
2572 return error;
2573 }
Steve Antondcc3c022017-12-22 16:02:54 -08002574 } else {
2575 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2576 "Unknown section type.");
2577 }
2578 }
2579
2580 return RTCError::OK();
2581}
2582
2583RTCError PeerConnection::UpdateTransceiverChannel(
2584 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2585 transceiver,
2586 const cricket::ContentInfo& content,
2587 const cricket::ContentGroup* bundle_group) {
2588 RTC_DCHECK(IsUnifiedPlan());
2589 RTC_DCHECK(transceiver);
2590 cricket::BaseChannel* channel = transceiver->internal()->channel();
2591 if (content.rejected) {
2592 if (channel) {
2593 transceiver->internal()->SetChannel(nullptr);
2594 DestroyBaseChannel(channel);
2595 }
2596 } else {
2597 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002598 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002599 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002600 } else {
Steve Anton69470252018-02-09 11:43:08 -08002601 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002602 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002603 }
2604 if (!channel) {
2605 LOG_AND_RETURN_ERROR(
2606 RTCErrorType::INTERNAL_ERROR,
2607 "Failed to create channel for mid=" + content.name);
2608 }
2609 transceiver->internal()->SetChannel(channel);
2610 }
2611 }
2612 return RTCError::OK();
2613}
2614
Steve Antonfa2260d2017-12-28 16:38:23 -08002615RTCError PeerConnection::UpdateDataChannel(
2616 cricket::ContentSource source,
2617 const cricket::ContentInfo& content,
2618 const cricket::ContentGroup* bundle_group) {
2619 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002620 // If data channels are disabled, ignore this media section. CreateAnswer
2621 // will take care of rejecting it.
2622 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002623 }
2624 if (content.rejected) {
2625 DestroyDataChannel();
2626 } else {
2627 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002628 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002629 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2630 "Failed to create data channel.");
2631 }
2632 }
2633 if (source == cricket::CS_REMOTE) {
2634 const MediaContentDescription* data_desc = content.media_description();
2635 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2636 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2637 }
2638 }
2639 }
2640 return RTCError::OK();
2641}
2642
Steve Antondcc3c022017-12-22 16:02:54 -08002643RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2644PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002645 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002646 size_t mline_index,
2647 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002648 const ContentInfo* old_local_content,
2649 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002650 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002651 // If this is an offer then the m= section might be recycled. If the m=
2652 // section is being recycled (defined as: rejected in the current local or
2653 // remote description and not rejected in new description), dissociate the
2654 // currently associated RtpTransceiver by setting its mid property to null,
2655 // and discard the mapping between the transceiver and its m= section index.
2656 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2657 old_remote_content)) {
2658 // We want to dissociate the transceiver that has the rejected mid.
2659 const std::string& old_mid =
2660 (old_local_content && old_local_content->rejected)
2661 ? old_local_content->name
2662 : old_remote_content->name;
2663 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002664 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002665 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2666 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002667 old_transceiver->internal()->set_mid(absl::nullopt);
2668 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002669 }
2670 }
2671 const MediaContentDescription* media_desc = content.media_description();
2672 auto transceiver = GetAssociatedTransceiver(content.name);
2673 if (source == cricket::CS_LOCAL) {
2674 // Find the RtpTransceiver that corresponds to this m= section, using the
2675 // mapping between transceivers and m= section indices established when
2676 // creating the offer.
2677 if (!transceiver) {
2678 transceiver = GetTransceiverByMLineIndex(mline_index);
2679 }
2680 if (!transceiver) {
2681 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2682 "Unknown transceiver");
2683 }
2684 } else {
2685 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2686 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2687 // of the same type...
2688 if (!transceiver &&
2689 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2690 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2691 }
2692 // If no RtpTransceiver was found in the previous step, create one with a
2693 // recvonly direction.
2694 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002695 RTC_LOG(LS_INFO) << "Adding "
2696 << cricket::MediaTypeToString(media_desc->type())
2697 << " transceiver for MID=" << content.name
2698 << " at i=" << mline_index
2699 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002700 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002701 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002702 std::string receiver_id;
2703 if (!media_desc->streams().empty()) {
2704 receiver_id = media_desc->streams()[0].id;
2705 } else {
2706 receiver_id = rtc::CreateRandomUuid();
2707 }
2708 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002709 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002710 transceiver->internal()->set_direction(
2711 RtpTransceiverDirection::kRecvOnly);
2712 }
2713 }
2714 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002715 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002716 LOG_AND_RETURN_ERROR(
2717 RTCErrorType::INVALID_PARAMETER,
2718 "Transceiver type does not match media description type.");
2719 }
2720 // Associate the found or created RtpTransceiver with the m= section by
2721 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2722 // section, and establish a mapping between the transceiver and the index of
2723 // the m= section.
2724 transceiver->internal()->set_mid(content.name);
2725 transceiver->internal()->set_mline_index(mline_index);
2726 return std::move(transceiver);
2727}
2728
2729rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2730PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2731 RTC_DCHECK(IsUnifiedPlan());
2732 for (auto transceiver : transceivers_) {
2733 if (transceiver->mid() == mid) {
2734 return transceiver;
2735 }
2736 }
2737 return nullptr;
2738}
2739
2740rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2741PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2742 RTC_DCHECK(IsUnifiedPlan());
2743 for (auto transceiver : transceivers_) {
2744 if (transceiver->internal()->mline_index() == mline_index) {
2745 return transceiver;
2746 }
2747 }
2748 return nullptr;
2749}
2750
2751rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2752PeerConnection::FindAvailableTransceiverToReceive(
2753 cricket::MediaType media_type) const {
2754 RTC_DCHECK(IsUnifiedPlan());
2755 // From JSEP section 5.10 (Applying a Remote Description):
2756 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2757 // the same type that were added to the PeerConnection by addTrack and are not
2758 // associated with any m= section and are not stopped, find the first such
2759 // RtpTransceiver.
2760 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002761 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002762 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2763 !transceiver->stopped()) {
2764 return transceiver;
2765 }
2766 }
2767 return nullptr;
2768}
2769
Steve Antoned10bd92017-12-05 10:52:59 -08002770const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2771 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2772 transceiver,
2773 const SessionDescriptionInterface* sdesc) const {
2774 RTC_DCHECK(transceiver);
2775 RTC_DCHECK(sdesc);
2776 if (IsUnifiedPlan()) {
2777 if (!transceiver->internal()->mid()) {
2778 // This transceiver is not associated with a media section yet.
2779 return nullptr;
2780 }
2781 return sdesc->description()->GetContentByName(
2782 *transceiver->internal()->mid());
2783 } else {
2784 // Plan B only allows at most one audio and one video section, so use the
2785 // first media section of that type.
2786 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002787 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002788 }
2789}
2790
deadbeef46c73892016-11-16 19:42:04 -08002791PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2792 return configuration_;
2793}
2794
deadbeef293e9262017-01-11 12:28:30 -08002795bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2796 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002797 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002798 if (IsClosed()) {
2799 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2800 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2801 }
2802
Qingsi Wanga2d60672018-04-11 16:57:45 -07002803 // According to JSEP, after setLocalDescription, changing the candidate pool
2804 // size is not allowed, and changing the set of ICE servers will not result
2805 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002806 if (local_description() && configuration.ice_candidate_pool_size !=
2807 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002808 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2809 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002810 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002811 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002812
deadbeef293e9262017-01-11 12:28:30 -08002813 // The simplest (and most future-compatible) way to tell if the config was
2814 // modified in an invalid way is to copy each property we do support
2815 // modifying, then use operator==. There are far more properties we don't
2816 // support modifying than those we do, and more could be added.
2817 RTCConfiguration modified_config = configuration_;
2818 modified_config.servers = configuration.servers;
2819 modified_config.type = configuration.type;
2820 modified_config.ice_candidate_pool_size =
2821 configuration.ice_candidate_pool_size;
2822 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002823 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002824 modified_config.ice_check_interval_strong_connectivity =
2825 configuration.ice_check_interval_strong_connectivity;
2826 modified_config.ice_check_interval_weak_connectivity =
2827 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002828 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2829 modified_config.ice_unwritable_min_checks =
2830 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002831 modified_config.stun_candidate_keepalive_interval =
2832 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002833 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002834 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002835 modified_config.active_reset_srtp_params =
2836 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002837 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002838 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002839 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2840 }
2841
Steve Anton038834f2017-07-14 15:59:59 -07002842 // Validate the modified configuration.
2843 RTCError validate_error = ValidateConfiguration(modified_config);
2844 if (!validate_error.ok()) {
2845 return SafeSetError(std::move(validate_error), error);
2846 }
2847
deadbeef293e9262017-01-11 12:28:30 -08002848 // Note that this isn't possible through chromium, since it's an unsigned
2849 // short in WebIDL.
2850 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002851 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002852 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2853 }
2854
2855 // Parse ICE servers before hopping to network thread.
2856 cricket::ServerAddresses stun_servers;
2857 std::vector<cricket::RelayServerConfig> turn_servers;
2858 RTCErrorType parse_error =
2859 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2860 if (parse_error != RTCErrorType::NONE) {
2861 return SafeSetError(parse_error, error);
2862 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002863 // Note if STUN or TURN servers were supplied.
2864 if (!stun_servers.empty()) {
2865 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2866 }
2867 if (!turn_servers.empty()) {
2868 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2869 }
deadbeef293e9262017-01-11 12:28:30 -08002870
2871 // In theory this shouldn't fail.
2872 if (!network_thread()->Invoke<bool>(
2873 RTC_FROM_HERE,
2874 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2875 stun_servers, turn_servers, modified_config.type,
2876 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002877 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002878 modified_config.turn_customizer,
2879 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002880 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002881 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2882 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002883
deadbeefd1a38b52016-12-10 13:15:33 -08002884 // As described in JSEP, calling setConfiguration with new ICE servers or
2885 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2886 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002887 if (modified_config.servers != configuration_.servers ||
2888 modified_config.type != configuration_.type ||
2889 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002890 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002891 }
skvladd1f5fda2017-02-03 16:54:05 -08002892
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002893 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002894
Zhi Huangb57e1692018-06-12 11:41:11 -07002895 if (configuration_.active_reset_srtp_params !=
2896 modified_config.active_reset_srtp_params) {
2897 transport_controller_->SetActiveResetSrtpParams(
2898 modified_config.active_reset_srtp_params);
2899 }
2900
deadbeef293e9262017-01-11 12:28:30 -08002901 configuration_ = modified_config;
2902 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002903}
2904
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002905bool PeerConnection::AddIceCandidate(
2906 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002907 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002908 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002909 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002910 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07002911 return false;
2912 }
Steve Antond25da372017-11-06 14:50:29 -08002913
2914 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002915 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002916 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002917 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002918 return false;
2919 }
2920
2921 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002922 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002923 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08002924 return false;
2925 }
2926
2927 bool valid = false;
2928 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2929 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002930 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08002931 return false;
2932 }
2933
2934 // Add this candidate to the remote session description.
2935 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002936 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002937 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08002938 return false;
2939 }
2940
2941 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002942 bool result = UseCandidate(ice_candidate);
2943 if (result) {
2944 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
2945 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
2946 } else {
2947 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
2948 }
2949 return result;
Steve Antond25da372017-11-06 14:50:29 -08002950 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002951 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002952 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08002953 return true;
2954 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002955}
2956
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002957bool PeerConnection::RemoveIceCandidates(
2958 const std::vector<cricket::Candidate>& candidates) {
2959 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002960 if (IsClosed()) {
2961 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2962 return false;
2963 }
2964
Steve Antond25da372017-11-06 14:50:29 -08002965 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002966 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2967 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002968 return false;
2969 }
2970
2971 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002972 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002973 return false;
2974 }
2975
2976 size_t number_removed =
2977 mutable_remote_description()->RemoveCandidates(candidates);
2978 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002979 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07002980 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002981 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002982 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002983 }
2984
2985 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07002986 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
2987 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002988 RTC_LOG(LS_ERROR)
2989 << "RemoveIceCandidates: Error when removing remote candidates: "
2990 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08002991 }
2992 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002993}
2994
Niels Möller0c4f7be2018-05-07 14:01:37 +02002995RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002996 if (!worker_thread()->IsCurrent()) {
2997 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02002998 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07002999 }
3000
Niels Möller0c4f7be2018-05-07 14:01:37 +02003001 const bool has_min = bitrate.min_bitrate_bps.has_value();
3002 const bool has_start = bitrate.start_bitrate_bps.has_value();
3003 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003004 if (has_min && *bitrate.min_bitrate_bps < 0) {
3005 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3006 "min_bitrate_bps <= 0");
3007 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003008 if (has_start) {
3009 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003010 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003011 "start_bitrate_bps < min_bitrate_bps");
3012 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003013 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3014 "curent_bitrate_bps < 0");
3015 }
3016 }
3017 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003018 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003019 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003020 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003021 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3022 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3023 "max_bitrate_bps < min_bitrate_bps");
3024 } else if (*bitrate.max_bitrate_bps < 0) {
3025 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3026 "max_bitrate_bps < 0");
3027 }
3028 }
3029
zstein4b979802017-06-02 14:37:37 -07003030 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003031 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003032
3033 return RTCError::OK();
3034}
3035
Alex Narest78609d52017-10-20 10:37:47 +02003036void PeerConnection::SetBitrateAllocationStrategy(
3037 std::unique_ptr<rtc::BitrateAllocationStrategy>
3038 bitrate_allocation_strategy) {
3039 rtc::Thread* worker_thread = factory_->worker_thread();
3040 if (!worker_thread->IsCurrent()) {
3041 rtc::BitrateAllocationStrategy* strategy_raw =
3042 bitrate_allocation_strategy.release();
3043 auto functor = [this, strategy_raw]() {
3044 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003045 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003046 };
3047 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3048 return;
3049 }
3050 RTC_DCHECK(call_.get());
3051 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3052}
3053
henrika5f6bf242017-11-01 11:06:56 +01003054void PeerConnection::SetAudioPlayout(bool playout) {
3055 if (!worker_thread()->IsCurrent()) {
3056 worker_thread()->Invoke<void>(
3057 RTC_FROM_HERE,
3058 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3059 return;
3060 }
3061 auto audio_state =
3062 factory_->channel_manager()->media_engine()->GetAudioState();
3063 audio_state->SetPlayout(playout);
3064}
3065
3066void PeerConnection::SetAudioRecording(bool recording) {
3067 if (!worker_thread()->IsCurrent()) {
3068 worker_thread()->Invoke<void>(
3069 RTC_FROM_HERE,
3070 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3071 return;
3072 }
3073 auto audio_state =
3074 factory_->channel_manager()->media_engine()->GetAudioState();
3075 audio_state->SetRecording(recording);
3076}
3077
Steve Anton8c0f7a72017-10-03 10:03:10 -07003078std::unique_ptr<rtc::SSLCertificate>
3079PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003080 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3081 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003082 return nullptr;
3083 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003084 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003085}
3086
Zhi Huang70b820f2018-01-27 14:16:15 -08003087std::unique_ptr<rtc::SSLCertChain>
3088PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003089 auto audio_transceiver = GetFirstAudioTransceiver();
3090 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003091 return nullptr;
3092 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003093 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003094 audio_transceiver->internal()->channel()->transport_name());
3095}
3096
3097rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3098PeerConnection::GetFirstAudioTransceiver() const {
3099 for (auto transceiver : transceivers_) {
3100 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3101 return transceiver;
3102 }
3103 }
3104 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003105}
3106
ivoc14d5dbe2016-07-04 07:06:55 -07003107bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3108 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003109 // TODO(eladalon): It would be better to not allow negative values into PC.
3110 const size_t max_size = (max_size_bytes < 0)
3111 ? RtcEventLog::kUnlimitedOutput
3112 : rtc::saturated_cast<size_t>(max_size_bytes);
3113 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003114 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003115 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003116}
3117
Bjorn Tereliusde939432017-11-20 17:38:14 +01003118bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3119 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003120 // TODO(eladalon): In C++14, this can be done with a lambda.
3121 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003122 bool operator()() {
3123 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3124 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003125 PeerConnection* const pc;
3126 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003127 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003128 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003129 return worker_thread()->Invoke<bool>(
3130 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003131}
3132
3133void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003134 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003135 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3136}
3137
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003139 return pending_local_description_ ? pending_local_description_.get()
3140 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003141}
3142
3143const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003144 return pending_remote_description_ ? pending_remote_description_.get()
3145 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003146}
3147
deadbeeffe4a8a42016-12-20 17:56:17 -08003148const SessionDescriptionInterface* PeerConnection::current_local_description()
3149 const {
Steve Anton75737c02017-11-06 10:37:17 -08003150 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003151}
3152
3153const SessionDescriptionInterface* PeerConnection::current_remote_description()
3154 const {
Steve Anton75737c02017-11-06 10:37:17 -08003155 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003156}
3157
3158const SessionDescriptionInterface* PeerConnection::pending_local_description()
3159 const {
Steve Anton75737c02017-11-06 10:37:17 -08003160 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003161}
3162
3163const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3164 const {
Steve Anton75737c02017-11-06 10:37:17 -08003165 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003166}
3167
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003168void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003169 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003170 // Update stats here so that we have the most recent stats for tracks and
3171 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003172 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003173
Steve Anton75737c02017-11-06 10:37:17 -08003174 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003175 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003176
Steve Anton8af21862017-12-15 11:20:13 -08003177 for (auto transceiver : transceivers_) {
3178 transceiver->Stop();
3179 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003180
3181 // Ensure that all asynchronous stats requests are completed before destroying
3182 // the transport controller below.
3183 if (stats_collector_) {
3184 stats_collector_->WaitForPendingRequest();
3185 }
3186
3187 // Don't destroy BaseChannels until after stats has been cleaned up so that
3188 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003189 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003190
Qingsi Wang93a84392018-01-30 17:13:09 -08003191 // The event log is used in the transport controller, which must be outlived
3192 // by the former. CreateOffer by the peer connection is implemented
3193 // asynchronously and if the peer connection is closed without resetting the
3194 // WebRTC session description factory, the session description factory would
3195 // call the transport controller.
3196 webrtc_session_desc_factory_.reset();
3197 transport_controller_.reset();
3198
deadbeef42a42632017-03-10 15:18:00 -08003199 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003200 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3201 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003202
Steve Anton978b8762017-09-29 12:15:02 -07003203 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003204 call_.reset();
3205 // The event log must outlive call (and any other object that uses it).
3206 event_log_.reset();
3207 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003208 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003209 // The .h file says that observer can be discarded after close() returns.
3210 // Make sure this is true.
3211 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212}
3213
Steve Antonafb0bb72018-02-20 11:35:37 -08003214cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3215 RTC_DCHECK(!IsUnifiedPlan());
3216 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3217 GetAudioTransceiver()->internal()->channel());
3218 if (voice_channel) {
3219 return voice_channel->media_channel();
3220 } else {
3221 return nullptr;
3222 }
3223}
3224
3225cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3226 RTC_DCHECK(!IsUnifiedPlan());
3227 auto* video_channel = static_cast<cricket::VideoChannel*>(
3228 GetVideoTransceiver()->internal()->channel());
3229 if (video_channel) {
3230 return video_channel->media_channel();
3231 } else {
3232 return nullptr;
3233 }
3234}
3235
Steve Anton4171afb2017-11-20 10:20:22 -08003236void PeerConnection::CreateAudioReceiver(
3237 MediaStreamInterface* stream,
3238 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003239 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3240 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003241 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3242 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003243 auto* audio_receiver = new AudioRtpReceiver(
3244 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003245 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003246 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3247 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3248 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003249 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003250 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003251 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003252}
3253
Steve Anton4171afb2017-11-20 10:20:22 -08003254void PeerConnection::CreateVideoReceiver(
3255 MediaStreamInterface* stream,
3256 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003257 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3258 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003259 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3260 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003261 auto* video_receiver = new VideoRtpReceiver(
3262 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003263 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003264 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3265 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3266 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003267 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003268 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003269 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003270}
3271
deadbeef70ab1a12015-09-28 16:53:55 -07003272// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3273// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003274rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003275 const RtpSenderInfo& remote_sender_info) {
3276 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3277 if (!receiver) {
3278 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3279 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003280 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003281 }
Steve Anton4171afb2017-11-20 10:20:22 -08003282 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3283 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3284 } else {
3285 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3286 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003287 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003288}
3289
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003290void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3291 MediaStreamInterface* stream) {
3292 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003293 RTC_DCHECK(track);
3294 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003295 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003296 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003297 // We already have a sender for this track, so just change the stream_id
3298 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003299 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003300 return;
3301 }
3302
3303 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003304 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3305 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003306 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003307 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003308 // If the sender has already been configured in SDP, we call SetSsrc,
3309 // which will connect the sender to the underlying transport. This can
3310 // occur if a local session description that contains the ID of the sender
3311 // is set before AddStream is called. It can also occur if the local
3312 // session description is not changed and RemoveStream is called, and
3313 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003314 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003315 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003316 if (sender_info) {
3317 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003318 }
3319}
3320
3321// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3322// indefinitely, when we have unified plan SDP.
3323void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3324 MediaStreamInterface* stream) {
3325 RTC_DCHECK(!IsClosed());
3326 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003327 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003328 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3329 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003330 return;
3331 }
Steve Anton4171afb2017-11-20 10:20:22 -08003332 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003333}
3334
3335void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3336 MediaStreamInterface* stream) {
3337 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003338 RTC_DCHECK(track);
3339 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003340 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003341 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003342 // We already have a sender for this track, so just change the stream_id
3343 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003344 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003345 return;
3346 }
3347
3348 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003349 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3350 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003351 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003352 GetVideoTransceiver()->internal()->AddSender(new_sender);
3353 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003354 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003355 if (sender_info) {
3356 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003357 }
3358}
3359
3360void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3361 MediaStreamInterface* stream) {
3362 RTC_DCHECK(!IsClosed());
3363 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003364 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003365 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3366 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003367 return;
3368 }
Steve Anton4171afb2017-11-20 10:20:22 -08003369 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003370}
3371
Steve Antonba818672017-11-06 10:21:57 -08003372void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003373 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003374 if (ice_connection_state_ == new_state) {
3375 return;
3376 }
3377
deadbeefcbecd352015-09-23 11:50:27 -07003378 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003379 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003380 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003381 return;
3382 }
Steve Antonba818672017-11-06 10:21:57 -08003383
Mirko Bonadei675513b2017-11-09 11:09:25 +01003384 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3385 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003386 RTC_DCHECK(ice_connection_state_ !=
3387 PeerConnectionInterface::kIceConnectionClosed);
3388
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003389 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003390 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391}
3392
3393void PeerConnection::OnIceGatheringChange(
3394 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003395 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003396 if (IsClosed()) {
3397 return;
3398 }
3399 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003400 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003401}
3402
jbauch81bf7b02017-03-25 08:31:12 -07003403void PeerConnection::OnIceCandidate(
3404 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003405 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003406 if (IsClosed()) {
3407 return;
3408 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003409 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003410 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3411 candidate->candidate().address().IsPrivateIP()) {
3412 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3413 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003414 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003415}
3416
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003417void PeerConnection::OnIceCandidatesRemoved(
3418 const std::vector<cricket::Candidate>& candidates) {
3419 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003420 if (IsClosed()) {
3421 return;
3422 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003423 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003424}
3425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003426void PeerConnection::ChangeSignalingState(
3427 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003428 RTC_DCHECK(signaling_thread()->IsCurrent());
3429 if (signaling_state_ == signaling_state) {
3430 return;
3431 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003432 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3433 << GetSignalingStateString(signaling_state_)
3434 << " New state: "
3435 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003436 signaling_state_ = signaling_state;
3437 if (signaling_state == kClosed) {
3438 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003439 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003440 if (ice_gathering_state_ != kIceGatheringComplete) {
3441 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003442 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003443 }
3444 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003445 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003446}
3447
deadbeefeb459812015-12-15 19:24:43 -08003448void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3449 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003450 if (IsClosed()) {
3451 return;
3452 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003453 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003454 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003455}
3456
deadbeefeb459812015-12-15 19:24:43 -08003457void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3458 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003459 if (IsClosed()) {
3460 return;
3461 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003462 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003463 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003464}
3465
3466void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3467 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003468 if (IsClosed()) {
3469 return;
3470 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003471 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003472 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003473}
3474
3475void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3476 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003477 if (IsClosed()) {
3478 return;
3479 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003480 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003481 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003482}
3483
Henrik Boström31638672017-11-23 17:48:32 +01003484void PeerConnection::PostSetSessionDescriptionSuccess(
3485 SetSessionDescriptionObserver* observer) {
Steve Antonbb192762018-08-31 11:57:02 -07003486 async_invoker_.AsyncInvoke<void>(
3487 RTC_FROM_HERE, signaling_thread(),
3488 rtc::Bind(&SetSessionDescriptionObserver::OnSuccess, observer));
Henrik Boström31638672017-11-23 17:48:32 +01003489}
3490
deadbeefab9b2d12015-10-14 11:33:11 -07003491void PeerConnection::PostSetSessionDescriptionFailure(
3492 SetSessionDescriptionObserver* observer,
Steve Antonbb192762018-08-31 11:57:02 -07003493 RTCError error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003494 RTC_DCHECK(!error.ok());
Steve Antonbb192762018-08-31 11:57:02 -07003495 // TODO(steveanton): In C++14 this can be done with a lambda.
3496 struct Functor {
3497 void operator()() { observer->OnFailure(std::move(error)); }
3498 rtc::scoped_refptr<SetSessionDescriptionObserver> observer;
3499 RTCError error;
3500 };
3501 async_invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(),
3502 Functor{observer, std::move(error)});
deadbeefab9b2d12015-10-14 11:33:11 -07003503}
3504
3505void PeerConnection::PostCreateSessionDescriptionFailure(
3506 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003507 RTCError error) {
3508 RTC_DCHECK(!error.ok());
Steve Antonbb192762018-08-31 11:57:02 -07003509 // TODO(steveanton): In C++14 this can be done with a lambda.
3510 struct Functor {
3511 void operator()() { observer->OnFailure(std::move(error)); }
3512 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer;
3513 RTCError error;
3514 };
3515 async_invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(),
3516 Functor{observer, std::move(error)});
deadbeefab9b2d12015-10-14 11:33:11 -07003517}
3518
zhihuang1c378ed2017-08-17 14:10:50 -07003519void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003520 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003521 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003522 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003523
Steve Antondcc3c022017-12-22 16:02:54 -08003524 if (IsUnifiedPlan()) {
3525 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3526 } else {
3527 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3528 }
3529
Steve Antonfa2260d2017-12-28 16:38:23 -08003530 // Intentionally unset the data channel type for RTP data channel with the
3531 // second condition. Otherwise the RTP data channels would be successfully
3532 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3533 // when building with chromium. We want to leave RTP data channels broken, so
3534 // people won't try to use them.
3535 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3536 session_options->data_channel_type = data_channel_type();
3537 }
3538
Steve Antondcc3c022017-12-22 16:02:54 -08003539 // Apply ICE restart flag and renomination flag.
3540 for (auto& options : session_options->media_description_options) {
3541 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3542 options.transport_options.enable_ice_renomination =
3543 configuration_.enable_ice_renomination;
3544 }
3545
3546 session_options->rtcp_cname = rtcp_cname_;
3547 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003548 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003549}
3550
3551void PeerConnection::GetOptionsForPlanBOffer(
3552 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3553 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003554 // Figure out transceiver directional preferences.
3555 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3556 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3557
3558 // By default, generate sendrecv/recvonly m= sections.
3559 bool recv_audio = true;
3560 bool recv_video = true;
3561
3562 // By default, only offer a new m= section if we have media to send with it.
3563 bool offer_new_audio_description = send_audio;
3564 bool offer_new_video_description = send_video;
3565 bool offer_new_data_description = HasDataChannels();
3566
3567 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003568 if (offer_answer_options.offer_to_receive_audio !=
3569 RTCOfferAnswerOptions::kUndefined) {
3570 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003571 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003572 offer_new_audio_description ||
3573 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003574 }
Steve Antondcc3c022017-12-22 16:02:54 -08003575 if (offer_answer_options.offer_to_receive_video !=
3576 RTCOfferAnswerOptions::kUndefined) {
3577 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003578 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003579 offer_new_video_description ||
3580 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003581 }
3582
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003583 absl::optional<size_t> audio_index;
3584 absl::optional<size_t> video_index;
3585 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003586 // If a current description exists, generate m= sections in the same order,
3587 // using the first audio/video/data section that appears and rejecting
3588 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003589 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003590 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003591 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003592 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3593 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3594 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003595 }
3596
zhihuang1c378ed2017-08-17 14:10:50 -07003597 // Add audio/video/data m= sections to the end if needed.
3598 if (!audio_index && offer_new_audio_description) {
3599 session_options->media_description_options.push_back(
3600 cricket::MediaDescriptionOptions(
3601 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003602 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3603 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003604 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003605 }
zhihuang1c378ed2017-08-17 14:10:50 -07003606 if (!video_index && offer_new_video_description) {
3607 session_options->media_description_options.push_back(
3608 cricket::MediaDescriptionOptions(
3609 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003610 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3611 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003612 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003613 }
zhihuang1c378ed2017-08-17 14:10:50 -07003614 if (!data_index && offer_new_data_description) {
3615 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003616 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003617 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003618 }
3619
3620 cricket::MediaDescriptionOptions* audio_media_description_options =
3621 !audio_index ? nullptr
3622 : &session_options->media_description_options[*audio_index];
3623 cricket::MediaDescriptionOptions* video_media_description_options =
3624 !video_index ? nullptr
3625 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003626
Steve Anton4171afb2017-11-20 10:20:22 -08003627 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003628 video_media_description_options,
3629 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003630}
3631
3632// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3633// and return a reference to it.
3634// Generated MIDs should be no more than 3 bytes long to take up less space in
3635// the RTP packet.
3636static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3637 RTC_DCHECK(used_mids);
3638 // We're boring: just generate MIDs 0, 1, 2, ...
3639 size_t i = 0;
3640 std::set<std::string>::iterator it;
3641 bool inserted;
3642 do {
3643 std::string mid = rtc::ToString(i++);
3644 auto insert_result = used_mids->insert(mid);
3645 it = insert_result.first;
3646 inserted = insert_result.second;
3647 } while (!inserted);
3648 return *it;
3649}
3650
3651static cricket::MediaDescriptionOptions
3652GetMediaDescriptionOptionsForTransceiver(
3653 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3654 transceiver,
3655 const std::string& mid) {
3656 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003657 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003658 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003659 // This behavior is specified in JSEP. The gist is that:
3660 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3661 // sendrecv.
3662 // 2. If the MSID is included, then it must be included in any subsequent
3663 // offer/answer exactly the same until the RtpTransceiver is stopped.
3664 if (!transceiver->stopped() &&
3665 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3666 transceiver->internal()->has_ever_been_used_to_send())) {
3667 cricket::SenderOptions sender_options;
3668 sender_options.track_id = transceiver->sender()->id();
3669 sender_options.stream_ids = transceiver->sender()->stream_ids();
3670 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3671 // set in the RTP parameters when the transceiver was added.
3672 sender_options.num_sim_layers = 1;
3673 media_description_options.sender_options.push_back(sender_options);
3674 }
Steve Antondcc3c022017-12-22 16:02:54 -08003675 return media_description_options;
3676}
3677
3678void PeerConnection::GetOptionsForUnifiedPlanOffer(
3679 const RTCOfferAnswerOptions& offer_answer_options,
3680 cricket::MediaSessionOptions* session_options) {
3681 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3682 // Offers) and 5.2.2 (Subsequent Offers).
3683 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3684 const ContentInfos& local_contents =
3685 (local_description() ? local_description()->description()->contents()
3686 : ContentInfos());
3687 const ContentInfos& remote_contents =
3688 (remote_description() ? remote_description()->description()->contents()
3689 : ContentInfos());
3690 // The mline indices that can be recycled. New transceivers should reuse these
3691 // slots first.
3692 std::queue<size_t> recycleable_mline_indices;
3693 // Track the MIDs used in previous offer/answer exchanges and the current
3694 // offer so that new, unique MIDs are generated.
3695 std::set<std::string> used_mids = seen_mids_;
3696 // First, go through each media section that exists in either the local or
3697 // remote description and generate a media section in this offer for the
3698 // associated transceiver. If a media section can be recycled, generate a
3699 // default, rejected media section here that can be later overwritten.
3700 for (size_t i = 0;
3701 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3702 // Either |local_content| or |remote_content| is non-null.
3703 const ContentInfo* local_content =
3704 (i < local_contents.size() ? &local_contents[i] : nullptr);
3705 const ContentInfo* remote_content =
3706 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3707 bool had_been_rejected = (local_content && local_content->rejected) ||
3708 (remote_content && remote_content->rejected);
3709 const std::string& mid =
3710 (local_content ? local_content->name : remote_content->name);
3711 cricket::MediaType media_type =
3712 (local_content ? local_content->media_description()->type()
3713 : remote_content->media_description()->type());
3714 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3715 media_type == cricket::MEDIA_TYPE_VIDEO) {
3716 auto transceiver = GetAssociatedTransceiver(mid);
3717 RTC_CHECK(transceiver);
3718 // A media section is considered eligible for recycling if it is marked as
3719 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003720 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003721 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003722 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3723 RtpTransceiverDirection::kInactive,
3724 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003725 recycleable_mline_indices.push(i);
3726 } else {
3727 session_options->media_description_options.push_back(
3728 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3729 // CreateOffer shouldn't really cause any state changes in
3730 // PeerConnection, but we need a way to match new transceivers to new
3731 // media sections in SetLocalDescription and JSEP specifies this is done
3732 // by recording the index of the media section generated for the
3733 // transceiver in the offer.
3734 transceiver->internal()->set_mline_index(i);
3735 }
3736 } else {
3737 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003738 RTC_CHECK(GetDataMid());
3739 if (had_been_rejected || mid != *GetDataMid()) {
3740 session_options->media_description_options.push_back(
3741 GetMediaDescriptionOptionsForRejectedData(mid));
3742 } else {
3743 session_options->media_description_options.push_back(
3744 GetMediaDescriptionOptionsForActiveData(mid));
3745 }
Steve Antondcc3c022017-12-22 16:02:54 -08003746 }
3747 }
3748 // Next, look for transceivers that are newly added (that is, are not stopped
3749 // and not associated). Reuse media sections marked as recyclable first,
3750 // otherwise append to the end of the offer. New media sections should be
3751 // added in the order they were added to the PeerConnection.
3752 for (auto transceiver : transceivers_) {
3753 if (transceiver->mid() || transceiver->stopped()) {
3754 continue;
3755 }
3756 size_t mline_index;
3757 if (!recycleable_mline_indices.empty()) {
3758 mline_index = recycleable_mline_indices.front();
3759 recycleable_mline_indices.pop();
3760 session_options->media_description_options[mline_index] =
3761 GetMediaDescriptionOptionsForTransceiver(transceiver,
3762 AllocateMid(&used_mids));
3763 } else {
3764 mline_index = session_options->media_description_options.size();
3765 session_options->media_description_options.push_back(
3766 GetMediaDescriptionOptionsForTransceiver(transceiver,
3767 AllocateMid(&used_mids)));
3768 }
3769 // See comment above for why CreateOffer changes the transceiver's state.
3770 transceiver->internal()->set_mline_index(mline_index);
3771 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003772 // Lastly, add a m-section if we have local data channels and an m section
3773 // does not already exist.
3774 if (!GetDataMid() && HasDataChannels()) {
3775 session_options->media_description_options.push_back(
3776 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3777 }
Steve Antondcc3c022017-12-22 16:02:54 -08003778}
3779
3780void PeerConnection::GetOptionsForAnswer(
3781 const RTCOfferAnswerOptions& offer_answer_options,
3782 cricket::MediaSessionOptions* session_options) {
3783 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3784
3785 if (IsUnifiedPlan()) {
3786 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3787 } else {
3788 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3789 }
3790
Steve Antonfa2260d2017-12-28 16:38:23 -08003791 // Intentionally unset the data channel type for RTP data channel. Otherwise
3792 // the RTP data channels would be successfully negotiated by default and the
3793 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3794 // We want to leave RTP data channels broken, so people won't try to use them.
3795 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3796 session_options->data_channel_type = data_channel_type();
3797 }
3798
Steve Antondcc3c022017-12-22 16:02:54 -08003799 // Apply ICE renomination flag.
3800 for (auto& options : session_options->media_description_options) {
3801 options.transport_options.enable_ice_renomination =
3802 configuration_.enable_ice_renomination;
3803 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003804
3805 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003806 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003807 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003808}
3809
Steve Antondcc3c022017-12-22 16:02:54 -08003810void PeerConnection::GetOptionsForPlanBAnswer(
3811 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003812 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003813 // Figure out transceiver directional preferences.
3814 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3815 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3816
3817 // By default, generate sendrecv/recvonly m= sections. The direction is also
3818 // restricted by the direction in the offer.
3819 bool recv_audio = true;
3820 bool recv_video = true;
3821
3822 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003823 if (offer_answer_options.offer_to_receive_audio !=
3824 RTCOfferAnswerOptions::kUndefined) {
3825 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003826 }
Steve Antondcc3c022017-12-22 16:02:54 -08003827 if (offer_answer_options.offer_to_receive_video !=
3828 RTCOfferAnswerOptions::kUndefined) {
3829 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003830 }
3831
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003832 absl::optional<size_t> audio_index;
3833 absl::optional<size_t> video_index;
3834 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003835
3836 // Generate m= sections that match those in the offer.
3837 // Note that mediasession.cc will handle intersection our preferred
3838 // direction with the offered direction.
3839 GenerateMediaDescriptionOptions(
3840 remote_description(),
3841 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3842 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3843 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003844
3845 cricket::MediaDescriptionOptions* audio_media_description_options =
3846 !audio_index ? nullptr
3847 : &session_options->media_description_options[*audio_index];
3848 cricket::MediaDescriptionOptions* video_media_description_options =
3849 !video_index ? nullptr
3850 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003851
Steve Anton4171afb2017-11-20 10:20:22 -08003852 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003853 video_media_description_options,
3854 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003855}
zhihuangaf388472016-11-02 16:49:48 -07003856
Steve Antondcc3c022017-12-22 16:02:54 -08003857void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3858 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3859 cricket::MediaSessionOptions* session_options) {
3860 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3861 // Answers) and 5.3.2 (Subsequent Answers).
3862 RTC_DCHECK(remote_description());
3863 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3864 for (const ContentInfo& content :
3865 remote_description()->description()->contents()) {
3866 cricket::MediaType media_type = content.media_description()->type();
3867 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3868 media_type == cricket::MEDIA_TYPE_VIDEO) {
3869 auto transceiver = GetAssociatedTransceiver(content.name);
3870 RTC_CHECK(transceiver);
3871 session_options->media_description_options.push_back(
3872 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3873 } else {
3874 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003875 // Reject all data sections if data channels are disabled.
3876 // Reject a data section if it has already been rejected.
3877 // Reject all data sections except for the first one.
3878 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3879 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003880 session_options->media_description_options.push_back(
3881 GetMediaDescriptionOptionsForRejectedData(content.name));
3882 } else {
3883 session_options->media_description_options.push_back(
3884 GetMediaDescriptionOptionsForActiveData(content.name));
3885 }
Steve Antondcc3c022017-12-22 16:02:54 -08003886 }
3887 }
htaa2a49d92016-03-04 02:51:39 -08003888}
3889
zhihuang1c378ed2017-08-17 14:10:50 -07003890void PeerConnection::GenerateMediaDescriptionOptions(
3891 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003892 RtpTransceiverDirection audio_direction,
3893 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003894 absl::optional<size_t>* audio_index,
3895 absl::optional<size_t>* video_index,
3896 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003897 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003898 for (const cricket::ContentInfo& content :
3899 session_desc->description()->contents()) {
3900 if (IsAudioContent(&content)) {
3901 // If we already have an audio m= section, reject this extra one.
3902 if (*audio_index) {
3903 session_options->media_description_options.push_back(
3904 cricket::MediaDescriptionOptions(
3905 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003906 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003907 } else {
3908 session_options->media_description_options.push_back(
3909 cricket::MediaDescriptionOptions(
3910 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003911 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003912 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003913 }
3914 } else if (IsVideoContent(&content)) {
3915 // If we already have an video m= section, reject this extra one.
3916 if (*video_index) {
3917 session_options->media_description_options.push_back(
3918 cricket::MediaDescriptionOptions(
3919 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003920 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003921 } else {
3922 session_options->media_description_options.push_back(
3923 cricket::MediaDescriptionOptions(
3924 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003925 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003926 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003927 }
3928 } else {
3929 RTC_DCHECK(IsDataContent(&content));
3930 // If we already have an data m= section, reject this extra one.
3931 if (*data_index) {
3932 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003933 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003934 } else {
3935 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003936 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003937 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003938 }
3939 }
htaa2a49d92016-03-04 02:51:39 -08003940 }
deadbeefab9b2d12015-10-14 11:33:11 -07003941}
3942
Steve Antonfa2260d2017-12-28 16:38:23 -08003943cricket::MediaDescriptionOptions
3944PeerConnection::GetMediaDescriptionOptionsForActiveData(
3945 const std::string& mid) const {
3946 // Direction for data sections is meaningless, but legacy endpoints might
3947 // expect sendrecv.
3948 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3949 RtpTransceiverDirection::kSendRecv,
3950 /*stopped=*/false);
3951 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3952 return options;
3953}
3954
3955cricket::MediaDescriptionOptions
3956PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3957 const std::string& mid) const {
3958 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3959 RtpTransceiverDirection::kInactive,
3960 /*stopped=*/true);
3961 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3962 return options;
3963}
3964
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003965absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08003966 switch (data_channel_type_) {
3967 case cricket::DCT_RTP:
3968 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003969 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08003970 }
3971 return rtp_data_channel_->content_name();
3972 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07003973 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08003974 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003975 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08003976 }
3977}
3978
Steve Anton4171afb2017-11-20 10:20:22 -08003979void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3980 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3981 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003982 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003983}
3984
Steve Anton4171afb2017-11-20 10:20:22 -08003985void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003986 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003987 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003988 cricket::MediaType media_type,
3989 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07003990 RTC_DCHECK(!IsUnifiedPlan());
3991
Steve Anton4171afb2017-11-20 10:20:22 -08003992 std::vector<RtpSenderInfo>* current_senders =
3993 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003994
Steve Anton4171afb2017-11-20 10:20:22 -08003995 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003996 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003997 for (auto sender_it = current_senders->begin();
3998 sender_it != current_senders->end();
3999 /* incremented manually */) {
4000 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004001 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004002 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004003 std::string params_stream_id;
4004 if (params) {
4005 params_stream_id =
4006 (!params->first_stream_id().empty() ? params->first_stream_id()
4007 : kDefaultStreamId);
4008 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004009 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004010 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004011 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004012 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004013 sender_exists) {
4014 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004015 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004016 OnRemoteSenderRemoved(info, media_type);
4017 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004018 }
4019 }
4020
Steve Anton4171afb2017-11-20 10:20:22 -08004021 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004022 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004023 if (!params.has_ssrcs()) {
4024 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4025 // sender, this means it is coming from a Unified Plan endpoint,so we just
4026 // create a default.
4027 default_sender_needed = true;
4028 break;
4029 }
4030
Seth Hampson845e8782018-03-02 11:34:10 -08004031 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004032 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004033 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4034 // not supported in Plan B, we just take the first here and create the
4035 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004036 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004037 (!params.first_stream_id().empty() ? params.first_stream_id()
4038 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004039 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004040 uint32_t ssrc = params.first_ssrc();
4041
4042 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004043 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004044 if (!stream) {
4045 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004046 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004047 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004048 remote_streams_->AddStream(stream);
4049 new_streams->AddStream(stream);
4050 }
4051
Steve Anton4171afb2017-11-20 10:20:22 -08004052 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004053 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004054 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004055 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004056 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004057 }
4058 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004059
Steve Anton4171afb2017-11-20 10:20:22 -08004060 // Add default sender if necessary.
4061 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004062 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004063 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004064 if (!default_stream) {
4065 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004066 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004067 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004068 remote_streams_->AddStream(default_stream);
4069 new_streams->AddStream(default_stream);
4070 }
Steve Anton4171afb2017-11-20 10:20:22 -08004071 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4072 ? kDefaultAudioSenderId
4073 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004074 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004075 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004076 if (!default_sender_info) {
4077 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004078 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004079 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004080 }
4081 }
deadbeefab9b2d12015-10-14 11:33:11 -07004082}
4083
Steve Anton4171afb2017-11-20 10:20:22 -08004084void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4085 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004086 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4087 << " receiver for track_id=" << sender_info.sender_id
4088 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004089
Steve Anton3d954a62018-04-02 11:27:23 -07004090 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004091 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004092 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004093 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004094 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004095 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004096 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004097 }
4098}
4099
Steve Anton4171afb2017-11-20 10:20:22 -08004100void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4101 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004102 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4103 << " receiver for track_id=" << sender_info.sender_id
4104 << " and stream_id=" << sender_info.stream_id;
4105
Seth Hampson845e8782018-03-02 11:34:10 -08004106 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004107
Henrik Boström933d8b02017-10-10 10:05:16 -07004108 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004109 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004110 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4111 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004112 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004113 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004114 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004115 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004116 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004117 }
4118 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004119 // Stopping or destroying a VideoRtpReceiver will end the
4120 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004121 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004122 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004123 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004124 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004125 // There's no guarantee the track is still available, e.g. the track may
4126 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004127 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004128 }
4129 } else {
nisseede5da42017-01-12 05:15:36 -08004130 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004131 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004132 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004133 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004134 }
deadbeefab9b2d12015-10-14 11:33:11 -07004135}
4136
4137void PeerConnection::UpdateEndedRemoteMediaStreams() {
4138 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4139 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4140 MediaStreamInterface* stream = remote_streams_->at(i);
4141 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4142 streams_to_remove.push_back(stream);
4143 }
4144 }
4145
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004146 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004147 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004148 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004149 }
4150}
4151
Steve Anton4171afb2017-11-20 10:20:22 -08004152void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004153 const std::vector<cricket::StreamParams>& streams,
4154 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004155 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004156
Seth Hampson845e8782018-03-02 11:34:10 -08004157 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004158 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004159 for (auto sender_it = current_senders->begin();
4160 sender_it != current_senders->end();
4161 /* incremented manually */) {
4162 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004163 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004164 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4165 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004166 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004167 OnLocalSenderRemoved(info, media_type);
4168 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004169 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004170 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004171 }
4172 }
4173
Steve Anton4171afb2017-11-20 10:20:22 -08004174 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004175 for (const cricket::StreamParams& params : streams) {
4176 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004177 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004178 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004179 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004180 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004181 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004182 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004183 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004184 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004185 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004186 }
4187 }
4188}
4189
Steve Anton4171afb2017-11-20 10:20:22 -08004190void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4191 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004192 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004193 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004194 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004195 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4196 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004197 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004198 return;
4199 }
4200
deadbeeffac06552015-11-25 11:26:01 -08004201 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004202 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004203 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004204 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004205 }
deadbeeffac06552015-11-25 11:26:01 -08004206
Seth Hampson5b4f0752018-04-02 16:31:36 -07004207 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004208 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004209}
4210
Steve Anton4171afb2017-11-20 10:20:22 -08004211void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4212 cricket::MediaType media_type) {
4213 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004214 if (!sender) {
4215 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004216 // SessionDescriptions has been renegotiated.
4217 return;
4218 }
deadbeeffac06552015-11-25 11:26:01 -08004219
4220 // A sender has been removed from the SessionDescription but it's still
4221 // associated with the PeerConnection. This only occurs if the SDP doesn't
4222 // match with the calls to CreateSender, AddStream and RemoveStream.
4223 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004224 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004225 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004226 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004227 }
deadbeeffac06552015-11-25 11:26:01 -08004228
Steve Anton4171afb2017-11-20 10:20:22 -08004229 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004230}
4231
4232void PeerConnection::UpdateLocalRtpDataChannels(
4233 const cricket::StreamParamsVec& streams) {
4234 std::vector<std::string> existing_channels;
4235
4236 // Find new and active data channels.
4237 for (const cricket::StreamParams& params : streams) {
4238 // |it->sync_label| is actually the data channel label. The reason is that
4239 // we use the same naming of data channels as we do for
4240 // MediaStreams and Tracks.
4241 // For MediaStreams, the sync_label is the MediaStream label and the
4242 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004243 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004244 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004245 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004246 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004247 continue;
4248 }
4249 // Set the SSRC the data channel should use for sending.
4250 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4251 existing_channels.push_back(data_channel_it->first);
4252 }
4253
4254 UpdateClosingRtpDataChannels(existing_channels, true);
4255}
4256
4257void PeerConnection::UpdateRemoteRtpDataChannels(
4258 const cricket::StreamParamsVec& streams) {
4259 std::vector<std::string> existing_channels;
4260
4261 // Find new and active data channels.
4262 for (const cricket::StreamParams& params : streams) {
4263 // The data channel label is either the mslabel or the SSRC if the mslabel
4264 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004265 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004266 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004267 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004268 auto data_channel_it = rtp_data_channels_.find(label);
4269 if (data_channel_it == rtp_data_channels_.end()) {
4270 // This is a new data channel.
4271 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4272 } else {
4273 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4274 }
4275 existing_channels.push_back(label);
4276 }
4277
4278 UpdateClosingRtpDataChannels(existing_channels, false);
4279}
4280
4281void PeerConnection::UpdateClosingRtpDataChannels(
4282 const std::vector<std::string>& active_channels,
4283 bool is_local_update) {
4284 auto it = rtp_data_channels_.begin();
4285 while (it != rtp_data_channels_.end()) {
4286 DataChannel* data_channel = it->second;
4287 if (std::find(active_channels.begin(), active_channels.end(),
4288 data_channel->label()) != active_channels.end()) {
4289 ++it;
4290 continue;
4291 }
4292
4293 if (is_local_update) {
4294 data_channel->SetSendSsrc(0);
4295 } else {
4296 data_channel->RemotePeerRequestClose();
4297 }
4298
4299 if (data_channel->state() == DataChannel::kClosed) {
4300 rtp_data_channels_.erase(it);
4301 it = rtp_data_channels_.begin();
4302 } else {
4303 ++it;
4304 }
4305 }
4306}
4307
4308void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4309 uint32_t remote_ssrc) {
4310 rtc::scoped_refptr<DataChannel> channel(
4311 InternalCreateDataChannel(label, nullptr));
4312 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004313 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004314 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004315 return;
4316 }
4317 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004318 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4319 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004320 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004321}
4322
4323rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4324 const std::string& label,
4325 const InternalDataChannelInit* config) {
4326 if (IsClosed()) {
4327 return nullptr;
4328 }
Steve Anton75737c02017-11-06 10:37:17 -08004329 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004330 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004331 << "InternalCreateDataChannel: Data is not supported in this call.";
4332 return nullptr;
4333 }
4334 InternalDataChannelInit new_config =
4335 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004336 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004337 if (new_config.id < 0) {
4338 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004339 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004340 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004341 RTC_LOG(LS_ERROR)
4342 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004343 return nullptr;
4344 }
4345 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004346 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004347 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004348 return nullptr;
4349 }
4350 }
4351
Steve Anton75737c02017-11-06 10:37:17 -08004352 rtc::scoped_refptr<DataChannel> channel(
4353 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004354 if (!channel) {
4355 sid_allocator_.ReleaseSid(new_config.id);
4356 return nullptr;
4357 }
4358
4359 if (channel->data_channel_type() == cricket::DCT_RTP) {
4360 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004361 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4362 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004363 return nullptr;
4364 }
4365 rtp_data_channels_[channel->label()] = channel;
4366 } else {
4367 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4368 sctp_data_channels_.push_back(channel);
4369 channel->SignalClosed.connect(this,
4370 &PeerConnection::OnSctpDataChannelClosed);
4371 }
4372
Steve Anton2d8609c2018-01-23 16:38:46 -08004373 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004374 return channel;
4375}
4376
4377bool PeerConnection::HasDataChannels() const {
4378 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4379}
4380
4381void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4382 for (const auto& channel : sctp_data_channels_) {
4383 if (channel->id() < 0) {
4384 int sid;
4385 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004386 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004387 continue;
4388 }
4389 channel->SetSctpSid(sid);
4390 }
4391 }
4392}
4393
4394void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004395 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004396 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4397 ++it) {
4398 if (it->get() == channel) {
4399 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004400 // After the closing procedure is done, it's safe to use this ID for
4401 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004402 sid_allocator_.ReleaseSid(channel->id());
4403 }
deadbeefbd292462015-12-14 18:15:29 -08004404 // Since this method is triggered by a signal from the DataChannel,
4405 // we can't free it directly here; we need to free it asynchronously.
4406 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004407 sctp_data_channels_.erase(it);
Steve Antonbb192762018-08-31 11:57:02 -07004408 async_invoker_.AsyncInvoke<void>(
4409 RTC_FROM_HERE, signaling_thread(),
4410 [this] { sctp_data_channels_to_free_.clear(); });
deadbeefab9b2d12015-10-14 11:33:11 -07004411 return;
4412 }
4413 }
4414}
4415
deadbeefab9b2d12015-10-14 11:33:11 -07004416void PeerConnection::OnDataChannelDestroyed() {
4417 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4418 // DataChannel may callback to us and try to modify the list.
4419 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4420 temp_rtp_dcs.swap(rtp_data_channels_);
4421 for (const auto& kv : temp_rtp_dcs) {
4422 kv.second->OnTransportChannelDestroyed();
4423 }
4424
4425 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4426 temp_sctp_dcs.swap(sctp_data_channels_);
4427 for (const auto& channel : temp_sctp_dcs) {
4428 channel->OnTransportChannelDestroyed();
4429 }
4430}
4431
4432void PeerConnection::OnDataChannelOpenMessage(
4433 const std::string& label,
4434 const InternalDataChannelInit& config) {
4435 rtc::scoped_refptr<DataChannel> channel(
4436 InternalCreateDataChannel(label, &config));
4437 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004438 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004439 return;
4440 }
4441
deadbeefa601f5c2016-06-06 14:27:39 -07004442 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4443 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004444 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004445 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004446}
4447
Steve Anton4171afb2017-11-20 10:20:22 -08004448rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4449PeerConnection::GetAudioTransceiver() const {
4450 // This method only works with Plan B SDP, where there is a single
4451 // audio/video transceiver.
4452 RTC_DCHECK(!IsUnifiedPlan());
4453 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004454 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004455 return transceiver;
4456 }
4457 }
4458 RTC_NOTREACHED();
4459 return nullptr;
4460}
4461
4462rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4463PeerConnection::GetVideoTransceiver() const {
4464 // This method only works with Plan B SDP, where there is a single
4465 // audio/video transceiver.
4466 RTC_DCHECK(!IsUnifiedPlan());
4467 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004468 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004469 return transceiver;
4470 }
4471 }
4472 RTC_NOTREACHED();
4473 return nullptr;
4474}
4475
4476// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4477// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004478bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004479 switch (type) {
4480 case cricket::MEDIA_TYPE_AUDIO:
4481 return !GetAudioTransceiver()->internal()->senders().empty();
4482 case cricket::MEDIA_TYPE_VIDEO:
4483 return !GetVideoTransceiver()->internal()->senders().empty();
4484 case cricket::MEDIA_TYPE_DATA:
4485 return false;
4486 }
4487 RTC_NOTREACHED();
4488 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004489}
4490
Steve Anton4171afb2017-11-20 10:20:22 -08004491rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4492PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4493 for (auto transceiver : transceivers_) {
4494 for (auto sender : transceiver->internal()->senders()) {
4495 if (sender->track() == track) {
4496 return sender;
4497 }
4498 }
4499 }
4500 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004501}
4502
Steve Anton4171afb2017-11-20 10:20:22 -08004503rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4504PeerConnection::FindSenderById(const std::string& sender_id) const {
4505 for (auto transceiver : transceivers_) {
4506 for (auto sender : transceiver->internal()->senders()) {
4507 if (sender->id() == sender_id) {
4508 return sender;
4509 }
4510 }
4511 }
4512 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004513}
4514
Steve Anton4171afb2017-11-20 10:20:22 -08004515rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4516PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4517 for (auto transceiver : transceivers_) {
4518 for (auto receiver : transceiver->internal()->receivers()) {
4519 if (receiver->id() == receiver_id) {
4520 return receiver;
4521 }
4522 }
4523 }
4524 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004525}
4526
Steve Anton4171afb2017-11-20 10:20:22 -08004527std::vector<PeerConnection::RtpSenderInfo>*
4528PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4529 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4530 media_type == cricket::MEDIA_TYPE_VIDEO);
4531 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4532 ? &remote_audio_sender_infos_
4533 : &remote_video_sender_infos_;
4534}
4535
4536std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004537 cricket::MediaType media_type) {
4538 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4539 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004540 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4541 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004542}
4543
Steve Anton4171afb2017-11-20 10:20:22 -08004544const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4545 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004546 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004547 const std::string sender_id) const {
4548 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004549 if (sender_info.stream_id == stream_id &&
4550 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004551 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004552 }
4553 }
4554 return nullptr;
4555}
4556
4557DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4558 for (const auto& channel : sctp_data_channels_) {
4559 if (channel->id() == sid) {
4560 return channel;
4561 }
4562 }
4563 return nullptr;
4564}
4565
deadbeef91dd5672016-05-18 16:55:30 -07004566bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004567 const cricket::ServerAddresses& stun_servers,
4568 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004569 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004570 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004571 // To handle both internal and externally created port allocator, we will
4572 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004573 port_allocator_flags_ = port_allocator_->flags();
4574 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4575 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4576 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004577 // If the disable-IPv6 flag was specified, we'll not override it
4578 // by experiment.
4579 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004580 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004581 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4582 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004583 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004584 }
4585
zhihuangb09b3f92017-03-07 14:40:51 -08004586 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004587 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004588 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004589 }
4590
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004591 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004592 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004593 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004594 }
4595
honghaiz60347052016-05-31 18:29:12 -07004596 if (configuration.candidate_network_policy ==
4597 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004598 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004599 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004600 }
4601
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004602 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004603 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004604 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4605 }
4606
Qingsi Wanga2d60672018-04-11 16:57:45 -07004607 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004608 // No step delay is used while allocating ports.
4609 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4610 port_allocator_->set_candidate_filter(
4611 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004612 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004613
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004614 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004615 for (auto& turn_server : turn_servers_copy) {
4616 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004617 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004618 // Call this last since it may create pooled allocator sessions using the
4619 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004620 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004621 stun_servers, std::move(turn_servers_copy),
4622 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4623 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004624 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004625 return true;
4626}
4627
deadbeef91dd5672016-05-18 16:55:30 -07004628bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004629 const cricket::ServerAddresses& stun_servers,
4630 const std::vector<cricket::RelayServerConfig>& turn_servers,
4631 IceTransportsType type,
4632 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004633 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004634 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004635 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004636 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004637 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004638 // According to JSEP, after setLocalDescription, changing the candidate pool
4639 // size is not allowed, and changing the set of ICE servers will not result
4640 // in new candidates being gathered.
4641 if (local_description()) {
4642 port_allocator_->FreezeCandidatePool();
4643 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004644 // Add the custom tls turn servers if they exist.
4645 auto turn_servers_copy = turn_servers;
4646 for (auto& turn_server : turn_servers_copy) {
4647 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4648 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004649 // Call this last since it may create pooled allocator sessions using the
4650 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004651 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004652 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4653 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004654}
4655
Steve Antonba818672017-11-06 10:21:57 -08004656cricket::ChannelManager* PeerConnection::channel_manager() const {
4657 return factory_->channel_manager();
4658}
4659
Elad Alon99c3fe52017-10-13 16:29:40 +02004660bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004661 std::unique_ptr<RtcEventLogOutput> output,
4662 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004663 if (!event_log_) {
4664 return false;
4665 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004666 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004667}
4668
4669void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004670 if (event_log_) {
4671 event_log_->StopLogging();
4672 }
ivoc14d5dbe2016-07-04 07:06:55 -07004673}
nisseeaabdf62017-05-05 02:23:02 -07004674
Steve Anton75737c02017-11-06 10:37:17 -08004675cricket::BaseChannel* PeerConnection::GetChannel(
4676 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004677 for (auto transceiver : transceivers_) {
4678 cricket::BaseChannel* channel = transceiver->internal()->channel();
4679 if (channel && channel->content_name() == content_name) {
4680 return channel;
4681 }
Steve Anton75737c02017-11-06 10:37:17 -08004682 }
4683 if (rtp_data_channel() &&
4684 rtp_data_channel()->content_name() == content_name) {
4685 return rtp_data_channel();
4686 }
4687 return nullptr;
4688}
4689
4690bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4691 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004692 RTC_LOG(LS_INFO)
4693 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004694 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004695 return false;
4696 }
4697 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004698 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004699 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004700 return false;
4701 }
4702
Zhi Huange830e682018-03-30 10:48:35 -07004703 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4704 if (dtls_role) {
4705 *role = *dtls_role;
4706 return true;
4707 }
4708 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004709}
4710
4711bool PeerConnection::GetSslRole(const std::string& content_name,
4712 rtc::SSLRole* role) {
4713 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004714 RTC_LOG(LS_INFO)
4715 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004716 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004717 return false;
4718 }
4719
Zhi Huange830e682018-03-30 10:48:35 -07004720 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4721 if (dtls_role) {
4722 *role = *dtls_role;
4723 return true;
4724 }
4725 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004726}
4727
Steve Antonf8470812017-12-04 10:46:21 -08004728void PeerConnection::SetSessionError(SessionError error,
4729 const std::string& error_desc) {
4730 RTC_DCHECK_RUN_ON(signaling_thread());
4731 if (error != session_error_) {
4732 session_error_ = error;
4733 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004734 }
4735}
4736
Zhi Huange830e682018-03-30 10:48:35 -07004737RTCError PeerConnection::UpdateSessionState(
4738 SdpType type,
4739 cricket::ContentSource source,
4740 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004741 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004742
4743 // If there's already a pending error then no state transition should happen.
4744 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004745 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004746
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004747 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004748 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004749 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004750 }
4751
4752 // Update the signaling state according to the specified state machine (see
4753 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004754 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004755 ChangeSignalingState(source == cricket::CS_LOCAL
4756 ? PeerConnectionInterface::kHaveLocalOffer
4757 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004758 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004759 ChangeSignalingState(source == cricket::CS_LOCAL
4760 ? PeerConnectionInterface::kHaveLocalPrAnswer
4761 : PeerConnectionInterface::kHaveRemotePrAnswer);
4762 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004763 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004764 ChangeSignalingState(PeerConnectionInterface::kStable);
4765 }
4766
4767 // Update internal objects according to the session description's media
4768 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004769 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004770 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004771 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004772 }
4773
Steve Anton8a006912017-12-04 15:25:56 -08004774 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004775}
4776
Steve Anton8a006912017-12-04 15:25:56 -08004777RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004778 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004779 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004780 const SessionDescriptionInterface* sdesc =
4781 (source == cricket::CS_LOCAL ? local_description()
4782 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004783 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004784
4785 // Push down the new SDP media section for each audio/video transceiver.
4786 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004787 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004788 FindMediaSectionForTransceiver(transceiver, sdesc);
4789 cricket::BaseChannel* channel = transceiver->internal()->channel();
4790 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004791 continue;
4792 }
4793 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004794 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004795 if (!content_desc) {
4796 continue;
4797 }
4798 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004799 bool success = (source == cricket::CS_LOCAL)
4800 ? channel->SetLocalContent(content_desc, type, &error)
4801 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004802 if (!success) {
4803 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4804 }
4805 }
4806
4807 // If using the RtpDataChannel, push down the new SDP section for it too.
4808 if (rtp_data_channel_) {
4809 const ContentInfo* data_content =
4810 cricket::GetFirstDataContent(sdesc->description());
4811 if (data_content && !data_content->rejected) {
4812 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004813 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004814 if (data_desc) {
4815 std::string error;
4816 bool success =
4817 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004818 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004819 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004820 if (!success) {
4821 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4822 std::move(error));
4823 }
Steve Anton75737c02017-11-06 10:37:17 -08004824 }
4825 }
4826 }
Steve Antoned10bd92017-12-05 10:52:59 -08004827
Steve Anton75737c02017-11-06 10:37:17 -08004828 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4829 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4830 if (sctp_transport_ && local_description() && remote_description() &&
4831 cricket::GetFirstDataContent(local_description()->description()) &&
4832 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004833 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004834 RTC_FROM_HERE,
4835 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004836 if (!success) {
4837 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4838 "Failed to push down SCTP parameters.");
4839 }
Steve Anton75737c02017-11-06 10:37:17 -08004840 }
Steve Antoned10bd92017-12-05 10:52:59 -08004841
Steve Anton8a006912017-12-04 15:25:56 -08004842 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004843}
4844
4845bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4846 RTC_DCHECK(network_thread()->IsCurrent());
4847 RTC_DCHECK(local_description());
4848 RTC_DCHECK(remote_description());
4849 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4850 // When we support "max-message-size", that would also be pushed down here.
4851 return sctp_transport_->Start(
4852 GetSctpPort(local_description()->description()),
4853 GetSctpPort(remote_description()->description()));
4854}
4855
Steve Anton8a006912017-12-04 15:25:56 -08004856RTCError PeerConnection::PushdownTransportDescription(
4857 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004858 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004859 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004860
Zhi Huange830e682018-03-30 10:48:35 -07004861 if (source == cricket::CS_LOCAL) {
4862 const SessionDescriptionInterface* sdesc = local_description();
4863 RTC_DCHECK(sdesc);
4864 return transport_controller_->SetLocalDescription(type,
4865 sdesc->description());
4866 } else {
4867 const SessionDescriptionInterface* sdesc = remote_description();
4868 RTC_DCHECK(sdesc);
4869 return transport_controller_->SetRemoteDescription(type,
4870 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004871 }
Steve Anton75737c02017-11-06 10:37:17 -08004872}
4873
4874bool PeerConnection::GetTransportDescription(
4875 const SessionDescription* description,
4876 const std::string& content_name,
4877 cricket::TransportDescription* tdesc) {
4878 if (!description || !tdesc) {
4879 return false;
4880 }
4881 const TransportInfo* transport_info =
4882 description->GetTransportInfoByName(content_name);
4883 if (!transport_info) {
4884 return false;
4885 }
4886 *tdesc = transport_info->description;
4887 return true;
4888}
4889
Steve Anton75737c02017-11-06 10:37:17 -08004890cricket::IceConfig PeerConnection::ParseIceConfig(
4891 const PeerConnectionInterface::RTCConfiguration& config) const {
4892 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004893 switch (config.continual_gathering_policy) {
4894 case PeerConnectionInterface::GATHER_ONCE:
4895 gathering_policy = cricket::GATHER_ONCE;
4896 break;
4897 case PeerConnectionInterface::GATHER_CONTINUALLY:
4898 gathering_policy = cricket::GATHER_CONTINUALLY;
4899 break;
4900 default:
4901 RTC_NOTREACHED();
4902 gathering_policy = cricket::GATHER_ONCE;
4903 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004904
Steve Anton75737c02017-11-06 10:37:17 -08004905 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004906 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4907 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004908 ice_config.prioritize_most_likely_candidate_pairs =
4909 config.prioritize_most_likely_ice_candidate_pairs;
4910 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004911 RTCConfigurationToIceConfigOptionalInt(
4912 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004913 ice_config.continual_gathering_policy = gathering_policy;
4914 ice_config.presume_writable_when_fully_relayed =
4915 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004916 ice_config.ice_check_interval_strong_connectivity =
4917 config.ice_check_interval_strong_connectivity;
4918 ice_config.ice_check_interval_weak_connectivity =
4919 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004920 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004921 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004922 ice_config.regather_all_networks_interval_range =
4923 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004924 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004925 return ice_config;
4926}
4927
Steve Anton75737c02017-11-06 10:37:17 -08004928bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4929 std::string* track_id) {
4930 if (!local_description()) {
4931 return false;
4932 }
4933 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4934 track_id);
4935}
4936
4937bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4938 std::string* track_id) {
4939 if (!remote_description()) {
4940 return false;
4941 }
4942 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4943 track_id);
4944}
4945
4946bool PeerConnection::SendData(const cricket::SendDataParams& params,
4947 const rtc::CopyOnWriteBuffer& payload,
4948 cricket::SendDataResult* result) {
4949 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004950 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004951 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004952 return false;
4953 }
4954 return rtp_data_channel_
4955 ? rtp_data_channel_->SendData(params, payload, result)
4956 : network_thread()->Invoke<bool>(
4957 RTC_FROM_HERE,
4958 Bind(&cricket::SctpTransportInternal::SendData,
4959 sctp_transport_.get(), params, payload, result));
4960}
4961
4962bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4963 if (!rtp_data_channel_ && !sctp_transport_) {
4964 // Don't log an error here, because DataChannels are expected to call
4965 // ConnectDataChannel in this state. It's the only way to initially tell
4966 // whether or not the underlying transport is ready.
4967 return false;
4968 }
4969 if (rtp_data_channel_) {
4970 rtp_data_channel_->SignalReadyToSendData.connect(
4971 webrtc_data_channel, &DataChannel::OnChannelReady);
4972 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4973 &DataChannel::OnDataReceived);
4974 } else {
4975 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4976 &DataChannel::OnChannelReady);
4977 SignalSctpDataReceived.connect(webrtc_data_channel,
4978 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004979 SignalSctpClosingProcedureStartedRemotely.connect(
4980 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
4981 SignalSctpClosingProcedureComplete.connect(
4982 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08004983 }
4984 return true;
4985}
4986
4987void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4988 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004989 RTC_LOG(LS_ERROR)
4990 << "DisconnectDataChannel called when rtp_data_channel_ and "
4991 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004992 return;
4993 }
4994 if (rtp_data_channel_) {
4995 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4996 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4997 } else {
4998 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4999 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005000 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5001 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005002 }
5003}
5004
5005void PeerConnection::AddSctpDataStream(int sid) {
5006 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005007 RTC_LOG(LS_ERROR)
5008 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005009 return;
5010 }
5011 network_thread()->Invoke<void>(
5012 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5013 sctp_transport_.get(), sid));
5014}
5015
5016void PeerConnection::RemoveSctpDataStream(int sid) {
5017 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005018 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005019 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005020 return;
5021 }
5022 network_thread()->Invoke<void>(
5023 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5024 sctp_transport_.get(), sid));
5025}
5026
5027bool PeerConnection::ReadyToSendData() const {
5028 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5029 sctp_ready_to_send_data_;
5030}
5031
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005032absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005033 if (sctp_mid_ && transport_controller_) {
5034 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5035 if (dtls_transport) {
5036 return dtls_transport->transport_name();
5037 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005038 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005039 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005040 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005041}
5042
Qingsi Wang72a43a12018-02-20 16:03:18 -08005043cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5044 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005045 network_thread()->Invoke<void>(
5046 RTC_FROM_HERE,
5047 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5048 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005049 return candidate_states_list;
5050}
5051
Steve Anton5dfde182018-02-06 10:34:40 -08005052std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5053 const {
5054 std::map<std::string, std::string> transport_names_by_mid;
5055 for (auto transceiver : transceivers_) {
5056 cricket::BaseChannel* channel = transceiver->internal()->channel();
5057 if (channel) {
5058 transport_names_by_mid[channel->content_name()] =
5059 channel->transport_name();
5060 }
Steve Anton75737c02017-11-06 10:37:17 -08005061 }
Steve Anton5dfde182018-02-06 10:34:40 -08005062 if (rtp_data_channel_) {
5063 transport_names_by_mid[rtp_data_channel_->content_name()] =
5064 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005065 }
5066 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005067 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005068 RTC_DCHECK(transport_name);
5069 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005070 }
Steve Anton5dfde182018-02-06 10:34:40 -08005071 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005072}
5073
Steve Anton5dfde182018-02-06 10:34:40 -08005074std::map<std::string, cricket::TransportStats>
5075PeerConnection::GetTransportStatsByNames(
5076 const std::set<std::string>& transport_names) {
5077 if (!network_thread()->IsCurrent()) {
5078 return network_thread()
5079 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5080 RTC_FROM_HERE,
5081 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005082 }
Steve Anton5dfde182018-02-06 10:34:40 -08005083 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5084 for (const std::string& transport_name : transport_names) {
5085 cricket::TransportStats transport_stats;
5086 bool success =
5087 transport_controller_->GetStats(transport_name, &transport_stats);
5088 if (success) {
5089 transport_stats_by_name[transport_name] = std::move(transport_stats);
5090 } else {
5091 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5092 << transport_name;
5093 }
5094 }
5095 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005096}
5097
5098bool PeerConnection::GetLocalCertificate(
5099 const std::string& transport_name,
5100 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005101 if (!certificate) {
5102 return false;
5103 }
5104 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5105 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005106}
5107
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005108std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005109 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005110 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005111}
5112
5113cricket::DataChannelType PeerConnection::data_channel_type() const {
5114 return data_channel_type_;
5115}
5116
5117bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5118 return pending_ice_restarts_.find(content_name) !=
5119 pending_ice_restarts_.end();
5120}
5121
Steve Anton75737c02017-11-06 10:37:17 -08005122bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5123 return transport_controller_->NeedsIceRestart(content_name);
5124}
5125
5126void PeerConnection::OnCertificateReady(
5127 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5128 transport_controller_->SetLocalCertificate(certificate);
5129}
5130
5131void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005132 SetSessionError(SessionError::kTransport,
5133 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005134}
5135
5136void PeerConnection::OnTransportControllerConnectionState(
5137 cricket::IceConnectionState state) {
5138 switch (state) {
5139 case cricket::kIceConnectionConnecting:
5140 // If the current state is Connected or Completed, then there were
5141 // writable channels but now there are not, so the next state must
5142 // be Disconnected.
5143 // kIceConnectionConnecting is currently used as the default,
5144 // un-connected state by the TransportController, so its only use is
5145 // detecting disconnections.
5146 if (ice_connection_state_ ==
5147 PeerConnectionInterface::kIceConnectionConnected ||
5148 ice_connection_state_ ==
5149 PeerConnectionInterface::kIceConnectionCompleted) {
5150 SetIceConnectionState(
5151 PeerConnectionInterface::kIceConnectionDisconnected);
5152 }
5153 break;
5154 case cricket::kIceConnectionFailed:
5155 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5156 break;
5157 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005158 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005159 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005160 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005161 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005162 break;
5163 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005164 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005165 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005166 if (ice_connection_state_ !=
5167 PeerConnectionInterface::kIceConnectionConnected) {
5168 // If jumping directly from "checking" to "connected",
5169 // signal "connected" first.
5170 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5171 }
5172 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005173 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005174 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005175 break;
5176 default:
5177 RTC_NOTREACHED();
5178 }
5179}
5180
5181void PeerConnection::OnTransportControllerCandidatesGathered(
5182 const std::string& transport_name,
5183 const cricket::Candidates& candidates) {
5184 RTC_DCHECK(signaling_thread()->IsCurrent());
5185 int sdp_mline_index;
5186 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005187 RTC_LOG(LS_ERROR)
5188 << "OnTransportControllerCandidatesGathered: content name "
5189 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005190 return;
5191 }
5192
5193 for (cricket::Candidates::const_iterator citer = candidates.begin();
5194 citer != candidates.end(); ++citer) {
5195 // Use transport_name as the candidate media id.
5196 std::unique_ptr<JsepIceCandidate> candidate(
5197 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5198 if (local_description()) {
5199 mutable_local_description()->AddCandidate(candidate.get());
5200 }
5201 OnIceCandidate(std::move(candidate));
5202 }
5203}
5204
5205void PeerConnection::OnTransportControllerCandidatesRemoved(
5206 const std::vector<cricket::Candidate>& candidates) {
5207 RTC_DCHECK(signaling_thread()->IsCurrent());
5208 // Sanity check.
5209 for (const cricket::Candidate& candidate : candidates) {
5210 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005211 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005212 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005213 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005214 return;
5215 }
5216 }
5217
5218 if (local_description()) {
5219 mutable_local_description()->RemoveCandidates(candidates);
5220 }
5221 OnIceCandidatesRemoved(candidates);
5222}
5223
5224void PeerConnection::OnTransportControllerDtlsHandshakeError(
5225 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005226 RTC_HISTOGRAM_ENUMERATION(
5227 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5228 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005229}
5230
Steve Antoned10bd92017-12-05 10:52:59 -08005231void PeerConnection::EnableSending() {
5232 for (auto transceiver : transceivers_) {
5233 cricket::BaseChannel* channel = transceiver->internal()->channel();
5234 if (channel && !channel->enabled()) {
5235 channel->Enable(true);
5236 }
Steve Anton75737c02017-11-06 10:37:17 -08005237 }
5238
Steve Anton4171afb2017-11-20 10:20:22 -08005239 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005240 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005241 }
Steve Anton75737c02017-11-06 10:37:17 -08005242}
5243
5244// Returns the media index for a local ice candidate given the content name.
5245bool PeerConnection::GetLocalCandidateMediaIndex(
5246 const std::string& content_name,
5247 int* sdp_mline_index) {
5248 if (!local_description() || !sdp_mline_index) {
5249 return false;
5250 }
5251
5252 bool content_found = false;
5253 const ContentInfos& contents = local_description()->description()->contents();
5254 for (size_t index = 0; index < contents.size(); ++index) {
5255 if (contents[index].name == content_name) {
5256 *sdp_mline_index = static_cast<int>(index);
5257 content_found = true;
5258 break;
5259 }
5260 }
5261 return content_found;
5262}
5263
5264bool PeerConnection::UseCandidatesInSessionDescription(
5265 const SessionDescriptionInterface* remote_desc) {
5266 if (!remote_desc) {
5267 return true;
5268 }
5269 bool ret = true;
5270
5271 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5272 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5273 for (size_t n = 0; n < candidates->count(); ++n) {
5274 const IceCandidateInterface* candidate = candidates->at(n);
5275 bool valid = false;
5276 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5277 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005278 RTC_LOG(LS_INFO)
5279 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005280 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005281 }
5282 continue;
5283 }
5284 ret = UseCandidate(candidate);
5285 if (!ret) {
5286 break;
5287 }
5288 }
5289 }
5290 return ret;
5291}
5292
5293bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5294 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5295 size_t remote_content_size =
5296 remote_description()->description()->contents().size();
5297 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005298 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005299 return false;
5300 }
5301
5302 cricket::ContentInfo content =
5303 remote_description()->description()->contents()[mediacontent_index];
5304 std::vector<cricket::Candidate> candidates;
5305 candidates.push_back(candidate->candidate());
5306 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005307 RTCError error =
5308 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005309 if (error.ok()) {
5310 // Candidates successfully submitted for checking.
5311 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5312 ice_connection_state_ ==
5313 PeerConnectionInterface::kIceConnectionDisconnected) {
5314 // If state is New, then the session has just gotten its first remote ICE
5315 // candidates, so go to Checking.
5316 // If state is Disconnected, the session is re-using old candidates or
5317 // receiving additional ones, so go to Checking.
5318 // If state is Connected, stay Connected.
5319 // TODO(bemasc): If state is Connected, and the new candidates are for a
5320 // newly added transport, then the state actually _should_ move to
5321 // checking. Add a way to distinguish that case.
5322 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5323 }
5324 // TODO(bemasc): If state is Completed, go back to Connected.
5325 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005326 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005327 }
5328 return true;
5329}
5330
5331void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005332 // Destroy video channel first since it may have a pointer to the
5333 // voice channel.
5334 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005335 if (!video_info || video_info->rejected) {
5336 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005337 }
5338
Steve Anton6fec8802017-12-04 10:37:29 -08005339 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5340 if (!audio_info || audio_info->rejected) {
5341 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005342 }
5343
5344 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5345 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005346 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005347 }
5348}
5349
Steve Antondcc3c022017-12-22 16:02:54 -08005350RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5351 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005352 const cricket::ContentGroup* bundle_group = nullptr;
5353 if (configuration_.bundle_policy ==
5354 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005355 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005356 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005357 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5358 "max-bundle configured but session description "
5359 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005360 }
5361 }
Steve Antondcc3c022017-12-22 16:02:54 -08005362 return std::move(bundle_group);
5363}
5364
5365RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005366 // Creating the media channels. Transports should already have been created
5367 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005368 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005369 if (voice && !voice->rejected &&
5370 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005371 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005372 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005373 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5374 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005375 }
5376 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5377 }
5378
Steve Antondcc3c022017-12-22 16:02:54 -08005379 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005380 if (video && !video->rejected &&
5381 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005382 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005383 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005384 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5385 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005386 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005387 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005388 }
5389
Steve Antondcc3c022017-12-22 16:02:54 -08005390 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005391 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5392 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005393 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005394 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5395 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005396 }
5397 }
5398
Steve Anton8a006912017-12-04 15:25:56 -08005399 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005400}
5401
Steve Anton4171afb2017-11-20 10:20:22 -08005402// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005403cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005404 const std::string& mid) {
5405 RtpTransportInternal* rtp_transport =
5406 transport_controller_->GetRtpTransport(mid);
5407 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005408 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005409 call_.get(), configuration_.media_config, rtp_transport,
5410 signaling_thread(), mid, SrtpRequired(),
5411 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005412 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005413 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005414 }
Steve Anton75737c02017-11-06 10:37:17 -08005415 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5416 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005417 voice_channel->SignalSentPacket.connect(this,
5418 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005419 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005420
Steve Antoneda6ccd2017-12-04 10:21:55 -08005421 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005422}
5423
Steve Anton4171afb2017-11-20 10:20:22 -08005424// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005425cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005426 const std::string& mid) {
5427 RtpTransportInternal* rtp_transport =
5428 transport_controller_->GetRtpTransport(mid);
5429 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005430 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005431 call_.get(), configuration_.media_config, rtp_transport,
5432 signaling_thread(), mid, SrtpRequired(),
5433 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005434 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005435 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005436 }
Steve Anton75737c02017-11-06 10:37:17 -08005437 video_channel->SignalDtlsSrtpSetupFailure.connect(
5438 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005439 video_channel->SignalSentPacket.connect(this,
5440 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005441 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005442
Steve Antoneda6ccd2017-12-04 10:21:55 -08005443 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005444}
5445
Zhi Huange830e682018-03-30 10:48:35 -07005446bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005447 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5448 if (sctp) {
5449 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005450 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005451 << "Trying to create SCTP transport, but didn't compile with "
5452 "SCTP support (HAVE_SCTP)";
5453 return false;
5454 }
5455 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005456 RTC_FROM_HERE,
5457 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005458 return false;
5459 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005460 for (const auto& channel : sctp_data_channels_) {
5461 channel->OnTransportChannelCreated();
5462 }
Steve Anton75737c02017-11-06 10:37:17 -08005463 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005464 RtpTransportInternal* rtp_transport =
5465 transport_controller_->GetRtpTransport(mid);
5466 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005467 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005468 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5469 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005470 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005471 return false;
5472 }
Steve Anton75737c02017-11-06 10:37:17 -08005473 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5474 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5475 rtp_data_channel_->SignalSentPacket.connect(
5476 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005477 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005478 }
5479
Steve Anton75737c02017-11-06 10:37:17 -08005480 return true;
5481}
5482
5483Call::Stats PeerConnection::GetCallStats() {
5484 if (!worker_thread()->IsCurrent()) {
5485 return worker_thread()->Invoke<Call::Stats>(
5486 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5487 }
5488 if (call_) {
5489 return call_->GetStats();
5490 } else {
5491 return Call::Stats();
5492 }
5493}
5494
Zhi Huange830e682018-03-30 10:48:35 -07005495bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005496 RTC_DCHECK(network_thread()->IsCurrent());
5497 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005498 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005499 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005500 RTC_DCHECK(dtls_transport);
5501 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005502 RTC_DCHECK(sctp_transport_);
5503 sctp_invoker_.reset(new rtc::AsyncInvoker());
5504 sctp_transport_->SignalReadyToSendData.connect(
5505 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5506 sctp_transport_->SignalDataReceived.connect(
5507 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005508 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5509 // another thread. Would be nice if there was a helper class similar to
5510 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5511 // code.
5512 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5513 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5514 sctp_transport_->SignalClosingProcedureComplete.connect(
5515 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005516 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005517 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005518 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005519}
5520
5521void PeerConnection::DestroySctpTransport_n() {
5522 RTC_DCHECK(network_thread()->IsCurrent());
5523 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005524 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005525 sctp_invoker_.reset(nullptr);
5526 sctp_ready_to_send_data_ = false;
5527}
5528
5529void PeerConnection::OnSctpTransportReadyToSendData_n() {
5530 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5531 RTC_DCHECK(network_thread()->IsCurrent());
5532 // Note: Cannot use rtc::Bind here because it will grab a reference to
5533 // PeerConnection and potentially cause PeerConnection to live longer than
5534 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5535 // be destroyed before PeerConnection is destroyed, and at that point all
5536 // pending tasks will be cleared.
5537 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5538 OnSctpTransportReadyToSendData_s(true);
5539 });
5540}
5541
5542void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5543 RTC_DCHECK(signaling_thread()->IsCurrent());
5544 sctp_ready_to_send_data_ = ready;
5545 SignalSctpReadyToSendData(ready);
5546}
5547
5548void PeerConnection::OnSctpTransportDataReceived_n(
5549 const cricket::ReceiveDataParams& params,
5550 const rtc::CopyOnWriteBuffer& payload) {
5551 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5552 RTC_DCHECK(network_thread()->IsCurrent());
5553 // Note: Cannot use rtc::Bind here because it will grab a reference to
5554 // PeerConnection and potentially cause PeerConnection to live longer than
5555 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5556 // be destroyed before PeerConnection is destroyed, and at that point all
5557 // pending tasks will be cleared.
5558 sctp_invoker_->AsyncInvoke<void>(
5559 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5560 OnSctpTransportDataReceived_s(params, payload);
5561 });
5562}
5563
5564void PeerConnection::OnSctpTransportDataReceived_s(
5565 const cricket::ReceiveDataParams& params,
5566 const rtc::CopyOnWriteBuffer& payload) {
5567 RTC_DCHECK(signaling_thread()->IsCurrent());
5568 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5569 // Received OPEN message; parse and signal that a new data channel should
5570 // be created.
5571 std::string label;
5572 InternalDataChannelInit config;
5573 config.id = params.ssrc;
5574 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005575 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5576 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005577 return;
5578 }
5579 config.open_handshake_role = InternalDataChannelInit::kAcker;
5580 OnDataChannelOpenMessage(label, config);
5581 } else {
5582 // Otherwise just forward the signal.
5583 SignalSctpDataReceived(params, payload);
5584 }
5585}
5586
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005587void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005588 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5589 RTC_DCHECK(network_thread()->IsCurrent());
5590 sctp_invoker_->AsyncInvoke<void>(
5591 RTC_FROM_HERE, signaling_thread(),
5592 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005593 &SignalSctpClosingProcedureStartedRemotely, sid));
5594}
5595
5596void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5597 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5598 RTC_DCHECK(network_thread()->IsCurrent());
5599 sctp_invoker_->AsyncInvoke<void>(
5600 RTC_FROM_HERE, signaling_thread(),
5601 rtc::Bind(&sigslot::signal1<int>::operator(),
5602 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005603}
5604
5605// Returns false if bundle is enabled and rtcp_mux is disabled.
5606bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5607 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5608 if (!bundle_enabled)
5609 return true;
5610
5611 const cricket::ContentGroup* bundle_group =
5612 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5613 RTC_DCHECK(bundle_group != NULL);
5614
5615 const cricket::ContentInfos& contents = desc->contents();
5616 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5617 citer != contents.end(); ++citer) {
5618 const cricket::ContentInfo* content = (&*citer);
5619 RTC_DCHECK(content != NULL);
5620 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005621 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005622 if (!HasRtcpMuxEnabled(content))
5623 return false;
5624 }
5625 }
5626 // RTCP-MUX is enabled in all the contents.
5627 return true;
5628}
5629
5630bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005631 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005632}
5633
Steve Anton8a006912017-12-04 15:25:56 -08005634RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005635 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005636 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005637 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005638 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005639 }
5640
5641 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005642 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005643 }
5644
Steve Anton3828c062017-12-06 10:34:51 -08005645 SdpType type = sdesc->GetType();
5646 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5647 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005648 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005649 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005650 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005651 }
5652
5653 // Verify crypto settings.
5654 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005655 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5656 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005657 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005658 if (!crypto_error.ok()) {
5659 return crypto_error;
5660 }
Steve Anton75737c02017-11-06 10:37:17 -08005661 }
5662
5663 // Verify ice-ufrag and ice-pwd.
5664 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005665 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5666 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005667 }
5668
5669 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5671 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005672 }
5673
5674 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5675 // m-lines that do not rtcp-mux enabled.
5676
5677 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005678 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005679 // With an answer we want to compare the new answer session description with
5680 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005681 const cricket::SessionDescription* offer_desc =
5682 (source == cricket::CS_LOCAL) ? remote_description()->description()
5683 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005684 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5685 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5686 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005687 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5688 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005689 }
5690 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005691 // The re-offers should respect the order of m= sections in current
5692 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005693 // With a re-offer, either the current local or current remote descriptions
5694 // could be the most up to date, so we would like to check against both of
5695 // them if they exist. It could be the case that one of them has a 0 port
5696 // for a media section, but the other does not. This is important to check
5697 // against in the case that we are recycling an m= section.
5698 const cricket::SessionDescription* current_desc = nullptr;
5699 const cricket::SessionDescription* secondary_current_desc = nullptr;
5700 if (local_description()) {
5701 current_desc = local_description()->description();
5702 if (remote_description()) {
5703 secondary_current_desc = remote_description()->description();
5704 }
5705 } else if (remote_description()) {
5706 current_desc = remote_description()->description();
5707 }
Steve Anton75737c02017-11-06 10:37:17 -08005708 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005709 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5710 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005711 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5712 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005713 }
5714 }
5715
Steve Antonba42e992018-04-09 14:10:01 -07005716 if (IsUnifiedPlan()) {
5717 // Ensure that each audio and video media section has at most one
5718 // "StreamParams". This will return an error if receiving a session
5719 // description from a "Plan B" endpoint which adds multiple tracks of the
5720 // same type. With Unified Plan, there can only be at most one track per
5721 // media section.
5722 for (const ContentInfo& content : sdesc->description()->contents()) {
5723 const MediaContentDescription& desc = *content.description;
5724 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5725 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5726 desc.streams().size() > 1u) {
5727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5728 "Media section has more than one track specified "
5729 "with a=ssrc lines which is not supported with "
5730 "Unified Plan.");
5731 }
5732 }
5733 }
5734
Steve Anton8a006912017-12-04 15:25:56 -08005735 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005736}
5737
Steve Anton3828c062017-12-06 10:34:51 -08005738bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005739 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005740 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005741 return (state == PeerConnectionInterface::kStable) ||
5742 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005743 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005744 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005745 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5746 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5747 }
5748}
5749
Steve Anton3828c062017-12-06 10:34:51 -08005750bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005751 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005752 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005753 return (state == PeerConnectionInterface::kStable) ||
5754 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005755 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005756 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005757 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5758 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5759 }
5760}
5761
Steve Antonf8470812017-12-04 10:46:21 -08005762const char* PeerConnection::SessionErrorToString(SessionError error) const {
5763 switch (error) {
5764 case SessionError::kNone:
5765 return "ERROR_NONE";
5766 case SessionError::kContent:
5767 return "ERROR_CONTENT";
5768 case SessionError::kTransport:
5769 return "ERROR_TRANSPORT";
5770 }
5771 RTC_NOTREACHED();
5772 return "";
5773}
5774
Steve Anton75737c02017-11-06 10:37:17 -08005775std::string PeerConnection::GetSessionErrorMsg() {
5776 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005777 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5778 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005779 return desc.str();
5780}
5781
Steve Anton8e20f172018-03-06 10:55:04 -08005782void PeerConnection::ReportSdpFormatReceived(
5783 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005784 int num_audio_mlines = 0;
5785 int num_video_mlines = 0;
5786 int num_audio_tracks = 0;
5787 int num_video_tracks = 0;
5788 for (const ContentInfo& content : remote_offer.description()->contents()) {
5789 cricket::MediaType media_type = content.media_description()->type();
5790 int num_tracks = std::max(
5791 1, static_cast<int>(content.media_description()->streams().size()));
5792 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5793 num_audio_mlines += 1;
5794 num_audio_tracks += num_tracks;
5795 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5796 num_video_mlines += 1;
5797 num_video_tracks += num_tracks;
5798 }
5799 }
5800 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5801 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5802 format = kSdpFormatReceivedComplexUnifiedPlan;
5803 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5804 format = kSdpFormatReceivedComplexPlanB;
5805 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5806 format = kSdpFormatReceivedSimple;
5807 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005808 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5809 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005810}
5811
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005812void PeerConnection::NoteUsageEvent(UsageEvent event) {
5813 RTC_DCHECK_RUN_ON(signaling_thread());
5814 usage_event_accumulator_ |= static_cast<int>(event);
5815}
5816
5817void PeerConnection::ReportUsagePattern() const {
5818 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005819 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5820 usage_event_accumulator_,
5821 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005822 const int bad_bits =
5823 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5824 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5825 const int good_bits =
5826 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5827 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5828 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5829 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5830 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005831 // If called after close(), we can't report, because observer may have
5832 // been deallocated, and therefore pointer is null. Write to log instead.
5833 if (observer_) {
5834 Observer()->OnInterestingUsage(usage_event_accumulator_);
5835 } else {
5836 RTC_LOG(LS_INFO) << "Interesting usage signature "
5837 << usage_event_accumulator_
5838 << " observed after observer shutdown";
5839 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005840 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005841}
5842
Steve Anton0ffaaa22018-02-23 10:31:30 -08005843void PeerConnection::ReportNegotiatedSdpSemantics(
5844 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005845 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005846 switch (answer.description()->msid_signaling()) {
5847 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005848 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005849 break;
5850 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005851 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005852 break;
5853 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005854 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005855 break;
5856 case cricket::kMsidSignalingMediaSection |
5857 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005858 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005859 break;
5860 default:
5861 RTC_NOTREACHED();
5862 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005863 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5864 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005865}
5866
Steve Anton75737c02017-11-06 10:37:17 -08005867// We need to check the local/remote description for the Transport instead of
5868// the session, because a new Transport added during renegotiation may have
5869// them unset while the session has them set from the previous negotiation.
5870// Not doing so may trigger the auto generation of transport description and
5871// mess up DTLS identity information, ICE credential, etc.
5872bool PeerConnection::ReadyToUseRemoteCandidate(
5873 const IceCandidateInterface* candidate,
5874 const SessionDescriptionInterface* remote_desc,
5875 bool* valid) {
5876 *valid = true;
5877
5878 const SessionDescriptionInterface* current_remote_desc =
5879 remote_desc ? remote_desc : remote_description();
5880
5881 if (!current_remote_desc) {
5882 return false;
5883 }
5884
5885 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5886 size_t remote_content_size =
5887 current_remote_desc->description()->contents().size();
5888 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005889 RTC_LOG(LS_ERROR)
5890 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5891 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005892
5893 *valid = false;
5894 return false;
5895 }
5896
5897 cricket::ContentInfo content =
5898 current_remote_desc->description()->contents()[mediacontent_index];
5899
5900 const std::string transport_name = GetTransportName(content.name);
5901 if (transport_name.empty()) {
5902 return false;
5903 }
Zhi Huange830e682018-03-30 10:48:35 -07005904 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005905}
5906
5907bool PeerConnection::SrtpRequired() const {
5908 return dtls_enabled_ ||
5909 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5910}
5911
5912void PeerConnection::OnTransportControllerGatheringState(
5913 cricket::IceGatheringState state) {
5914 RTC_DCHECK(signaling_thread()->IsCurrent());
5915 if (state == cricket::kIceGatheringGathering) {
5916 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5917 } else if (state == cricket::kIceGatheringComplete) {
5918 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5919 }
5920}
5921
5922void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005923 std::map<std::string, std::set<cricket::MediaType>>
5924 media_types_by_transport_name;
5925 for (auto transceiver : transceivers_) {
5926 if (transceiver->internal()->channel()) {
5927 const std::string& transport_name =
5928 transceiver->internal()->channel()->transport_name();
5929 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005930 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005931 }
Steve Anton75737c02017-11-06 10:37:17 -08005932 }
5933 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005934 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5935 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005936 }
Zhi Huange830e682018-03-30 10:48:35 -07005937
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005938 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005939 if (transport_name) {
5940 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08005941 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005942 }
Zhi Huange830e682018-03-30 10:48:35 -07005943
Steve Antonc7b964c2018-02-01 14:39:45 -08005944 for (const auto& entry : media_types_by_transport_name) {
5945 const std::string& transport_name = entry.first;
5946 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005947 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005948 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005949 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005950 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005951 }
5952 }
5953}
5954// Walk through the ConnectionInfos to gather best connection usage
5955// for IPv4 and IPv6.
5956void PeerConnection::ReportBestConnectionState(
5957 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005958 for (const cricket::TransportChannelStats& channel_stats :
5959 stats.channel_stats) {
5960 for (const cricket::ConnectionInfo& connection_info :
5961 channel_stats.connection_infos) {
5962 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005963 continue;
5964 }
5965
Steve Antonc7b964c2018-02-01 14:39:45 -08005966 const cricket::Candidate& local = connection_info.local_candidate;
5967 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005968
5969 // Increment the counter for IceCandidatePairType.
5970 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5971 (local.type() == RELAY_PORT_TYPE &&
5972 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005973 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
5974 GetIceCandidatePairCounter(local, remote),
5975 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08005976 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005977 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
5978 GetIceCandidatePairCounter(local, remote),
5979 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08005980 } else {
5981 RTC_CHECK(0);
5982 }
Steve Anton75737c02017-11-06 10:37:17 -08005983
5984 // Increment the counter for IP type.
5985 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005986 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
5987 kBestConnections_IPv4,
5988 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08005989 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005990 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
5991 kBestConnections_IPv6,
5992 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08005993 } else {
5994 RTC_CHECK(0);
5995 }
5996
5997 return;
5998 }
5999 }
6000}
6001
6002void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006003 const cricket::TransportStats& stats,
6004 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006005 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6006 return;
6007 }
6008
6009 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6010 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6011 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6012 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6013 return;
6014 }
6015
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006016 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6017 for (cricket::MediaType media_type : media_types) {
6018 switch (media_type) {
6019 case cricket::MEDIA_TYPE_AUDIO:
6020 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6021 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6022 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6023 break;
6024 case cricket::MEDIA_TYPE_VIDEO:
6025 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6026 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6027 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6028 break;
6029 case cricket::MEDIA_TYPE_DATA:
6030 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6031 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6032 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6033 break;
6034 default:
6035 RTC_NOTREACHED();
6036 continue;
6037 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006038 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006039 }
6040
6041 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6042 for (cricket::MediaType media_type : media_types) {
6043 switch (media_type) {
6044 case cricket::MEDIA_TYPE_AUDIO:
6045 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6046 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6047 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6048 break;
6049 case cricket::MEDIA_TYPE_VIDEO:
6050 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6051 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6052 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6053 break;
6054 case cricket::MEDIA_TYPE_DATA:
6055 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6056 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6057 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6058 break;
6059 default:
6060 RTC_NOTREACHED();
6061 continue;
6062 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006063 }
Steve Anton75737c02017-11-06 10:37:17 -08006064 }
6065}
6066
6067void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6068 RTC_DCHECK(worker_thread()->IsCurrent());
6069 RTC_DCHECK(call_);
6070 call_->OnSentPacket(sent_packet);
6071}
6072
6073const std::string PeerConnection::GetTransportName(
6074 const std::string& content_name) {
6075 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006076 if (channel) {
6077 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006078 }
Steve Anton6fec8802017-12-04 10:37:29 -08006079 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006080 RTC_DCHECK(sctp_mid_);
6081 if (content_name == *sctp_mid_) {
6082 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006083 }
6084 }
6085 // Return an empty string if failed to retrieve the transport name.
6086 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006087}
6088
Steve Anton6fec8802017-12-04 10:37:29 -08006089void PeerConnection::DestroyTransceiverChannel(
6090 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6091 transceiver) {
6092 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006093
Steve Anton6fec8802017-12-04 10:37:29 -08006094 cricket::BaseChannel* channel = transceiver->internal()->channel();
6095 if (channel) {
6096 transceiver->internal()->SetChannel(nullptr);
6097 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006098 }
6099}
6100
6101void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006102 if (rtp_data_channel_) {
6103 OnDataChannelDestroyed();
6104 DestroyBaseChannel(rtp_data_channel_);
6105 rtp_data_channel_ = nullptr;
6106 }
6107
6108 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6109 // grab a reference to this PeerConnection. If this is called from the
6110 // PeerConnection destructor, the RefCountedObject vtable will have already
6111 // been destroyed (since it is a subclass of PeerConnection) and using
6112 // rtc::Bind will cause "Pure virtual function called" error to appear.
6113
6114 if (sctp_transport_) {
6115 OnDataChannelDestroyed();
6116 network_thread()->Invoke<void>(RTC_FROM_HERE,
6117 [this] { DestroySctpTransport_n(); });
6118 }
6119}
6120
6121void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6122 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006123 switch (channel->media_type()) {
6124 case cricket::MEDIA_TYPE_AUDIO:
6125 channel_manager()->DestroyVoiceChannel(
6126 static_cast<cricket::VoiceChannel*>(channel));
6127 break;
6128 case cricket::MEDIA_TYPE_VIDEO:
6129 channel_manager()->DestroyVideoChannel(
6130 static_cast<cricket::VideoChannel*>(channel));
6131 break;
6132 case cricket::MEDIA_TYPE_DATA:
6133 channel_manager()->DestroyRtpDataChannel(
6134 static_cast<cricket::RtpDataChannel*>(channel));
6135 break;
6136 default:
6137 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6138 break;
6139 }
Zhi Huange830e682018-03-30 10:48:35 -07006140}
Steve Anton6fec8802017-12-04 10:37:29 -08006141
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006142bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006143 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006144 RtpTransportInternal* rtp_transport,
6145 cricket::DtlsTransportInternal* dtls_transport) {
6146 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006147 auto base_channel = GetChannel(mid);
6148 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006149 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006150 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006151 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006152 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006153 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006154 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006155}
6156
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006157PeerConnectionObserver* PeerConnection::Observer() const {
6158 // In earlier production code, the pointer was not cleared on close,
6159 // which might have led to undefined behavior if the observer was not
6160 // deallocated, or strange crashes if it was.
6161 // We use CHECK in order to catch such behavior if it exists.
6162 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6163 RTC_CHECK(observer_);
6164 return observer_;
6165}
6166
Harald Alvestrand89061872018-01-02 14:08:34 +01006167void PeerConnection::ClearStatsCache() {
6168 if (stats_collector_) {
6169 stats_collector_->ClearCachedStatsReport();
6170 }
6171}
6172
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006173void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonbb192762018-08-31 11:57:02 -07006174 async_invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(),
6175 [this] { ReportUsagePattern(); });
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006176}
6177
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006178} // namespace webrtc