blob: 4b6eb1734ec8010ca47eb7fa350d3b855b3dc3f4 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
25#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080026#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020027#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080031#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080037#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080040#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080041#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010048#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070054#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
Steve Anton75737c02017-11-06 10:37:17 -080056using cricket::ContentInfo;
57using cricket::ContentInfos;
58using cricket::MediaContentDescription;
59using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080060using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::TransportInfo;
62
63using cricket::LOCAL_PORT_TYPE;
64using cricket::STUN_PORT_TYPE;
65using cricket::RELAY_PORT_TYPE;
66using cricket::PRFLX_PORT_TYPE;
67
Steve Antonba818672017-11-06 10:21:57 -080068namespace webrtc {
69
Steve Anton75737c02017-11-06 10:37:17 -080070// Error messages
71const char kBundleWithoutRtcpMux[] =
72 "rtcp-mux must be enabled when BUNDLE "
73 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080074const char kInvalidCandidates[] = "Description contains invalid candidates.";
75const char kInvalidSdp[] = "Invalid session description.";
76const char kMlineMismatchInAnswer[] =
77 "The order of m-lines in answer doesn't match order in offer. Rejecting "
78 "answer.";
79const char kMlineMismatchInSubsequentOffer[] =
80 "The order of m-lines in subsequent offer doesn't match order from "
81 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080082const char kSdpWithoutDtlsFingerprint[] =
83 "Called with SDP without DTLS fingerprint.";
84const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
85const char kSdpWithoutIceUfragPwd[] =
86 "Called with SDP without ice-ufrag and ice-pwd.";
87const char kSessionError[] = "Session error code: ";
88const char kSessionErrorDesc[] = "Session error description: ";
89const char kDtlsSrtpSetupFailureRtp[] =
90 "Couldn't set up DTLS-SRTP on RTP channel.";
91const char kDtlsSrtpSetupFailureRtcp[] =
92 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
Harald Alvestrand19793842018-06-25 12:03:50 +0200103static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
104
deadbeefab9b2d12015-10-14 11:33:11 -0700105// Check if we can send |new_stream| on a PeerConnection.
106bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
107 webrtc::MediaStreamInterface* new_stream) {
108 if (!new_stream || !current_streams) {
109 return false;
110 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700111 if (current_streams->find(new_stream->id()) != nullptr) {
112 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100113 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700114 return false;
115 }
116 return true;
117}
118
deadbeef5e97fb52015-10-15 12:49:08 -0700119// If the direction is "recvonly" or "inactive", treat the description
120// as containing no streams.
121// See: https://code.google.com/p/webrtc/issues/detail?id=5054
122std::vector<cricket::StreamParams> GetActiveStreams(
123 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800124 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700125 ? desc->streams()
126 : std::vector<cricket::StreamParams>();
127}
128
deadbeefab9b2d12015-10-14 11:33:11 -0700129bool IsValidOfferToReceiveMedia(int value) {
130 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
131 return (value >= Options::kUndefined) &&
132 (value <= Options::kMaxOfferToReceiveMedia);
133}
134
zhihuang1c378ed2017-08-17 14:10:50 -0700135// Add options to |[audio/video]_media_description_options| from |senders|.
136void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700137 const std::vector<rtc::scoped_refptr<
138 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700139 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200140 cricket::MediaDescriptionOptions* video_media_description_options,
141 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700142 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700143 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
144 if (audio_media_description_options) {
145 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700146 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700147 }
148 } else {
149 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
150 if (video_media_description_options) {
151 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200152 sender->id(), sender->internal()->stream_ids(),
153 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700154 }
155 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700156 }
zhihuang1c378ed2017-08-17 14:10:50 -0700157}
olka3c747662017-08-17 06:50:32 -0700158
zhihuang1c378ed2017-08-17 14:10:50 -0700159// Add options to |session_options| from |rtp_data_channels|.
160void AddRtpDataChannelOptions(
161 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
162 rtp_data_channels,
163 cricket::MediaDescriptionOptions* data_media_description_options) {
164 if (!data_media_description_options) {
165 return;
166 }
deadbeefab9b2d12015-10-14 11:33:11 -0700167 // Check for data channels.
168 for (const auto& kv : rtp_data_channels) {
169 const DataChannel* channel = kv.second;
170 if (channel->state() == DataChannel::kConnecting ||
171 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700172 // Legacy RTP data channels are signaled with the track/stream ID set to
173 // the data channel's label.
174 data_media_description_options->AddRtpDataChannel(channel->label(),
175 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700176 }
177 }
178}
179
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700180uint32_t ConvertIceTransportTypeToCandidateFilter(
181 PeerConnectionInterface::IceTransportsType type) {
182 switch (type) {
183 case PeerConnectionInterface::kNone:
184 return cricket::CF_NONE;
185 case PeerConnectionInterface::kRelay:
186 return cricket::CF_RELAY;
187 case PeerConnectionInterface::kNoHost:
188 return (cricket::CF_ALL & ~cricket::CF_HOST);
189 case PeerConnectionInterface::kAll:
190 return cricket::CF_ALL;
191 default:
nissec80e7412017-01-11 05:56:46 -0800192 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700193 }
194 return cricket::CF_NONE;
195}
196
deadbeef293e9262017-01-11 12:28:30 -0800197// Helper to set an error and return from a method.
198bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
199 if (error) {
200 error->set_type(type);
201 }
202 return type == webrtc::RTCErrorType::NONE;
203}
204
Steve Anton038834f2017-07-14 15:59:59 -0700205bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700206 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700207 if (error_out) {
208 *error_out = std::move(error);
209 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700210 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700211}
212
Steve Antonba818672017-11-06 10:21:57 -0800213std::string GetSignalingStateString(
214 PeerConnectionInterface::SignalingState state) {
215 switch (state) {
216 case PeerConnectionInterface::kStable:
217 return "kStable";
218 case PeerConnectionInterface::kHaveLocalOffer:
219 return "kHaveLocalOffer";
220 case PeerConnectionInterface::kHaveLocalPrAnswer:
221 return "kHavePrAnswer";
222 case PeerConnectionInterface::kHaveRemoteOffer:
223 return "kHaveRemoteOffer";
224 case PeerConnectionInterface::kHaveRemotePrAnswer:
225 return "kHaveRemotePrAnswer";
226 case PeerConnectionInterface::kClosed:
227 return "kClosed";
228 }
229 RTC_NOTREACHED();
230 return "";
231}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700232
Steve Anton75737c02017-11-06 10:37:17 -0800233IceCandidatePairType GetIceCandidatePairCounter(
234 const cricket::Candidate& local,
235 const cricket::Candidate& remote) {
236 const auto& l = local.type();
237 const auto& r = remote.type();
238 const auto& host = LOCAL_PORT_TYPE;
239 const auto& srflx = STUN_PORT_TYPE;
240 const auto& relay = RELAY_PORT_TYPE;
241 const auto& prflx = PRFLX_PORT_TYPE;
242 if (l == host && r == host) {
243 bool local_private = IPIsPrivate(local.address().ipaddr());
244 bool remote_private = IPIsPrivate(remote.address().ipaddr());
245 if (local_private) {
246 if (remote_private) {
247 return kIceCandidatePairHostPrivateHostPrivate;
248 } else {
249 return kIceCandidatePairHostPrivateHostPublic;
250 }
251 } else {
252 if (remote_private) {
253 return kIceCandidatePairHostPublicHostPrivate;
254 } else {
255 return kIceCandidatePairHostPublicHostPublic;
256 }
257 }
258 }
259 if (l == host && r == srflx)
260 return kIceCandidatePairHostSrflx;
261 if (l == host && r == relay)
262 return kIceCandidatePairHostRelay;
263 if (l == host && r == prflx)
264 return kIceCandidatePairHostPrflx;
265 if (l == srflx && r == host)
266 return kIceCandidatePairSrflxHost;
267 if (l == srflx && r == srflx)
268 return kIceCandidatePairSrflxSrflx;
269 if (l == srflx && r == relay)
270 return kIceCandidatePairSrflxRelay;
271 if (l == srflx && r == prflx)
272 return kIceCandidatePairSrflxPrflx;
273 if (l == relay && r == host)
274 return kIceCandidatePairRelayHost;
275 if (l == relay && r == srflx)
276 return kIceCandidatePairRelaySrflx;
277 if (l == relay && r == relay)
278 return kIceCandidatePairRelayRelay;
279 if (l == relay && r == prflx)
280 return kIceCandidatePairRelayPrflx;
281 if (l == prflx && r == host)
282 return kIceCandidatePairPrflxHost;
283 if (l == prflx && r == srflx)
284 return kIceCandidatePairPrflxSrflx;
285 if (l == prflx && r == relay)
286 return kIceCandidatePairPrflxRelay;
287 return kIceCandidatePairMax;
288}
289
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800290// Logic to decide if an m= section can be recycled. This means that the new
291// m= section is not rejected, but the old local or remote m= section is
292// rejected. |old_content_one| and |old_content_two| refer to the m= section
293// of the old remote and old local descriptions in no particular order.
294// We need to check both the old local and remote because either
295// could be the most current from the latest negotation.
296bool IsMediaSectionBeingRecycled(SdpType type,
297 const ContentInfo& content,
298 const ContentInfo* old_content_one,
299 const ContentInfo* old_content_two) {
300 return type == SdpType::kOffer && !content.rejected &&
301 ((old_content_one && old_content_one->rejected) ||
302 (old_content_two && old_content_two->rejected));
303}
304
Steve Anton75737c02017-11-06 10:37:17 -0800305// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800306// |current_desc|. The number of m= sections in |new_desc| should be no
307// less than |current_desc|. In the case of checking an answer's
308// |new_desc|, the |current_desc| is the last offer that was set as the
309// local or remote. In the case of checking an offer's |new_desc| we
310// check against the local and remote descriptions stored from the last
311// negotiation, because either of these could be the most up to date for
312// possible rejected m sections. These are the |current_desc| and
313// |secondary_current_desc|.
314bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
315 const SessionDescription* secondary_current_desc,
316 const SessionDescription& new_desc,
317 const SdpType type) {
318 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800319 return false;
320 }
321
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800322 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
323 const cricket::ContentInfo* secondary_content_info = nullptr;
324 if (secondary_current_desc &&
325 i < secondary_current_desc->contents().size()) {
326 secondary_content_info = &secondary_current_desc->contents()[i];
327 }
328 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
329 &current_desc.contents()[i],
330 secondary_content_info)) {
331 // For new offer descriptions, if the media section can be recycled, it's
332 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800333 continue;
334 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800335 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800336 return false;
337 }
338 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800339 new_desc.contents()[i].media_description();
340 const MediaContentDescription* current_desc_mdesc =
341 current_desc.contents()[i].media_description();
342 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800343 return false;
344 }
345 }
346 return true;
347}
348
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800349bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
350 const SessionDescription& desc2) {
351 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800352}
353
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700354void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
355 cricket::MediaType media_type) {
356 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
357 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100358 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
359 KeyExchangeProtocolMedia>
360 proto_media_counter_map = {
361 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
362 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
363 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
364 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
365 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
366 kEnumCounterKeyProtocolMediaTypeDtlsData},
367 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
368 kEnumCounterKeyProtocolMediaTypeSdesAudio},
369 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
370 kEnumCounterKeyProtocolMediaTypeSdesVideo},
371 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
372 kEnumCounterKeyProtocolMediaTypeSdesData}};
373
374 auto it = proto_media_counter_map.find({protocol_type, media_type});
375 if (it != proto_media_counter_map.end()) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700376 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
377 it->second, kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100378 }
379}
380
Harald Alvestrand76829d72018-07-18 23:24:36 +0200381void NoteAddIceCandidateResult(int result) {
382 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
383 kAddIceCandidateMax);
384}
385
Steve Anton75737c02017-11-06 10:37:17 -0800386// Checks that each non-rejected content has SDES crypto keys or a DTLS
387// fingerprint, unless it's in a BUNDLE group, in which case only the
388// BUNDLE-tag section (first media section/description in the BUNDLE group)
389// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
390// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
391// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700392RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800393 const cricket::ContentGroup* bundle =
394 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800395 for (const cricket::ContentInfo& content_info : desc->contents()) {
396 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 continue;
398 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100399 // Note what media is used with each crypto protocol, for all sections.
400 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
401 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700402 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800403 const std::string& mid = content_info.name;
404 if (bundle && bundle->HasContentName(mid) &&
405 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800406 // This isn't the first media section in the BUNDLE group, so it's not
407 // required to have crypto attributes, since only the crypto attributes
408 // from the first section actually get used.
409 continue;
410 }
411
412 // If the content isn't rejected or bundled into another m= section, crypto
413 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800414 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800415 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800416 if (!media || !tinfo) {
417 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800418 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800419 }
420 if (dtls_enabled) {
421 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100422 RTC_LOG(LS_WARNING)
423 << "Session description must have DTLS fingerprint if "
424 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800425 return RTCError(RTCErrorType::INVALID_PARAMETER,
426 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800427 }
428 } else {
429 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100430 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800431 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800432 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800433 }
434 }
435 }
Steve Anton8a006912017-12-04 15:25:56 -0800436 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800437}
438
439// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
440// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
441// media section/description in the BUNDLE group) needs a ufrag and pwd.
442bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
443 const cricket::ContentGroup* bundle =
444 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800445 for (const cricket::ContentInfo& content_info : desc->contents()) {
446 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800447 continue;
448 }
Steve Anton8a006912017-12-04 15:25:56 -0800449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have ufrag/password, since only the ufrag/password from
454 // the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section,
459 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800460 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800461 if (!tinfo) {
462 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800464 return false;
465 }
466 if (tinfo->description.ice_ufrag.empty() ||
467 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800469 return false;
470 }
471 }
472 return true;
473}
474
475bool GetTrackIdBySsrc(const SessionDescription* session_description,
476 uint32_t ssrc,
477 std::string* track_id) {
478 RTC_DCHECK(track_id != NULL);
479
Steve Antonb1c1de12017-12-21 15:14:30 -0800480 const cricket::AudioContentDescription* audio_desc =
481 cricket::GetFirstAudioContentDescription(session_description);
482 if (audio_desc) {
483 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800484 if (found) {
485 *track_id = found->id;
486 return true;
487 }
488 }
489
Steve Antonb1c1de12017-12-21 15:14:30 -0800490 const cricket::VideoContentDescription* video_desc =
491 cricket::GetFirstVideoContentDescription(session_description);
492 if (video_desc) {
493 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800494 if (found) {
495 *track_id = found->id;
496 return true;
497 }
498 }
499 return false;
500}
501
502// Get the SCTP port out of a SessionDescription.
503// Return -1 if not found.
504int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800505 const cricket::DataContentDescription* data_desc =
506 GetFirstDataContentDescription(session_description);
507 RTC_DCHECK(data_desc);
508 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800509 return -1;
510 }
Steve Anton75737c02017-11-06 10:37:17 -0800511 std::string value;
512 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
513 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800514 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800515 if (!codec.Matches(match_pattern)) {
516 continue;
517 }
518 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
519 return rtc::FromString<int>(value);
520 }
521 }
522 return -1;
523}
524
Steve Anton75737c02017-11-06 10:37:17 -0800525// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
526bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
527 const SessionDescriptionInterface* new_desc,
528 const std::string& content_name) {
529 if (!old_desc) {
530 return false;
531 }
532 const SessionDescription* new_sd = new_desc->description();
533 const SessionDescription* old_sd = old_desc->description();
534 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
535 if (!cinfo || cinfo->rejected) {
536 return false;
537 }
538 // If the content isn't rejected, check if ufrag and password has changed.
539 const cricket::TransportDescription* new_transport_desc =
540 new_sd->GetTransportDescriptionByName(content_name);
541 const cricket::TransportDescription* old_transport_desc =
542 old_sd->GetTransportDescriptionByName(content_name);
543 if (!new_transport_desc || !old_transport_desc) {
544 // No transport description exists. This is not an ICE restart.
545 return false;
546 }
547 if (cricket::IceCredentialsChanged(
548 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
549 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100550 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
551 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800552 return true;
553 }
554 return false;
555}
556
Steve Anton80dd7b52018-02-16 17:08:42 -0800557// Generates a string error message for SetLocalDescription/SetRemoteDescription
558// from an RTCError.
559std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
560 SdpType type,
561 const RTCError& error) {
562 std::ostringstream oss;
563 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
564 << " " << SdpTypeToString(type) << " sdp: " << error.message();
565 return oss.str();
566}
567
Seth Hampson5b4f0752018-04-02 16:31:36 -0700568std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
569 std::string output = "streams=[";
570 const char* separator = "";
571 for (const auto& stream_id : stream_ids) {
572 output.append(separator).append(stream_id);
573 separator = ", ";
574 }
575 output.append("]");
576 return output;
577}
578
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200579absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700580 int rtc_configuration_parameter) {
581 if (rtc_configuration_parameter ==
582 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200583 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700584 }
585 return rtc_configuration_parameter;
586}
587
Steve Anton75737c02017-11-06 10:37:17 -0800588} // namespace
589
Henrik Boström31638672017-11-23 17:48:32 +0100590// Upon completion, posts a task to execute the callback of the
591// SetSessionDescriptionObserver asynchronously on the same thread. At this
592// point, the state of the peer connection might no longer reflect the effects
593// of the SetRemoteDescription operation, as the peer connection could have been
594// modified during the post.
595// TODO(hbos): Remove this class once we remove the version of
596// PeerConnectionInterface::SetRemoteDescription() that takes a
597// SetSessionDescriptionObserver as an argument.
598class PeerConnection::SetRemoteDescriptionObserverAdapter
599 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
600 public:
601 SetRemoteDescriptionObserverAdapter(
602 rtc::scoped_refptr<PeerConnection> pc,
603 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
604 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
605
606 // SetRemoteDescriptionObserverInterface implementation.
607 void OnSetRemoteDescriptionComplete(RTCError error) override {
608 if (error.ok())
609 pc_->PostSetSessionDescriptionSuccess(wrapper_);
610 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100611 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100612 }
613
614 private:
615 rtc::scoped_refptr<PeerConnection> pc_;
616 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
617};
618
deadbeef293e9262017-01-11 12:28:30 -0800619bool PeerConnectionInterface::RTCConfiguration::operator==(
620 const PeerConnectionInterface::RTCConfiguration& o) const {
621 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700622 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800623 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000624 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700625 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800626 BundlePolicy bundle_policy;
627 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700628 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
629 int ice_candidate_pool_size;
630 bool disable_ipv6;
631 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700632 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100633 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700634 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200635 absl::optional<int> screencast_min_bitrate;
636 absl::optional<bool> combined_audio_video_bwe;
637 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800638 TcpCandidatePolicy tcp_candidate_policy;
639 CandidateNetworkPolicy candidate_network_policy;
640 int audio_jitter_buffer_max_packets;
641 bool audio_jitter_buffer_fast_accelerate;
642 int ice_connection_receiving_timeout;
643 int ice_backup_candidate_pair_ping_interval;
644 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800645 bool prioritize_most_likely_ice_candidate_pairs;
646 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800647 bool prune_turn_ports;
648 bool presume_writable_when_fully_relayed;
649 bool enable_ice_renomination;
650 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200651 absl::optional<int> ice_check_interval_strong_connectivity;
652 absl::optional<int> ice_check_interval_weak_connectivity;
653 absl::optional<int> ice_check_min_interval;
654 absl::optional<int> ice_unwritable_timeout;
655 absl::optional<int> ice_unwritable_min_checks;
656 absl::optional<int> stun_candidate_keepalive_interval;
657 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200658 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800659 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200660 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700661 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800662 };
663 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
664 "Did you add something to RTCConfiguration and forget to "
665 "update operator==?");
666 return type == o.type && servers == o.servers &&
667 bundle_policy == o.bundle_policy &&
668 rtcp_mux_policy == o.rtcp_mux_policy &&
669 tcp_candidate_policy == o.tcp_candidate_policy &&
670 candidate_network_policy == o.candidate_network_policy &&
671 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
672 audio_jitter_buffer_fast_accelerate ==
673 o.audio_jitter_buffer_fast_accelerate &&
674 ice_connection_receiving_timeout ==
675 o.ice_connection_receiving_timeout &&
676 ice_backup_candidate_pair_ping_interval ==
677 o.ice_backup_candidate_pair_ping_interval &&
678 continual_gathering_policy == o.continual_gathering_policy &&
679 certificates == o.certificates &&
680 prioritize_most_likely_ice_candidate_pairs ==
681 o.prioritize_most_likely_ice_candidate_pairs &&
682 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800683 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700684 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100685 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800686 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800687 screencast_min_bitrate == o.screencast_min_bitrate &&
688 combined_audio_video_bwe == o.combined_audio_video_bwe &&
689 enable_dtls_srtp == o.enable_dtls_srtp &&
690 ice_candidate_pool_size == o.ice_candidate_pool_size &&
691 prune_turn_ports == o.prune_turn_ports &&
692 presume_writable_when_fully_relayed ==
693 o.presume_writable_when_fully_relayed &&
694 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800695 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800696 ice_check_interval_strong_connectivity ==
697 o.ice_check_interval_strong_connectivity &&
698 ice_check_interval_weak_connectivity ==
699 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700701 ice_unwritable_timeout == o.ice_unwritable_timeout &&
702 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800703 stun_candidate_keepalive_interval ==
704 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200705 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800706 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800707 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700708 network_preference == o.network_preference &&
709 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800710}
711
712bool PeerConnectionInterface::RTCConfiguration::operator!=(
713 const PeerConnectionInterface::RTCConfiguration& o) const {
714 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800715}
716
zhihuang8f65cdf2016-05-06 18:40:30 -0700717// Generate a RTCP CNAME when a PeerConnection is created.
718std::string GenerateRtcpCname() {
719 std::string cname;
720 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100721 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800722 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700723 }
724 return cname;
725}
726
zhihuang1c378ed2017-08-17 14:10:50 -0700727bool ValidateOfferAnswerOptions(
728 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
729 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
730 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700731}
732
zhihuang1c378ed2017-08-17 14:10:50 -0700733// From |rtc_options|, fill parts of |session_options| shared by all generated
734// m= sections (in other words, nothing that involves a map/array).
735void ExtractSharedMediaSessionOptions(
736 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
737 cricket::MediaSessionOptions* session_options) {
738 session_options->vad_enabled = rtc_options.voice_activity_detection;
739 session_options->bundle_enabled = rtc_options.use_rtp_mux;
740}
zhihuanga77e6bb2017-08-14 18:17:48 -0700741
zhihuang38ede132017-06-15 12:52:32 -0700742PeerConnection::PeerConnection(PeerConnectionFactory* factory,
743 std::unique_ptr<RtcEventLog> event_log,
744 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000745 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700746 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700747 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700748 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700749 remote_streams_(StreamCollection::Create()),
750 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000751
752PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100753 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800754 RTC_DCHECK_RUN_ON(signaling_thread());
755
Steve Anton8af21862017-12-15 11:20:13 -0800756 // Need to stop transceivers before destroying the stats collector because
757 // AudioRtpSender has a reference to the StatsCollector it will update when
758 // stopping.
759 for (auto transceiver : transceivers_) {
760 transceiver->Stop();
761 }
Steve Anton4171afb2017-11-20 10:20:22 -0800762
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700763 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800764 if (stats_collector_) {
765 stats_collector_->WaitForPendingRequest();
766 stats_collector_ = nullptr;
767 }
Steve Anton75737c02017-11-06 10:37:17 -0800768
Steve Anton8af21862017-12-15 11:20:13 -0800769 // Don't destroy BaseChannels until after stats has been cleaned up so that
770 // the last stats request can still read from the channels.
771 DestroyAllChannels();
772
Mirko Bonadei675513b2017-11-09 11:09:25 +0100773 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800774
775 webrtc_session_desc_factory_.reset();
776 sctp_invoker_.reset();
777 sctp_factory_.reset();
778 transport_controller_.reset();
779
deadbeef91dd5672016-05-18 16:55:30 -0700780 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700781 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700782 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700783 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700784 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700785 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800786 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700787 event_log_.reset();
788 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000789}
790
Steve Anton8af21862017-12-15 11:20:13 -0800791void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800792 // Destroy video channels first since they may have a pointer to a voice
793 // channel.
794 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800795 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800796 DestroyTransceiverChannel(transceiver);
797 }
798 }
799 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800800 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800801 DestroyTransceiverChannel(transceiver);
802 }
803 }
804 DestroyDataChannel();
805}
806
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000808 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700809 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100810 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700811
812 RTCError config_error = ValidateConfiguration(configuration);
813 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100814 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700815 return false;
816 }
817
Benjamin Wrightcab58882018-05-02 15:12:47 -0700818 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100819 RTC_LOG(LS_ERROR)
820 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100821 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800822 return false;
823 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200824
Benjamin Wrightcab58882018-05-02 15:12:47 -0700825 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800826 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100827 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100828 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800829 return false;
830 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700831
Benjamin Wrightcab58882018-05-02 15:12:47 -0700832 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700833 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700834 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700835 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800836
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200837 cricket::ServerAddresses stun_servers;
838 std::vector<cricket::RelayServerConfig> turn_servers;
839
840 RTCErrorType parse_error =
841 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
842 if (parse_error != RTCErrorType::NONE) {
843 return false;
844 }
845
deadbeef91dd5672016-05-18 16:55:30 -0700846 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700847 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700848 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200849 RTC_FROM_HERE,
850 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
851 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000852 return false;
853 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200854 // If initialization was successful, note if STUN or TURN servers
855 // were supplied.
856 if (!stun_servers.empty()) {
857 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
858 }
859 if (!turn_servers.empty()) {
860 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
861 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700863 // Send information about IPv4/IPv6 status.
864 PeerConnectionAddressFamilyCounter address_family;
865 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
866 address_family = kPeerConnection_IPv6;
867 } else {
868 address_family = kPeerConnection_IPv4;
869 }
870 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
871 kPeerConnectionAddressFamilyCounter_Max);
872
Zhi Huange830e682018-03-30 10:48:35 -0700873 const PeerConnectionFactoryInterface::Options& options = factory_->options();
874
Steve Anton75737c02017-11-06 10:37:17 -0800875 // RFC 3264: The numeric value of the session id and version in the
876 // o line MUST be representable with a "64 bit signed integer".
877 // Due to this constraint session id |session_id_| is max limited to
878 // LLONG_MAX.
879 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700880 JsepTransportController::Config config;
881 config.redetermine_role_on_ice_restart =
882 configuration.redetermine_role_on_ice_restart;
883 config.ssl_max_version = factory_->options().ssl_max_version;
884 config.disable_encryption = options.disable_encryption;
885 config.bundle_policy = configuration.bundle_policy;
886 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
887 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700888 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700889 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700890#if defined(ENABLE_EXTERNAL_AUTH)
891 config.enable_external_auth = true;
892#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700893 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700894 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700895 signaling_thread(), network_thread(), port_allocator_.get(),
896 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700897 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800898 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700899 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800900 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700901 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800902 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700903 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800904 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
905 transport_controller_->SignalDtlsHandshakeError.connect(
906 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
907
908 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700909
deadbeefab9b2d12015-10-14 11:33:11 -0700910 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700911 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000912
Steve Antonba818672017-11-06 10:21:57 -0800913 configuration_ = configuration;
914
Steve Anton75737c02017-11-06 10:37:17 -0800915 // Obtain a certificate from RTCConfiguration if any were provided (optional).
916 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
917 if (!configuration.certificates.empty()) {
918 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
919 // just picking the first one. The decision should be made based on the DTLS
920 // handshake. The DTLS negotiations need to know about all certificates.
921 certificate = configuration.certificates[0];
922 }
923
Steve Antond25da372017-11-06 14:50:29 -0800924 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800925
926 if (options.disable_encryption) {
927 dtls_enabled_ = false;
928 } else {
929 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700930 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800931 // |configuration| can override the default |dtls_enabled_| value.
932 if (configuration.enable_dtls_srtp) {
933 dtls_enabled_ = *(configuration.enable_dtls_srtp);
934 }
935 }
936
937 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
938 // It takes precendence over the disable_sctp_data_channels
939 // PeerConnectionFactoryInterface::Options.
940 if (configuration.enable_rtp_data_channel) {
941 data_channel_type_ = cricket::DCT_RTP;
942 } else {
943 // DTLS has to be enabled to use SCTP.
944 if (!options.disable_sctp_data_channels && dtls_enabled_) {
945 data_channel_type_ = cricket::DCT_SCTP;
946 }
947 }
948
949 video_options_.screencast_min_bitrate_kbps =
950 configuration.screencast_min_bitrate;
951 audio_options_.combined_audio_video_bwe =
952 configuration.combined_audio_video_bwe;
953
954 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100955 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800956
957 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100958 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800959
960 // Whether the certificate generator/certificate is null or not determines
961 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
962 // the right instructions by clearing the variables if needed.
963 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -0700964 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800965 certificate = nullptr;
966 } else if (certificate) {
967 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700968 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800969 }
970
971 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
972 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -0700973 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -0800974 webrtc_session_desc_factory_->SignalCertificateReady.connect(
975 this, &PeerConnection::OnCertificateReady);
976
977 if (options.disable_encryption) {
978 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
979 }
980
981 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
982 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000983
Steve Anton4171afb2017-11-20 10:20:22 -0800984 // Add default audio/video transceivers for Plan B SDP.
985 if (!IsUnifiedPlan()) {
986 transceivers_.push_back(
987 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
988 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
989 transceivers_.push_back(
990 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
991 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
992 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +0200993 int delay_ms =
994 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonbb192762018-08-31 11:57:02 -0700995 async_invoker_.AsyncInvokeDelayed<void>(RTC_FROM_HERE, signaling_thread(),
996 [this] { ReportUsagePattern(); },
997 delay_ms);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998 return true;
999}
1000
Steve Anton038834f2017-07-14 15:59:59 -07001001RTCError PeerConnection::ValidateConfiguration(
1002 const RTCConfiguration& config) const {
1003 if (config.ice_regather_interval_range &&
1004 config.continual_gathering_policy == GATHER_ONCE) {
1005 return RTCError(RTCErrorType::INVALID_PARAMETER,
1006 "ice_regather_interval_range specified but continual "
1007 "gathering policy is GATHER_ONCE");
1008 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001009 auto result =
1010 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1011 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001012}
1013
Yves Gerey665174f2018-06-19 15:03:05 +02001014rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001015 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1016 "Plan SdpSemantics. Please use GetSenders "
1017 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001018 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019}
1020
Yves Gerey665174f2018-06-19 15:03:05 +02001021rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001022 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1023 "Plan SdpSemantics. Please use GetReceivers "
1024 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001025 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026}
1027
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001028bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001029 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1030 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001031 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032 if (IsClosed()) {
1033 return false;
1034 }
deadbeefab9b2d12015-10-14 11:33:11 -07001035 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036 return false;
1037 }
deadbeefab9b2d12015-10-14 11:33:11 -07001038
1039 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001040 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1041 observer->SignalAudioTrackAdded.connect(this,
1042 &PeerConnection::OnAudioTrackAdded);
1043 observer->SignalAudioTrackRemoved.connect(
1044 this, &PeerConnection::OnAudioTrackRemoved);
1045 observer->SignalVideoTrackAdded.connect(this,
1046 &PeerConnection::OnVideoTrackAdded);
1047 observer->SignalVideoTrackRemoved.connect(
1048 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001049 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001050
deadbeefab9b2d12015-10-14 11:33:11 -07001051 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001052 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001053 }
1054 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001055 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001056 }
1057
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001058 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001059 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060 return true;
1061}
1062
1063void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001064 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1065 "Plan SdpSemantics. Please use RemoveTrack "
1066 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001067 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001068 if (!IsClosed()) {
1069 for (const auto& track : local_stream->GetAudioTracks()) {
1070 RemoveAudioTrack(track.get(), local_stream);
1071 }
1072 for (const auto& track : local_stream->GetVideoTracks()) {
1073 RemoveVideoTrack(track.get(), local_stream);
1074 }
deadbeefab9b2d12015-10-14 11:33:11 -07001075 }
deadbeefab9b2d12015-10-14 11:33:11 -07001076 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001077 stream_observers_.erase(
1078 std::remove_if(
1079 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001080 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001081 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001082 }),
1083 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001084
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085 if (IsClosed()) {
1086 return;
1087 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001088 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001089}
1090
Steve Anton2d6c76a2018-01-05 17:10:52 -08001091RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001092 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001093 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001094 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001095 if (!track) {
1096 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1097 }
1098 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1099 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1100 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1101 "Track has invalid kind: " + track->kind());
1102 }
Steve Antonf9381f02017-12-14 10:23:57 -08001103 if (IsClosed()) {
1104 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1105 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001106 }
Steve Anton4171afb2017-11-20 10:20:22 -08001107 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001108 LOG_AND_RETURN_ERROR(
1109 RTCErrorType::INVALID_PARAMETER,
1110 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001111 }
Steve Antonf9381f02017-12-14 10:23:57 -08001112 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001113 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1114 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001115 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001116 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001117 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001118 }
1119 return sender_or_error;
1120}
deadbeefe1f9d832016-01-14 15:35:42 -08001121
Steve Antonf9381f02017-12-14 10:23:57 -08001122RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1123PeerConnection::AddTrackPlanB(
1124 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001125 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001126 if (stream_ids.size() > 1u) {
1127 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1128 "AddTrack with more than one stream is not "
1129 "supported with Plan B semantics.");
1130 }
1131 std::vector<std::string> adjusted_stream_ids = stream_ids;
1132 if (adjusted_stream_ids.empty()) {
1133 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1134 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001135 cricket::MediaType media_type =
1136 (track->kind() == MediaStreamTrackInterface::kAudioKind
1137 ? cricket::MEDIA_TYPE_AUDIO
1138 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001139 auto new_sender =
1140 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001141 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001142 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001143 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001144 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001145 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001146 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001147 if (sender_info) {
1148 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001149 }
Steve Antonf9381f02017-12-14 10:23:57 -08001150 } else {
1151 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001152 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001153 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001154 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001155 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001156 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001157 if (sender_info) {
1158 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001159 }
deadbeefe1f9d832016-01-14 15:35:42 -08001160 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001161 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001162}
deadbeefe1f9d832016-01-14 15:35:42 -08001163
Steve Antonf9381f02017-12-14 10:23:57 -08001164RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1165PeerConnection::AddTrackUnifiedPlan(
1166 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001167 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001168 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1169 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001170 RTC_LOG(LS_INFO) << "Reusing an existing "
1171 << cricket::MediaTypeToString(transceiver->media_type())
1172 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001173 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001174 transceiver->internal()->set_direction(
1175 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001176 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001177 transceiver->internal()->set_direction(
1178 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001179 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001180 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001181 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001182 } else {
1183 cricket::MediaType media_type =
1184 (track->kind() == MediaStreamTrackInterface::kAudioKind
1185 ? cricket::MEDIA_TYPE_AUDIO
1186 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001187 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1188 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001189 std::string sender_id = track->id();
1190 // Avoid creating a sender with an existing ID by generating a random ID.
1191 // This can happen if this is the second time AddTrack has created a sender
1192 // for this track.
1193 if (FindSenderById(sender_id)) {
1194 sender_id = rtc::CreateRandomUuid();
1195 }
1196 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001197 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1198 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001199 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001200 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001201 }
Steve Antonf9381f02017-12-14 10:23:57 -08001202 return transceiver->sender();
1203}
1204
1205rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1206PeerConnection::FindFirstTransceiverForAddedTrack(
1207 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1208 RTC_DCHECK(track);
1209 for (auto transceiver : transceivers_) {
1210 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001211 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001212 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001213 !transceiver->internal()->has_ever_been_used_to_send() &&
1214 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001215 return transceiver;
1216 }
1217 }
1218 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001219}
1220
1221bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1222 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001223 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001224}
1225
Steve Anton24db5732018-07-23 10:27:33 -07001226RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001227 rtc::scoped_refptr<RtpSenderInterface> sender) {
1228 if (!sender) {
1229 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1230 }
deadbeefe1f9d832016-01-14 15:35:42 -08001231 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001232 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1233 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001234 }
Steve Antonf9381f02017-12-14 10:23:57 -08001235 if (IsUnifiedPlan()) {
1236 auto transceiver = FindTransceiverBySender(sender);
1237 if (!transceiver || !sender->track()) {
1238 return RTCError::OK();
1239 }
1240 sender->SetTrack(nullptr);
1241 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001242 transceiver->internal()->set_direction(
1243 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001244 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001245 transceiver->internal()->set_direction(
1246 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001247 }
Steve Anton4171afb2017-11-20 10:20:22 -08001248 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001249 bool removed;
1250 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1251 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1252 } else {
1253 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1254 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1255 }
1256 if (!removed) {
1257 LOG_AND_RETURN_ERROR(
1258 RTCErrorType::INVALID_PARAMETER,
1259 "Couldn't find sender " + sender->id() + " to remove.");
1260 }
Steve Anton4171afb2017-11-20 10:20:22 -08001261 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001262 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001263 return RTCError::OK();
1264}
1265
1266rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1267PeerConnection::FindTransceiverBySender(
1268 rtc::scoped_refptr<RtpSenderInterface> sender) {
1269 for (auto transceiver : transceivers_) {
1270 if (transceiver->sender() == sender) {
1271 return transceiver;
1272 }
1273 }
1274 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001275}
1276
Steve Anton9158ef62017-11-27 13:01:52 -08001277RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1278PeerConnection::AddTransceiver(
1279 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1280 return AddTransceiver(track, RtpTransceiverInit());
1281}
1282
1283RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1284PeerConnection::AddTransceiver(
1285 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1286 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001287 RTC_CHECK(IsUnifiedPlan())
1288 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001289 if (!track) {
1290 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1291 }
1292 cricket::MediaType media_type;
1293 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1294 media_type = cricket::MEDIA_TYPE_AUDIO;
1295 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1296 media_type = cricket::MEDIA_TYPE_VIDEO;
1297 } else {
1298 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1299 "Track kind is not audio or video");
1300 }
1301 return AddTransceiver(media_type, track, init);
1302}
1303
1304RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1305PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1306 return AddTransceiver(media_type, RtpTransceiverInit());
1307}
1308
1309RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1310PeerConnection::AddTransceiver(cricket::MediaType media_type,
1311 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001312 RTC_CHECK(IsUnifiedPlan())
1313 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001314 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1315 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1317 "media type is not audio or video");
1318 }
1319 return AddTransceiver(media_type, nullptr, init);
1320}
1321
1322RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1323PeerConnection::AddTransceiver(
1324 cricket::MediaType media_type,
1325 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001326 const RtpTransceiverInit& init,
1327 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001328 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1329 media_type == cricket::MEDIA_TYPE_VIDEO));
1330 if (track) {
1331 RTC_DCHECK_EQ(media_type,
1332 (track->kind() == MediaStreamTrackInterface::kAudioKind
1333 ? cricket::MEDIA_TYPE_AUDIO
1334 : cricket::MEDIA_TYPE_VIDEO));
1335 }
1336
1337 // TODO(bugs.webrtc.org/7600): Verify init.
1338
Steve Anton3d954a62018-04-02 11:27:23 -07001339 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1340 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001341 // Set the sender ID equal to the track ID if the track is specified unless
1342 // that sender ID is already in use.
1343 std::string sender_id =
1344 (track && !FindSenderById(track->id()) ? track->id()
1345 : rtc::CreateRandomUuid());
1346 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001347 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1348 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1349 transceiver->internal()->set_direction(init.direction);
1350
Steve Anton22da89f2018-01-25 13:58:07 -08001351 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001352 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001353 }
Steve Antonf9381f02017-12-14 10:23:57 -08001354
1355 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1356}
1357
Steve Anton02ee47c2018-01-10 16:26:06 -08001358rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1359PeerConnection::CreateSender(
1360 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001361 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001362 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001363 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001364 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001365 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1366 RTC_DCHECK(!track ||
1367 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1368 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1369 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001370 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001371 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001372 } else {
1373 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1374 RTC_DCHECK(!track ||
1375 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1376 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001377 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001378 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001379 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001380 bool set_track_succeeded = sender->SetTrack(track);
1381 RTC_DCHECK(set_track_succeeded);
1382 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001383 return sender;
1384}
1385
1386rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1387PeerConnection::CreateReceiver(cricket::MediaType media_type,
1388 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001389 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1390 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001391 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001392 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001393 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1394 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001395 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001396 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001397 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001398 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001399 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1400 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001401 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001402 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001403 return receiver;
1404}
1405
1406rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1407PeerConnection::CreateAndAddTransceiver(
1408 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1409 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1410 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001411 // Ensure that the new sender does not have an ID that is already in use by
1412 // another sender.
1413 // Allow receiver IDs to conflict since those come from remote SDP (which
1414 // could be invalid, but should not cause a crash).
1415 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001416 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1417 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001418 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001419 transceiver->internal()->SignalNegotiationNeeded.connect(
1420 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001421 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001422}
1423
Steve Anton52d86772018-02-20 15:48:12 -08001424void PeerConnection::OnNegotiationNeeded() {
1425 RTC_DCHECK_RUN_ON(signaling_thread());
1426 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001427 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001428}
1429
deadbeeffac06552015-11-25 11:26:01 -08001430rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001431 const std::string& kind,
1432 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001433 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1434 "Plan SdpSemantics. Please use AddTransceiver "
1435 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001436 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001437 if (IsClosed()) {
1438 return nullptr;
1439 }
Steve Anton4171afb2017-11-20 10:20:22 -08001440
Seth Hampson5b4f0752018-04-02 16:31:36 -07001441 // Internally we need to have one stream with Plan B semantics, so we
1442 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001443 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001444 if (stream_id.empty()) {
1445 stream_ids.push_back(rtc::CreateRandomUuid());
1446 RTC_LOG(LS_INFO)
1447 << "No stream_id specified for sender. Generated stream ID: "
1448 << stream_ids[0];
1449 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001450 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001451 }
1452
Steve Anton4171afb2017-11-20 10:20:22 -08001453 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001454 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001455 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001456 auto* audio_sender = new AudioRtpSender(
1457 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001458 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001459 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001460 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001461 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001462 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001463 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001464 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001465 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001466 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001467 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001468 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001469 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001470 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001471 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001472 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001473 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001474
deadbeefe1f9d832016-01-14 15:35:42 -08001475 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001476}
1477
deadbeef70ab1a12015-09-28 16:53:55 -07001478std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1479 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001480 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001481 for (auto sender : GetSendersInternal()) {
1482 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001483 }
1484 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001485}
1486
Steve Anton4171afb2017-11-20 10:20:22 -08001487std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1488PeerConnection::GetSendersInternal() const {
1489 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1490 all_senders;
1491 for (auto transceiver : transceivers_) {
1492 auto senders = transceiver->internal()->senders();
1493 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1494 }
1495 return all_senders;
1496}
1497
deadbeef70ab1a12015-09-28 16:53:55 -07001498std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1499PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001500 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001501 for (const auto& receiver : GetReceiversInternal()) {
1502 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001503 }
1504 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001505}
1506
Steve Anton4171afb2017-11-20 10:20:22 -08001507std::vector<
1508 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1509PeerConnection::GetReceiversInternal() const {
1510 std::vector<
1511 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1512 all_receivers;
1513 for (auto transceiver : transceivers_) {
1514 auto receivers = transceiver->internal()->receivers();
1515 all_receivers.insert(all_receivers.end(), receivers.begin(),
1516 receivers.end());
1517 }
1518 return all_receivers;
1519}
1520
Steve Anton9158ef62017-11-27 13:01:52 -08001521std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1522PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001523 RTC_CHECK(IsUnifiedPlan())
1524 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001525 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1526 for (auto transceiver : transceivers_) {
1527 all_transceivers.push_back(transceiver);
1528 }
1529 return all_transceivers;
1530}
1531
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001532bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001533 MediaStreamTrackInterface* track,
1534 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001535 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001536 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001537 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001538 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001539 return false;
1540 }
1541
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001542 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001543 // The StatsCollector is used to tell if a track is valid because it may
1544 // remember tracks that the PeerConnection previously removed.
1545 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001546 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1547 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001548 return false;
1549 }
Steve Antonbb192762018-08-31 11:57:02 -07001550 // Need to capture |observer| and |track| in scoped_refptrs to ensure they
1551 // live long enough.
1552 rtc::scoped_refptr<StatsObserver> observer_refptr(observer);
1553 rtc::scoped_refptr<MediaStreamTrackInterface> track_refptr(track);
1554 async_invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(),
1555 [this, observer_refptr, track_refptr] {
1556 StatsReports reports;
1557 stats_->GetStats(track_refptr, &reports);
1558 observer_refptr->OnComplete(reports);
1559 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560 return true;
1561}
1562
hbos74e1a4f2016-09-15 23:33:01 -07001563void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001564 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001565 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001566 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001567 stats_collector_->GetStatsReport(callback);
1568}
1569
Henrik Boström1df1bf82018-03-20 13:24:20 +01001570void PeerConnection::GetStats(
1571 rtc::scoped_refptr<RtpSenderInterface> selector,
1572 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1573 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1574 RTC_DCHECK(callback);
1575 RTC_DCHECK(stats_collector_);
1576 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1577 if (selector) {
1578 for (const auto& proxy_transceiver : transceivers_) {
1579 for (const auto& proxy_sender :
1580 proxy_transceiver->internal()->senders()) {
1581 if (proxy_sender == selector) {
1582 internal_sender = proxy_sender->internal();
1583 break;
1584 }
1585 }
1586 if (internal_sender)
1587 break;
1588 }
1589 }
1590 // If there is no |internal_sender| then |selector| is either null or does not
1591 // belong to the PeerConnection (in Plan B, senders can be removed from the
1592 // PeerConnection). This means that "all the stats objects representing the
1593 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1594 // produces an empty stats report.
1595 stats_collector_->GetStatsReport(internal_sender, callback);
1596}
1597
1598void PeerConnection::GetStats(
1599 rtc::scoped_refptr<RtpReceiverInterface> selector,
1600 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1601 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1602 RTC_DCHECK(callback);
1603 RTC_DCHECK(stats_collector_);
1604 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1605 if (selector) {
1606 for (const auto& proxy_transceiver : transceivers_) {
1607 for (const auto& proxy_receiver :
1608 proxy_transceiver->internal()->receivers()) {
1609 if (proxy_receiver == selector) {
1610 internal_receiver = proxy_receiver->internal();
1611 break;
1612 }
1613 }
1614 if (internal_receiver)
1615 break;
1616 }
1617 }
1618 // If there is no |internal_receiver| then |selector| is either null or does
1619 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1620 // the PeerConnection). This means that "all the stats objects representing
1621 // the selector" is an empty set. Invoking GetStatsReport() with a null
1622 // selector produces an empty stats report.
1623 stats_collector_->GetStatsReport(internal_receiver, callback);
1624}
1625
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1627 return signaling_state_;
1628}
1629
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630PeerConnectionInterface::IceConnectionState
1631PeerConnection::ice_connection_state() {
1632 return ice_connection_state_;
1633}
1634
1635PeerConnectionInterface::IceGatheringState
1636PeerConnection::ice_gathering_state() {
1637 return ice_gathering_state_;
1638}
1639
Yves Gerey665174f2018-06-19 15:03:05 +02001640rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001641 const std::string& label,
1642 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001643 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001644
deadbeefab9b2d12015-10-14 11:33:11 -07001645 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001646
kwibergd1fe2812016-04-27 06:47:29 -07001647 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001648 if (config) {
1649 internal_config.reset(new InternalDataChannelInit(*config));
1650 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001651 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001652 InternalCreateDataChannel(label, internal_config.get()));
1653 if (!channel.get()) {
1654 return nullptr;
1655 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001656
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001657 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1658 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001659 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001660 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001661 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001662 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001663 return DataChannelProxy::Create(signaling_thread(), channel.get());
1664}
1665
1666void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001667 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001668 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001669
nisse7ce109a2017-01-31 00:57:56 -08001670 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001671 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001672 return;
1673 }
deadbeefab9b2d12015-10-14 11:33:11 -07001674
Steve Anton8d3444d2017-10-20 15:30:51 -07001675 if (IsClosed()) {
1676 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001677 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001678 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001679 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001680 return;
1681 }
1682
zhihuang1c378ed2017-08-17 14:10:50 -07001683 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001684 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001685 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001686 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001687 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001688 return;
1689 }
1690
Steve Anton22da89f2018-01-25 13:58:07 -08001691 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1692 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1693 if (IsUnifiedPlan()) {
1694 RTCError error = HandleLegacyOfferOptions(options);
1695 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001696 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001697 return;
1698 }
1699 }
1700
zhihuang1c378ed2017-08-17 14:10:50 -07001701 cricket::MediaSessionOptions session_options;
1702 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001703 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704}
1705
Steve Anton22da89f2018-01-25 13:58:07 -08001706RTCError PeerConnection::HandleLegacyOfferOptions(
1707 const RTCOfferAnswerOptions& options) {
1708 RTC_DCHECK(IsUnifiedPlan());
1709
1710 if (options.offer_to_receive_audio == 0) {
1711 RemoveRecvDirectionFromReceivingTransceiversOfType(
1712 cricket::MEDIA_TYPE_AUDIO);
1713 } else if (options.offer_to_receive_audio == 1) {
1714 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1715 } else if (options.offer_to_receive_audio > 1) {
1716 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1717 "offer_to_receive_audio > 1 is not supported.");
1718 }
1719
1720 if (options.offer_to_receive_video == 0) {
1721 RemoveRecvDirectionFromReceivingTransceiversOfType(
1722 cricket::MEDIA_TYPE_VIDEO);
1723 } else if (options.offer_to_receive_video == 1) {
1724 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1725 } else if (options.offer_to_receive_video > 1) {
1726 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1727 "offer_to_receive_video > 1 is not supported.");
1728 }
1729
1730 return RTCError::OK();
1731}
1732
1733void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1734 cricket::MediaType media_type) {
1735 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001736 RtpTransceiverDirection new_direction =
1737 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1738 if (new_direction != transceiver->direction()) {
1739 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1740 << " transceiver (MID="
1741 << transceiver->mid().value_or("<not set>") << ") from "
1742 << RtpTransceiverDirectionToString(
1743 transceiver->direction())
1744 << " to "
1745 << RtpTransceiverDirectionToString(new_direction)
1746 << " since CreateOffer specified offer_to_receive=0";
1747 transceiver->internal()->set_direction(new_direction);
1748 }
Steve Anton22da89f2018-01-25 13:58:07 -08001749 }
1750}
1751
1752void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1753 cricket::MediaType media_type) {
1754 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001755 RTC_LOG(LS_INFO)
1756 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1757 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001758 RtpTransceiverInit init;
1759 init.direction = RtpTransceiverDirection::kRecvOnly;
1760 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1761 }
1762}
1763
1764std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1765PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1766 std::vector<
1767 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1768 receiving_transceivers;
1769 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001770 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001771 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1772 receiving_transceivers.push_back(transceiver);
1773 }
1774 }
1775 return receiving_transceivers;
1776}
1777
htaa2a49d92016-03-04 02:51:39 -08001778void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1779 const RTCOfferAnswerOptions& options) {
1780 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001781 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001782 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001783 return;
1784 }
1785
Steve Antondffead82018-02-06 10:31:29 -08001786 if (!(signaling_state_ == kHaveRemoteOffer ||
1787 signaling_state_ == kHaveLocalPrAnswer)) {
1788 std::string error =
1789 "PeerConnection cannot create an answer in a state other than "
1790 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001791 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001792 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001793 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001794 return;
1795 }
1796
Steve Antondffead82018-02-06 10:31:29 -08001797 // The remote description should be set if we're in the right state.
1798 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001799
Steve Anton22da89f2018-01-25 13:58:07 -08001800 if (IsUnifiedPlan()) {
1801 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1802 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1803 "supported with Unified Plan semantics. Use the "
1804 "RtpTransceiver API instead.";
1805 }
1806 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1807 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1808 "supported with Unified Plan semantics. Use the "
1809 "RtpTransceiver API instead.";
1810 }
1811 }
1812
htaa2a49d92016-03-04 02:51:39 -08001813 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001814 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001815
Steve Antond25da372017-11-06 14:50:29 -08001816 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001817}
1818
1819void PeerConnection::SetLocalDescription(
1820 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001821 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001822 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001823
Steve Anton80dd7b52018-02-16 17:08:42 -08001824 // The SetLocalDescription contract is that we take ownership of the session
1825 // description regardless of the outcome, so wrap it in a unique_ptr right
1826 // away. Ideally, SetLocalDescription's signature will be changed to take the
1827 // description as a unique_ptr argument to formalize this agreement.
1828 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1829
nisse7ce109a2017-01-31 00:57:56 -08001830 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001831 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 return;
1833 }
Steve Anton8a006912017-12-04 15:25:56 -08001834
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001835 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001836 PostSetSessionDescriptionFailure(
1837 observer,
1838 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839 return;
1840 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001841
Steve Anton80dd7b52018-02-16 17:08:42 -08001842 // If a session error has occurred the PeerConnection is in a possibly
1843 // inconsistent state so fail right away.
1844 if (session_error() != SessionError::kNone) {
1845 std::string error_message = GetSessionErrorMsg();
1846 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001847 PostSetSessionDescriptionFailure(
1848 observer,
1849 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001850 return;
1851 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001852
Steve Anton80dd7b52018-02-16 17:08:42 -08001853 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1854 if (!error.ok()) {
1855 std::string error_message = GetSetDescriptionErrorMessage(
1856 cricket::CS_LOCAL, desc->GetType(), error);
1857 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001858 PostSetSessionDescriptionFailure(
1859 observer,
1860 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001861 return;
1862 }
1863
1864 // Grab the description type before moving ownership to ApplyLocalDescription,
1865 // which may destroy it before returning.
1866 const SdpType type = desc->GetType();
1867
1868 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001869 // |desc| may be destroyed at this point.
1870
1871 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001872 // If ApplyLocalDescription fails, the PeerConnection could be in an
1873 // inconsistent state, so act conservatively here and set the session error
1874 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1875 SetSessionError(SessionError::kContent, error.message());
1876 std::string error_message =
1877 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1878 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001879 PostSetSessionDescriptionFailure(
1880 observer,
1881 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001882 return;
1883 }
Steve Anton8a006912017-12-04 15:25:56 -08001884 RTC_DCHECK(local_description());
1885
1886 PostSetSessionDescriptionSuccess(observer);
1887
Steve Antonbb192762018-08-31 11:57:02 -07001888 // MaybeStartGathering needs to be called after posting OnSuccess to the
1889 // SetSessionDescriptionObserver so that we don't signal any candidates before
1890 // signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001891 transport_controller_->MaybeStartGathering();
1892
Steve Antona3a92c22017-12-07 10:27:41 -08001893 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001894 // TODO(deadbeef): We already had to hop to the network thread for
1895 // MaybeStartGathering...
1896 network_thread()->Invoke<void>(
1897 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1898 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001899 // Make UMA notes about what was agreed to.
1900 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001901 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001902 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001903}
1904
1905RTCError PeerConnection::ApplyLocalDescription(
1906 std::unique_ptr<SessionDescriptionInterface> desc) {
1907 RTC_DCHECK_RUN_ON(signaling_thread());
1908 RTC_DCHECK(desc);
1909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 // Update stats here so that we have the most recent stats for tracks and
1911 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001912 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001913
Steve Antondcc3c022017-12-22 16:02:54 -08001914 // Take a reference to the old local description since it's used below to
1915 // compare against the new local description. When setting the new local
1916 // description, grab ownership of the replaced session description in case it
1917 // is the same as |old_local_description|, to keep it alive for the duration
1918 // of the method.
1919 const SessionDescriptionInterface* old_local_description =
1920 local_description();
1921 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001922 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001923 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001924 replaced_local_description = pending_local_description_
1925 ? std::move(pending_local_description_)
1926 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001927 current_local_description_ = std::move(desc);
1928 pending_local_description_ = nullptr;
1929 current_remote_description_ = std::move(pending_remote_description_);
1930 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001931 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001932 pending_local_description_ = std::move(desc);
1933 }
1934 // The session description to apply now must be accessed by
1935 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001936 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001937
Zhi Huange830e682018-03-30 10:48:35 -07001938 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
1939 if (!error.ok()) {
1940 return error;
1941 }
1942
Steve Antondcc3c022017-12-22 16:02:54 -08001943 if (IsUnifiedPlan()) {
1944 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001945 cricket::CS_LOCAL, *local_description(), old_local_description,
1946 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001947 if (!error.ok()) {
1948 return error;
1949 }
Steve Anton0f5400a2018-07-17 14:25:36 -07001950 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
1951 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08001952 for (auto transceiver : transceivers_) {
1953 const ContentInfo* content =
1954 FindMediaSectionForTransceiver(transceiver, local_description());
1955 if (!content) {
1956 continue;
1957 }
1958 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07001959 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
1960 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08001961 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07001962 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
1963 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
1964 // "recvonly", process the removal of a remote track for the media
1965 // description, given transceiver, removeList, and muteTracks.
1966 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
1967 (transceiver->internal()->fired_direction() &&
1968 RtpTransceiverDirectionHasRecv(
1969 *transceiver->internal()->fired_direction()))) {
1970 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
1971 &removed_streams);
1972 }
1973 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
1974 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08001975 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07001976 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08001977 }
Steve Anton0f5400a2018-07-17 14:25:36 -07001978 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001979 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07001980 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001981 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07001982 }
1983 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001984 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08001985 }
1986 } else {
Zhi Huange830e682018-03-30 10:48:35 -07001987 // Media channels will be created only when offer is set. These may use new
1988 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08001989 if (type == SdpType::kOffer) {
1990 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1991 // description is applied. Restore back to old description.
1992 RTCError error = CreateChannels(*local_description()->description());
1993 if (!error.ok()) {
1994 return error;
1995 }
1996 }
Steve Antondcc3c022017-12-22 16:02:54 -08001997 // Remove unused channels if MediaContentDescription is rejected.
1998 RemoveUnusedChannels(local_description()->description());
1999 }
Steve Anton8a006912017-12-04 15:25:56 -08002000
Zhi Huange830e682018-03-30 10:48:35 -07002001 error = UpdateSessionState(type, cricket::CS_LOCAL,
2002 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002003 if (!error.ok()) {
2004 return error;
2005 }
Steve Antondcc3c022017-12-22 16:02:54 -08002006
Steve Anton8a006912017-12-04 15:25:56 -08002007 if (remote_description()) {
2008 // Now that we have a local description, we can push down remote candidates.
2009 UseCandidatesInSessionDescription(remote_description());
2010 }
2011
2012 pending_ice_restarts_.clear();
2013 if (session_error() != SessionError::kNone) {
2014 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2015 }
2016
deadbeefab9b2d12015-10-14 11:33:11 -07002017 // If setting the description decided our SSL role, allocate any necessary
2018 // SCTP sids.
2019 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002020 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002021 AllocateSctpSids(role);
2022 }
2023
Steve Antond3679212018-01-17 17:41:02 -08002024 if (IsUnifiedPlan()) {
2025 for (auto transceiver : transceivers_) {
2026 const ContentInfo* content =
2027 FindMediaSectionForTransceiver(transceiver, local_description());
2028 if (!content) {
2029 continue;
2030 }
Steve Anton74255ff2018-01-24 18:32:57 -08002031 const auto& streams = content->media_description()->streams();
2032 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002033 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002034 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002035 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002036 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002037 } else {
2038 // 0 is a special value meaning "this sender has no associated send
2039 // stream". Need to call this so the sender won't attempt to configure
2040 // a no longer existing stream and run into DCHECKs in the lower
2041 // layers.
2042 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002043 }
2044 }
2045 } else {
2046 // Plan B semantics.
2047
Steve Antondcc3c022017-12-22 16:02:54 -08002048 // Update state and SSRC of local MediaStreams and DataChannels based on the
2049 // local session description.
2050 const cricket::ContentInfo* audio_content =
2051 GetFirstAudioContent(local_description()->description());
2052 if (audio_content) {
2053 if (audio_content->rejected) {
2054 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2055 } else {
2056 const cricket::AudioContentDescription* audio_desc =
2057 audio_content->media_description()->as_audio();
2058 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2059 }
deadbeeffaac4972015-11-12 15:33:07 -08002060 }
deadbeefab9b2d12015-10-14 11:33:11 -07002061
Steve Antondcc3c022017-12-22 16:02:54 -08002062 const cricket::ContentInfo* video_content =
2063 GetFirstVideoContent(local_description()->description());
2064 if (video_content) {
2065 if (video_content->rejected) {
2066 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2067 } else {
2068 const cricket::VideoContentDescription* video_desc =
2069 video_content->media_description()->as_video();
2070 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2071 }
deadbeeffaac4972015-11-12 15:33:07 -08002072 }
deadbeefab9b2d12015-10-14 11:33:11 -07002073 }
2074
2075 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002076 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002077 if (data_content) {
2078 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002079 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002080 if (rtc::starts_with(data_desc->protocol().data(),
2081 cricket::kMediaProtocolRtpPrefix)) {
2082 UpdateLocalRtpDataChannels(data_desc->streams());
2083 }
2084 }
2085
Steve Anton8a006912017-12-04 15:25:56 -08002086 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002087}
2088
2089void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002090 SetSessionDescriptionObserver* observer,
2091 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002092 SetRemoteDescription(
2093 std::unique_ptr<SessionDescriptionInterface>(desc),
2094 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2095 new SetRemoteDescriptionObserverAdapter(this, observer)));
2096}
2097
2098void PeerConnection::SetRemoteDescription(
2099 std::unique_ptr<SessionDescriptionInterface> desc,
2100 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002101 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002102
nisse7ce109a2017-01-31 00:57:56 -08002103 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002104 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002105 return;
2106 }
Steve Anton8a006912017-12-04 15:25:56 -08002107
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002109 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002110 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002111 return;
2112 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002113
Steve Anton80dd7b52018-02-16 17:08:42 -08002114 // If a session error has occurred the PeerConnection is in a possibly
2115 // inconsistent state so fail right away.
2116 if (session_error() != SessionError::kNone) {
2117 std::string error_message = GetSessionErrorMsg();
2118 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2119 observer->OnSetRemoteDescriptionComplete(
2120 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2121 return;
2122 }
Steve Anton71439a62018-02-15 11:53:06 -08002123
Steve Antonba42e992018-04-09 14:10:01 -07002124 if (desc->GetType() == SdpType::kOffer) {
2125 // Report to UMA the format of the received offer.
2126 ReportSdpFormatReceived(*desc);
2127 }
2128
Steve Anton80dd7b52018-02-16 17:08:42 -08002129 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002130 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002131 std::string error_message = GetSetDescriptionErrorMessage(
2132 cricket::CS_REMOTE, desc->GetType(), error);
2133 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002134 observer->OnSetRemoteDescriptionComplete(
2135 RTCError(error.type(), std::move(error_message)));
2136 return;
2137 }
Steve Anton71439a62018-02-15 11:53:06 -08002138
Steve Anton80dd7b52018-02-16 17:08:42 -08002139 // Grab the description type before moving ownership to
2140 // ApplyRemoteDescription, which may destroy it before returning.
2141 const SdpType type = desc->GetType();
2142
2143 error = ApplyRemoteDescription(std::move(desc));
2144 // |desc| may be destroyed at this point.
2145
2146 if (!error.ok()) {
2147 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2148 // inconsistent state, so act conservatively here and set the session error
2149 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2150 SetSessionError(SessionError::kContent, error.message());
2151 std::string error_message =
2152 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2153 RTC_LOG(LS_ERROR) << error_message;
2154 observer->OnSetRemoteDescriptionComplete(
2155 RTCError(error.type(), std::move(error_message)));
2156 return;
2157 }
2158 RTC_DCHECK(remote_description());
2159
2160 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002161 // TODO(deadbeef): We already had to hop to the network thread for
2162 // MaybeStartGathering...
2163 network_thread()->Invoke<void>(
2164 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2165 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002166 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002167 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002168 }
2169
2170 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002171 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002172}
2173
2174RTCError PeerConnection::ApplyRemoteDescription(
2175 std::unique_ptr<SessionDescriptionInterface> desc) {
2176 RTC_DCHECK_RUN_ON(signaling_thread());
2177 RTC_DCHECK(desc);
2178
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002179 // Update stats here so that we have the most recent stats for tracks and
2180 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002181 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002182
Steve Antondcc3c022017-12-22 16:02:54 -08002183 // Take a reference to the old remote description since it's used below to
2184 // compare against the new remote description. When setting the new remote
2185 // description, grab ownership of the replaced session description in case it
2186 // is the same as |old_remote_description|, to keep it alive for the duration
2187 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002188 const SessionDescriptionInterface* old_remote_description =
2189 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002190 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002191 SdpType type = desc->GetType();
2192 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002193 replaced_remote_description = pending_remote_description_
2194 ? std::move(pending_remote_description_)
2195 : std::move(current_remote_description_);
2196 current_remote_description_ = std::move(desc);
2197 pending_remote_description_ = nullptr;
2198 current_local_description_ = std::move(pending_local_description_);
2199 } else {
2200 replaced_remote_description = std::move(pending_remote_description_);
2201 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202 }
Steve Anton8a006912017-12-04 15:25:56 -08002203 // The session description to apply now must be accessed by
2204 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002205 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206
Zhi Huange830e682018-03-30 10:48:35 -07002207 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2208 if (!error.ok()) {
2209 return error;
2210 }
Steve Anton8a006912017-12-04 15:25:56 -08002211 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002212 if (IsUnifiedPlan()) {
2213 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002214 cricket::CS_REMOTE, *remote_description(), local_description(),
2215 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002216 if (!error.ok()) {
2217 return error;
2218 }
Steve Antondcc3c022017-12-22 16:02:54 -08002219 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002220 // Media channels will be created only when offer is set. These may use new
2221 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002222 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002223 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002224 // description is applied. Restore back to old description.
2225 RTCError error = CreateChannels(*remote_description()->description());
2226 if (!error.ok()) {
2227 return error;
2228 }
2229 }
Steve Antondcc3c022017-12-22 16:02:54 -08002230 // Remove unused channels if MediaContentDescription is rejected.
2231 RemoveUnusedChannels(remote_description()->description());
2232 }
Steve Anton8a006912017-12-04 15:25:56 -08002233
Zhi Huange830e682018-03-30 10:48:35 -07002234 // NOTE: Candidates allocation will be initiated only when
2235 // SetLocalDescription is called.
2236 error = UpdateSessionState(type, cricket::CS_REMOTE,
2237 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002238 if (!error.ok()) {
2239 return error;
2240 }
2241
2242 if (local_description() &&
2243 !UseCandidatesInSessionDescription(remote_description())) {
2244 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2245 }
2246
2247 if (old_remote_description) {
2248 for (const cricket::ContentInfo& content :
2249 old_remote_description->description()->contents()) {
2250 // Check if this new SessionDescription contains new ICE ufrag and
2251 // password that indicates the remote peer requests an ICE restart.
2252 // TODO(deadbeef): When we start storing both the current and pending
2253 // remote description, this should reset pending_ice_restarts and compare
2254 // against the current description.
2255 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2256 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002257 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002258 pending_ice_restarts_.insert(content.name);
2259 }
2260 } else {
2261 // We retain all received candidates only if ICE is not restarted.
2262 // When ICE is restarted, all previous candidates belong to an old
2263 // generation and should not be kept.
2264 // TODO(deadbeef): This goes against the W3C spec which says the remote
2265 // description should only contain candidates from the last set remote
2266 // description plus any candidates added since then. We should remove
2267 // this once we're sure it won't break anything.
2268 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2269 old_remote_description, content.name, mutable_remote_description());
2270 }
2271 }
2272 }
2273
2274 if (session_error() != SessionError::kNone) {
2275 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2276 }
2277
2278 // Set the the ICE connection state to connecting since the connection may
2279 // become writable with peer reflexive candidates before any remote candidate
2280 // is signaled.
2281 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2282 // is to have a new signal the indicates a change in checking state from the
2283 // transport and expose a new checking() member from transport that can be
2284 // read to determine the current checking state. The existing SignalConnecting
2285 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002286 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002287 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002288 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2289 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2290 }
2291
deadbeefab9b2d12015-10-14 11:33:11 -07002292 // If setting the description decided our SSL role, allocate any necessary
2293 // SCTP sids.
2294 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002295 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002296 AllocateSctpSids(role);
2297 }
2298
Steve Antondcc3c022017-12-22 16:02:54 -08002299 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002300 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002301 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002302 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002303 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002304 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002305 for (auto transceiver : transceivers_) {
2306 const ContentInfo* content =
2307 FindMediaSectionForTransceiver(transceiver, remote_description());
2308 if (!content) {
2309 continue;
2310 }
2311 const MediaContentDescription* media_desc = content->media_description();
2312 RtpTransceiverDirection local_direction =
2313 RtpTransceiverDirectionReversed(media_desc->direction());
2314 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2315 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2316 // transceiver's current direction is neither sendrecv nor recvonly,
2317 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002318 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002319 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002320 // The remote description has signaled the stream IDs.
2321 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002322 }
Steve Antondcc3c022017-12-22 16:02:54 -08002323 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002324 (!transceiver->fired_direction() ||
2325 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002326 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002327 << content->name << " (added to "
2328 << GetStreamIdsString(stream_ids) << ").";
2329
2330 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2331 for (const std::string& stream_id : stream_ids) {
2332 rtc::scoped_refptr<MediaStreamInterface> stream =
2333 remote_streams_->find(stream_id);
2334 if (!stream) {
2335 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2336 MediaStream::Create(stream_id));
2337 remote_streams_->AddStream(stream);
2338 added_streams.push_back(stream);
2339 }
2340 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002341 }
Steve Anton3172c032018-05-03 15:30:18 -07002342 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002343 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2344 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002345 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002346 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002347 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002348 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2349 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2350 // removal of a remote track for the media description, given transceiver,
2351 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002352 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002353 (transceiver->fired_direction() &&
2354 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2355 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2356 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002357 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002358 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2359 transceiver->internal()->set_fired_direction(local_direction);
2360 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2361 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002362 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002363 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2364 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002365 transceiver->internal()->set_current_direction(local_direction);
2366 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002367 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2368 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002369 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002370 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2371 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002372 transceiver->Stop();
2373 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002374 if (!content->rejected &&
2375 RtpTransceiverDirectionHasRecv(local_direction)) {
2376 // Set ssrc to 0 in the case of an unsignalled ssrc.
2377 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002378 if (!media_desc->streams().empty() &&
2379 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002380 ssrc = media_desc->streams()[0].first_ssrc();
2381 }
2382 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002383 }
Steve Antondcc3c022017-12-22 16:02:54 -08002384 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002385 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002386 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002387 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002388 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002389 observer->OnTrack(transceiver);
2390 observer->OnAddTrack(transceiver->receiver(),
2391 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002392 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002393 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002394 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002395 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002396 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002397 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002398 }
2399 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002400 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002401 }
Steve Antondcc3c022017-12-22 16:02:54 -08002402 }
2403
Henrik Boströmfdb92012017-11-09 19:55:44 +01002404 const cricket::ContentInfo* audio_content =
2405 GetFirstAudioContent(remote_description()->description());
2406 const cricket::ContentInfo* video_content =
2407 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002408 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002409 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002410 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002411 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002412 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002413 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002414
2415 // Check if the descriptions include streams, just in case the peer supports
2416 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002417 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002418 (audio_desc && !audio_desc->streams().empty()) ||
2419 (video_desc && !video_desc->streams().empty())) {
2420 remote_peer_supports_msid_ = true;
2421 }
deadbeefab9b2d12015-10-14 11:33:11 -07002422
2423 // We wait to signal new streams until we finish processing the description,
2424 // since only at that point will new streams have all their tracks.
2425 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2426
Steve Antondcc3c022017-12-22 16:02:54 -08002427 if (!IsUnifiedPlan()) {
2428 // TODO(steveanton): When removing RTP senders/receivers in response to a
2429 // rejected media section, there is some cleanup logic that expects the
2430 // voice/ video channel to still be set. But in this method the voice/video
2431 // channel would have been destroyed by the SetRemoteDescription caller
2432 // above so the cleanup that relies on them fails to run. The RemoveSenders
2433 // calls should be moved to right before the DestroyChannel calls to fix
2434 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002435
Steve Antondcc3c022017-12-22 16:02:54 -08002436 // Find all audio rtp streams and create corresponding remote AudioTracks
2437 // and MediaStreams.
2438 if (audio_content) {
2439 if (audio_content->rejected) {
2440 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2441 } else {
2442 bool default_audio_track_needed =
2443 !remote_peer_supports_msid_ &&
2444 RtpTransceiverDirectionHasSend(audio_desc->direction());
2445 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2446 default_audio_track_needed, audio_desc->type(),
2447 new_streams);
2448 }
deadbeeffaac4972015-11-12 15:33:07 -08002449 }
deadbeefab9b2d12015-10-14 11:33:11 -07002450
Steve Antondcc3c022017-12-22 16:02:54 -08002451 // Find all video rtp streams and create corresponding remote VideoTracks
2452 // and MediaStreams.
2453 if (video_content) {
2454 if (video_content->rejected) {
2455 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2456 } else {
2457 bool default_video_track_needed =
2458 !remote_peer_supports_msid_ &&
2459 RtpTransceiverDirectionHasSend(video_desc->direction());
2460 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2461 default_video_track_needed, video_desc->type(),
2462 new_streams);
2463 }
deadbeeffaac4972015-11-12 15:33:07 -08002464 }
deadbeefab9b2d12015-10-14 11:33:11 -07002465
Steve Antondcc3c022017-12-22 16:02:54 -08002466 // Update the DataChannels with the information from the remote peer.
2467 if (data_desc) {
2468 if (rtc::starts_with(data_desc->protocol().data(),
2469 cricket::kMediaProtocolRtpPrefix)) {
2470 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2471 }
deadbeefab9b2d12015-10-14 11:33:11 -07002472 }
deadbeefab9b2d12015-10-14 11:33:11 -07002473
Steve Antondcc3c022017-12-22 16:02:54 -08002474 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002475 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002476 for (size_t i = 0; i < new_streams->count(); ++i) {
2477 MediaStreamInterface* new_stream = new_streams->at(i);
2478 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002479 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002480 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2481 }
deadbeefab9b2d12015-10-14 11:33:11 -07002482
Steve Antondcc3c022017-12-22 16:02:54 -08002483 UpdateEndedRemoteMediaStreams();
2484 }
deadbeefab9b2d12015-10-14 11:33:11 -07002485
Steve Anton8a006912017-12-04 15:25:56 -08002486 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002487}
2488
Steve Anton0f5400a2018-07-17 14:25:36 -07002489void PeerConnection::ProcessRemovalOfRemoteTrack(
2490 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2491 transceiver,
2492 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2493 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2494 RTC_DCHECK(transceiver->mid());
2495 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2496 << *transceiver->mid();
2497 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2498 transceiver->internal()->receiver_internal()->streams();
2499 // This will remove the remote track from the streams.
2500 transceiver->internal()->receiver_internal()->set_stream_ids({});
2501 remove_list->push_back(transceiver);
2502 // Remove any streams that no longer have tracks.
2503 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2504 // of streams, see if the stream was removed by checking if this was the
2505 // last receiver with that stream ID.
2506 for (auto stream : media_streams) {
2507 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2508 remote_streams_->RemoveStream(stream);
2509 removed_streams->push_back(stream);
2510 }
2511 }
2512}
2513
Steve Antondcc3c022017-12-22 16:02:54 -08002514RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2515 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002516 const SessionDescriptionInterface& new_session,
2517 const SessionDescriptionInterface* old_local_description,
2518 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002519 RTC_DCHECK(IsUnifiedPlan());
2520
Steve Anton7464fca2018-01-19 11:10:37 -08002521 const cricket::ContentGroup* bundle_group = nullptr;
2522 if (new_session.GetType() == SdpType::kOffer) {
2523 auto bundle_group_or_error =
2524 GetEarlyBundleGroup(*new_session.description());
2525 if (!bundle_group_or_error.ok()) {
2526 return bundle_group_or_error.MoveError();
2527 }
2528 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002529 }
Steve Antondcc3c022017-12-22 16:02:54 -08002530
Steve Antondcc3c022017-12-22 16:02:54 -08002531 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002532 for (size_t i = 0; i < new_contents.size(); ++i) {
2533 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002534 cricket::MediaType media_type = new_content.media_description()->type();
2535 seen_mids_.insert(new_content.name);
2536 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2537 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002538 const cricket::ContentInfo* old_local_content = nullptr;
2539 if (old_local_description &&
2540 i < old_local_description->description()->contents().size()) {
2541 old_local_content =
2542 &old_local_description->description()->contents()[i];
2543 }
2544 const cricket::ContentInfo* old_remote_content = nullptr;
2545 if (old_remote_description &&
2546 i < old_remote_description->description()->contents().size()) {
2547 old_remote_content =
2548 &old_remote_description->description()->contents()[i];
2549 }
Steve Antondcc3c022017-12-22 16:02:54 -08002550 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002551 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2552 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002553 if (!transceiver_or_error.ok()) {
2554 return transceiver_or_error.MoveError();
2555 }
2556 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002557 RTCError error =
2558 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2559 if (!error.ok()) {
2560 return error;
2561 }
2562 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002563 if (GetDataMid() && new_content.name != *GetDataMid()) {
2564 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002565 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2566 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002567 continue;
2568 }
2569 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2570 if (!error.ok()) {
2571 return error;
2572 }
Steve Antondcc3c022017-12-22 16:02:54 -08002573 } else {
2574 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2575 "Unknown section type.");
2576 }
2577 }
2578
2579 return RTCError::OK();
2580}
2581
2582RTCError PeerConnection::UpdateTransceiverChannel(
2583 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2584 transceiver,
2585 const cricket::ContentInfo& content,
2586 const cricket::ContentGroup* bundle_group) {
2587 RTC_DCHECK(IsUnifiedPlan());
2588 RTC_DCHECK(transceiver);
2589 cricket::BaseChannel* channel = transceiver->internal()->channel();
2590 if (content.rejected) {
2591 if (channel) {
2592 transceiver->internal()->SetChannel(nullptr);
2593 DestroyBaseChannel(channel);
2594 }
2595 } else {
2596 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002597 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002598 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002599 } else {
Steve Anton69470252018-02-09 11:43:08 -08002600 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002601 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002602 }
2603 if (!channel) {
2604 LOG_AND_RETURN_ERROR(
2605 RTCErrorType::INTERNAL_ERROR,
2606 "Failed to create channel for mid=" + content.name);
2607 }
2608 transceiver->internal()->SetChannel(channel);
2609 }
2610 }
2611 return RTCError::OK();
2612}
2613
Steve Antonfa2260d2017-12-28 16:38:23 -08002614RTCError PeerConnection::UpdateDataChannel(
2615 cricket::ContentSource source,
2616 const cricket::ContentInfo& content,
2617 const cricket::ContentGroup* bundle_group) {
2618 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002619 // If data channels are disabled, ignore this media section. CreateAnswer
2620 // will take care of rejecting it.
2621 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002622 }
2623 if (content.rejected) {
2624 DestroyDataChannel();
2625 } else {
2626 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002627 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002628 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2629 "Failed to create data channel.");
2630 }
2631 }
2632 if (source == cricket::CS_REMOTE) {
2633 const MediaContentDescription* data_desc = content.media_description();
2634 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2635 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2636 }
2637 }
2638 }
2639 return RTCError::OK();
2640}
2641
Steve Antondcc3c022017-12-22 16:02:54 -08002642RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2643PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002644 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002645 size_t mline_index,
2646 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002647 const ContentInfo* old_local_content,
2648 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002649 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002650 // If this is an offer then the m= section might be recycled. If the m=
2651 // section is being recycled (defined as: rejected in the current local or
2652 // remote description and not rejected in new description), dissociate the
2653 // currently associated RtpTransceiver by setting its mid property to null,
2654 // and discard the mapping between the transceiver and its m= section index.
2655 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2656 old_remote_content)) {
2657 // We want to dissociate the transceiver that has the rejected mid.
2658 const std::string& old_mid =
2659 (old_local_content && old_local_content->rejected)
2660 ? old_local_content->name
2661 : old_remote_content->name;
2662 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002663 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002664 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2665 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002666 old_transceiver->internal()->set_mid(absl::nullopt);
2667 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002668 }
2669 }
2670 const MediaContentDescription* media_desc = content.media_description();
2671 auto transceiver = GetAssociatedTransceiver(content.name);
2672 if (source == cricket::CS_LOCAL) {
2673 // Find the RtpTransceiver that corresponds to this m= section, using the
2674 // mapping between transceivers and m= section indices established when
2675 // creating the offer.
2676 if (!transceiver) {
2677 transceiver = GetTransceiverByMLineIndex(mline_index);
2678 }
2679 if (!transceiver) {
2680 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2681 "Unknown transceiver");
2682 }
2683 } else {
2684 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2685 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2686 // of the same type...
2687 if (!transceiver &&
2688 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2689 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2690 }
2691 // If no RtpTransceiver was found in the previous step, create one with a
2692 // recvonly direction.
2693 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002694 RTC_LOG(LS_INFO) << "Adding "
2695 << cricket::MediaTypeToString(media_desc->type())
2696 << " transceiver for MID=" << content.name
2697 << " at i=" << mline_index
2698 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002699 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002700 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002701 std::string receiver_id;
2702 if (!media_desc->streams().empty()) {
2703 receiver_id = media_desc->streams()[0].id;
2704 } else {
2705 receiver_id = rtc::CreateRandomUuid();
2706 }
2707 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002708 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002709 transceiver->internal()->set_direction(
2710 RtpTransceiverDirection::kRecvOnly);
2711 }
2712 }
2713 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002714 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002715 LOG_AND_RETURN_ERROR(
2716 RTCErrorType::INVALID_PARAMETER,
2717 "Transceiver type does not match media description type.");
2718 }
2719 // Associate the found or created RtpTransceiver with the m= section by
2720 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2721 // section, and establish a mapping between the transceiver and the index of
2722 // the m= section.
2723 transceiver->internal()->set_mid(content.name);
2724 transceiver->internal()->set_mline_index(mline_index);
2725 return std::move(transceiver);
2726}
2727
2728rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2729PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2730 RTC_DCHECK(IsUnifiedPlan());
2731 for (auto transceiver : transceivers_) {
2732 if (transceiver->mid() == mid) {
2733 return transceiver;
2734 }
2735 }
2736 return nullptr;
2737}
2738
2739rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2740PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2741 RTC_DCHECK(IsUnifiedPlan());
2742 for (auto transceiver : transceivers_) {
2743 if (transceiver->internal()->mline_index() == mline_index) {
2744 return transceiver;
2745 }
2746 }
2747 return nullptr;
2748}
2749
2750rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2751PeerConnection::FindAvailableTransceiverToReceive(
2752 cricket::MediaType media_type) const {
2753 RTC_DCHECK(IsUnifiedPlan());
2754 // From JSEP section 5.10 (Applying a Remote Description):
2755 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2756 // the same type that were added to the PeerConnection by addTrack and are not
2757 // associated with any m= section and are not stopped, find the first such
2758 // RtpTransceiver.
2759 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002760 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002761 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2762 !transceiver->stopped()) {
2763 return transceiver;
2764 }
2765 }
2766 return nullptr;
2767}
2768
Steve Antoned10bd92017-12-05 10:52:59 -08002769const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2770 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2771 transceiver,
2772 const SessionDescriptionInterface* sdesc) const {
2773 RTC_DCHECK(transceiver);
2774 RTC_DCHECK(sdesc);
2775 if (IsUnifiedPlan()) {
2776 if (!transceiver->internal()->mid()) {
2777 // This transceiver is not associated with a media section yet.
2778 return nullptr;
2779 }
2780 return sdesc->description()->GetContentByName(
2781 *transceiver->internal()->mid());
2782 } else {
2783 // Plan B only allows at most one audio and one video section, so use the
2784 // first media section of that type.
2785 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002786 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002787 }
2788}
2789
deadbeef46c73892016-11-16 19:42:04 -08002790PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2791 return configuration_;
2792}
2793
deadbeef293e9262017-01-11 12:28:30 -08002794bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2795 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002796 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002797 if (IsClosed()) {
2798 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2799 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2800 }
2801
Qingsi Wanga2d60672018-04-11 16:57:45 -07002802 // According to JSEP, after setLocalDescription, changing the candidate pool
2803 // size is not allowed, and changing the set of ICE servers will not result
2804 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002805 if (local_description() && configuration.ice_candidate_pool_size !=
2806 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002807 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2808 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002809 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002810 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002811
deadbeef293e9262017-01-11 12:28:30 -08002812 // The simplest (and most future-compatible) way to tell if the config was
2813 // modified in an invalid way is to copy each property we do support
2814 // modifying, then use operator==. There are far more properties we don't
2815 // support modifying than those we do, and more could be added.
2816 RTCConfiguration modified_config = configuration_;
2817 modified_config.servers = configuration.servers;
2818 modified_config.type = configuration.type;
2819 modified_config.ice_candidate_pool_size =
2820 configuration.ice_candidate_pool_size;
2821 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002822 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002823 modified_config.ice_check_interval_strong_connectivity =
2824 configuration.ice_check_interval_strong_connectivity;
2825 modified_config.ice_check_interval_weak_connectivity =
2826 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002827 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2828 modified_config.ice_unwritable_min_checks =
2829 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002830 modified_config.stun_candidate_keepalive_interval =
2831 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002832 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002833 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002834 modified_config.active_reset_srtp_params =
2835 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002836 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002837 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002838 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2839 }
2840
Steve Anton038834f2017-07-14 15:59:59 -07002841 // Validate the modified configuration.
2842 RTCError validate_error = ValidateConfiguration(modified_config);
2843 if (!validate_error.ok()) {
2844 return SafeSetError(std::move(validate_error), error);
2845 }
2846
deadbeef293e9262017-01-11 12:28:30 -08002847 // Note that this isn't possible through chromium, since it's an unsigned
2848 // short in WebIDL.
2849 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002850 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002851 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2852 }
2853
2854 // Parse ICE servers before hopping to network thread.
2855 cricket::ServerAddresses stun_servers;
2856 std::vector<cricket::RelayServerConfig> turn_servers;
2857 RTCErrorType parse_error =
2858 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2859 if (parse_error != RTCErrorType::NONE) {
2860 return SafeSetError(parse_error, error);
2861 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002862 // Note if STUN or TURN servers were supplied.
2863 if (!stun_servers.empty()) {
2864 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2865 }
2866 if (!turn_servers.empty()) {
2867 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2868 }
deadbeef293e9262017-01-11 12:28:30 -08002869
2870 // In theory this shouldn't fail.
2871 if (!network_thread()->Invoke<bool>(
2872 RTC_FROM_HERE,
2873 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2874 stun_servers, turn_servers, modified_config.type,
2875 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002876 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002877 modified_config.turn_customizer,
2878 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002879 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002880 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2881 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002882
deadbeefd1a38b52016-12-10 13:15:33 -08002883 // As described in JSEP, calling setConfiguration with new ICE servers or
2884 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2885 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002886 if (modified_config.servers != configuration_.servers ||
2887 modified_config.type != configuration_.type ||
2888 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002889 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002890 }
skvladd1f5fda2017-02-03 16:54:05 -08002891
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002892 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002893
Zhi Huangb57e1692018-06-12 11:41:11 -07002894 if (configuration_.active_reset_srtp_params !=
2895 modified_config.active_reset_srtp_params) {
2896 transport_controller_->SetActiveResetSrtpParams(
2897 modified_config.active_reset_srtp_params);
2898 }
2899
deadbeef293e9262017-01-11 12:28:30 -08002900 configuration_ = modified_config;
2901 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002902}
2903
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002904bool PeerConnection::AddIceCandidate(
2905 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002906 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002907 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002908 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002909 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07002910 return false;
2911 }
Steve Antond25da372017-11-06 14:50:29 -08002912
2913 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002914 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002915 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002916 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002917 return false;
2918 }
2919
2920 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002921 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002922 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08002923 return false;
2924 }
2925
2926 bool valid = false;
2927 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2928 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002929 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08002930 return false;
2931 }
2932
2933 // Add this candidate to the remote session description.
2934 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002935 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002936 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08002937 return false;
2938 }
2939
2940 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002941 bool result = UseCandidate(ice_candidate);
2942 if (result) {
2943 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
2944 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
2945 } else {
2946 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
2947 }
2948 return result;
Steve Antond25da372017-11-06 14:50:29 -08002949 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002950 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002951 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08002952 return true;
2953 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002954}
2955
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002956bool PeerConnection::RemoveIceCandidates(
2957 const std::vector<cricket::Candidate>& candidates) {
2958 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002959 if (IsClosed()) {
2960 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2961 return false;
2962 }
2963
Steve Antond25da372017-11-06 14:50:29 -08002964 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002965 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2966 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002967 return false;
2968 }
2969
2970 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002971 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002972 return false;
2973 }
2974
2975 size_t number_removed =
2976 mutable_remote_description()->RemoveCandidates(candidates);
2977 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002978 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07002979 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002980 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002981 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002982 }
2983
2984 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07002985 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
2986 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002987 RTC_LOG(LS_ERROR)
2988 << "RemoveIceCandidates: Error when removing remote candidates: "
2989 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08002990 }
2991 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002992}
2993
Niels Möller0c4f7be2018-05-07 14:01:37 +02002994RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002995 if (!worker_thread()->IsCurrent()) {
2996 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02002997 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07002998 }
2999
Niels Möller0c4f7be2018-05-07 14:01:37 +02003000 const bool has_min = bitrate.min_bitrate_bps.has_value();
3001 const bool has_start = bitrate.start_bitrate_bps.has_value();
3002 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003003 if (has_min && *bitrate.min_bitrate_bps < 0) {
3004 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3005 "min_bitrate_bps <= 0");
3006 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003007 if (has_start) {
3008 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003009 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003010 "start_bitrate_bps < min_bitrate_bps");
3011 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003012 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3013 "curent_bitrate_bps < 0");
3014 }
3015 }
3016 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003017 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003018 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003019 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003020 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3021 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3022 "max_bitrate_bps < min_bitrate_bps");
3023 } else if (*bitrate.max_bitrate_bps < 0) {
3024 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3025 "max_bitrate_bps < 0");
3026 }
3027 }
3028
zstein4b979802017-06-02 14:37:37 -07003029 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003030 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003031
3032 return RTCError::OK();
3033}
3034
Alex Narest78609d52017-10-20 10:37:47 +02003035void PeerConnection::SetBitrateAllocationStrategy(
3036 std::unique_ptr<rtc::BitrateAllocationStrategy>
3037 bitrate_allocation_strategy) {
3038 rtc::Thread* worker_thread = factory_->worker_thread();
3039 if (!worker_thread->IsCurrent()) {
3040 rtc::BitrateAllocationStrategy* strategy_raw =
3041 bitrate_allocation_strategy.release();
3042 auto functor = [this, strategy_raw]() {
3043 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003044 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003045 };
3046 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3047 return;
3048 }
3049 RTC_DCHECK(call_.get());
3050 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3051}
3052
henrika5f6bf242017-11-01 11:06:56 +01003053void PeerConnection::SetAudioPlayout(bool playout) {
3054 if (!worker_thread()->IsCurrent()) {
3055 worker_thread()->Invoke<void>(
3056 RTC_FROM_HERE,
3057 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3058 return;
3059 }
3060 auto audio_state =
3061 factory_->channel_manager()->media_engine()->GetAudioState();
3062 audio_state->SetPlayout(playout);
3063}
3064
3065void PeerConnection::SetAudioRecording(bool recording) {
3066 if (!worker_thread()->IsCurrent()) {
3067 worker_thread()->Invoke<void>(
3068 RTC_FROM_HERE,
3069 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3070 return;
3071 }
3072 auto audio_state =
3073 factory_->channel_manager()->media_engine()->GetAudioState();
3074 audio_state->SetRecording(recording);
3075}
3076
Steve Anton8c0f7a72017-10-03 10:03:10 -07003077std::unique_ptr<rtc::SSLCertificate>
3078PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003079 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3080 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003081 return nullptr;
3082 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003083 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003084}
3085
Zhi Huang70b820f2018-01-27 14:16:15 -08003086std::unique_ptr<rtc::SSLCertChain>
3087PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003088 auto audio_transceiver = GetFirstAudioTransceiver();
3089 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003090 return nullptr;
3091 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003092 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003093 audio_transceiver->internal()->channel()->transport_name());
3094}
3095
3096rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3097PeerConnection::GetFirstAudioTransceiver() const {
3098 for (auto transceiver : transceivers_) {
3099 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3100 return transceiver;
3101 }
3102 }
3103 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003104}
3105
ivoc14d5dbe2016-07-04 07:06:55 -07003106bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3107 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003108 // TODO(eladalon): It would be better to not allow negative values into PC.
3109 const size_t max_size = (max_size_bytes < 0)
3110 ? RtcEventLog::kUnlimitedOutput
3111 : rtc::saturated_cast<size_t>(max_size_bytes);
3112 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003113 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003114 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003115}
3116
Bjorn Tereliusde939432017-11-20 17:38:14 +01003117bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3118 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003119 // TODO(eladalon): In C++14, this can be done with a lambda.
3120 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003121 bool operator()() {
3122 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3123 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003124 PeerConnection* const pc;
3125 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003126 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003127 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003128 return worker_thread()->Invoke<bool>(
3129 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003130}
3131
3132void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003133 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003134 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3135}
3136
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003137const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003138 return pending_local_description_ ? pending_local_description_.get()
3139 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003140}
3141
3142const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003143 return pending_remote_description_ ? pending_remote_description_.get()
3144 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145}
3146
deadbeeffe4a8a42016-12-20 17:56:17 -08003147const SessionDescriptionInterface* PeerConnection::current_local_description()
3148 const {
Steve Anton75737c02017-11-06 10:37:17 -08003149 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003150}
3151
3152const SessionDescriptionInterface* PeerConnection::current_remote_description()
3153 const {
Steve Anton75737c02017-11-06 10:37:17 -08003154 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003155}
3156
3157const SessionDescriptionInterface* PeerConnection::pending_local_description()
3158 const {
Steve Anton75737c02017-11-06 10:37:17 -08003159 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003160}
3161
3162const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3163 const {
Steve Anton75737c02017-11-06 10:37:17 -08003164 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003165}
3166
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003167void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003168 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003169 // Update stats here so that we have the most recent stats for tracks and
3170 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003171 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003172
Steve Anton75737c02017-11-06 10:37:17 -08003173 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003174 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003175
Steve Anton8af21862017-12-15 11:20:13 -08003176 for (auto transceiver : transceivers_) {
3177 transceiver->Stop();
3178 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003179
3180 // Ensure that all asynchronous stats requests are completed before destroying
3181 // the transport controller below.
3182 if (stats_collector_) {
3183 stats_collector_->WaitForPendingRequest();
3184 }
3185
3186 // Don't destroy BaseChannels until after stats has been cleaned up so that
3187 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003188 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003189
Qingsi Wang93a84392018-01-30 17:13:09 -08003190 // The event log is used in the transport controller, which must be outlived
3191 // by the former. CreateOffer by the peer connection is implemented
3192 // asynchronously and if the peer connection is closed without resetting the
3193 // WebRTC session description factory, the session description factory would
3194 // call the transport controller.
3195 webrtc_session_desc_factory_.reset();
3196 transport_controller_.reset();
3197
deadbeef42a42632017-03-10 15:18:00 -08003198 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003199 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3200 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003201
Steve Anton978b8762017-09-29 12:15:02 -07003202 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003203 call_.reset();
3204 // The event log must outlive call (and any other object that uses it).
3205 event_log_.reset();
3206 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003207 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003208 // The .h file says that observer can be discarded after close() returns.
3209 // Make sure this is true.
3210 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211}
3212
Steve Antonafb0bb72018-02-20 11:35:37 -08003213cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3214 RTC_DCHECK(!IsUnifiedPlan());
3215 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3216 GetAudioTransceiver()->internal()->channel());
3217 if (voice_channel) {
3218 return voice_channel->media_channel();
3219 } else {
3220 return nullptr;
3221 }
3222}
3223
3224cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3225 RTC_DCHECK(!IsUnifiedPlan());
3226 auto* video_channel = static_cast<cricket::VideoChannel*>(
3227 GetVideoTransceiver()->internal()->channel());
3228 if (video_channel) {
3229 return video_channel->media_channel();
3230 } else {
3231 return nullptr;
3232 }
3233}
3234
Steve Anton4171afb2017-11-20 10:20:22 -08003235void PeerConnection::CreateAudioReceiver(
3236 MediaStreamInterface* stream,
3237 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003238 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3239 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003240 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3241 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003242 auto* audio_receiver = new AudioRtpReceiver(
3243 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003244 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003245 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3246 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3247 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003248 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003249 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003250 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251}
3252
Steve Anton4171afb2017-11-20 10:20:22 -08003253void PeerConnection::CreateVideoReceiver(
3254 MediaStreamInterface* stream,
3255 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003256 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3257 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003258 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3259 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003260 auto* video_receiver = new VideoRtpReceiver(
3261 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003262 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003263 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3264 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3265 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003266 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003267 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003268 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269}
3270
deadbeef70ab1a12015-09-28 16:53:55 -07003271// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3272// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003273rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003274 const RtpSenderInfo& remote_sender_info) {
3275 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3276 if (!receiver) {
3277 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3278 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003279 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003280 }
Steve Anton4171afb2017-11-20 10:20:22 -08003281 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3282 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3283 } else {
3284 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3285 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003286 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003287}
3288
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003289void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3290 MediaStreamInterface* stream) {
3291 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003292 RTC_DCHECK(track);
3293 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003294 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003295 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003296 // We already have a sender for this track, so just change the stream_id
3297 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003298 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003299 return;
3300 }
3301
3302 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003303 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3304 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003305 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003306 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003307 // If the sender has already been configured in SDP, we call SetSsrc,
3308 // which will connect the sender to the underlying transport. This can
3309 // occur if a local session description that contains the ID of the sender
3310 // is set before AddStream is called. It can also occur if the local
3311 // session description is not changed and RemoveStream is called, and
3312 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003313 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003314 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003315 if (sender_info) {
3316 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003317 }
3318}
3319
3320// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3321// indefinitely, when we have unified plan SDP.
3322void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3323 MediaStreamInterface* stream) {
3324 RTC_DCHECK(!IsClosed());
3325 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003326 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003327 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3328 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003329 return;
3330 }
Steve Anton4171afb2017-11-20 10:20:22 -08003331 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003332}
3333
3334void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3335 MediaStreamInterface* stream) {
3336 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003337 RTC_DCHECK(track);
3338 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003339 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003340 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003341 // We already have a sender for this track, so just change the stream_id
3342 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003343 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003344 return;
3345 }
3346
3347 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003348 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3349 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003350 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003351 GetVideoTransceiver()->internal()->AddSender(new_sender);
3352 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003353 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003354 if (sender_info) {
3355 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003356 }
3357}
3358
3359void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3360 MediaStreamInterface* stream) {
3361 RTC_DCHECK(!IsClosed());
3362 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003363 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003364 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3365 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003366 return;
3367 }
Steve Anton4171afb2017-11-20 10:20:22 -08003368 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003369}
3370
Steve Antonba818672017-11-06 10:21:57 -08003371void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003372 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003373 if (ice_connection_state_ == new_state) {
3374 return;
3375 }
3376
deadbeefcbecd352015-09-23 11:50:27 -07003377 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003378 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003379 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003380 return;
3381 }
Steve Antonba818672017-11-06 10:21:57 -08003382
Mirko Bonadei675513b2017-11-09 11:09:25 +01003383 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3384 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003385 RTC_DCHECK(ice_connection_state_ !=
3386 PeerConnectionInterface::kIceConnectionClosed);
3387
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003388 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003389 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390}
3391
3392void PeerConnection::OnIceGatheringChange(
3393 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003394 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003395 if (IsClosed()) {
3396 return;
3397 }
3398 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003399 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003400}
3401
jbauch81bf7b02017-03-25 08:31:12 -07003402void PeerConnection::OnIceCandidate(
3403 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003404 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003405 if (IsClosed()) {
3406 return;
3407 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003408 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003409 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3410 candidate->candidate().address().IsPrivateIP()) {
3411 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3412 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003413 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003414}
3415
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003416void PeerConnection::OnIceCandidatesRemoved(
3417 const std::vector<cricket::Candidate>& candidates) {
3418 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003419 if (IsClosed()) {
3420 return;
3421 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003422 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003423}
3424
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003425void PeerConnection::ChangeSignalingState(
3426 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003427 RTC_DCHECK(signaling_thread()->IsCurrent());
3428 if (signaling_state_ == signaling_state) {
3429 return;
3430 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003431 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3432 << GetSignalingStateString(signaling_state_)
3433 << " New state: "
3434 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435 signaling_state_ = signaling_state;
3436 if (signaling_state == kClosed) {
3437 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003438 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003439 if (ice_gathering_state_ != kIceGatheringComplete) {
3440 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003441 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003442 }
3443 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003444 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003445}
3446
deadbeefeb459812015-12-15 19:24:43 -08003447void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3448 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003449 if (IsClosed()) {
3450 return;
3451 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003452 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003453 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003454}
3455
deadbeefeb459812015-12-15 19:24:43 -08003456void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3457 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003458 if (IsClosed()) {
3459 return;
3460 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003461 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003462 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003463}
3464
3465void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3466 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003467 if (IsClosed()) {
3468 return;
3469 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003470 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003471 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003472}
3473
3474void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3475 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003476 if (IsClosed()) {
3477 return;
3478 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003479 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003480 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003481}
3482
Henrik Boström31638672017-11-23 17:48:32 +01003483void PeerConnection::PostSetSessionDescriptionSuccess(
3484 SetSessionDescriptionObserver* observer) {
Steve Antonbb192762018-08-31 11:57:02 -07003485 async_invoker_.AsyncInvoke<void>(
3486 RTC_FROM_HERE, signaling_thread(),
3487 rtc::Bind(&SetSessionDescriptionObserver::OnSuccess, observer));
Henrik Boström31638672017-11-23 17:48:32 +01003488}
3489
deadbeefab9b2d12015-10-14 11:33:11 -07003490void PeerConnection::PostSetSessionDescriptionFailure(
3491 SetSessionDescriptionObserver* observer,
Steve Antonbb192762018-08-31 11:57:02 -07003492 RTCError error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003493 RTC_DCHECK(!error.ok());
Steve Antonbb192762018-08-31 11:57:02 -07003494 // TODO(steveanton): In C++14 this can be done with a lambda.
3495 struct Functor {
3496 void operator()() { observer->OnFailure(std::move(error)); }
3497 rtc::scoped_refptr<SetSessionDescriptionObserver> observer;
3498 RTCError error;
3499 };
3500 async_invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(),
3501 Functor{observer, std::move(error)});
deadbeefab9b2d12015-10-14 11:33:11 -07003502}
3503
3504void PeerConnection::PostCreateSessionDescriptionFailure(
3505 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003506 RTCError error) {
3507 RTC_DCHECK(!error.ok());
Steve Antonbb192762018-08-31 11:57:02 -07003508 // TODO(steveanton): In C++14 this can be done with a lambda.
3509 struct Functor {
3510 void operator()() { observer->OnFailure(std::move(error)); }
3511 rtc::scoped_refptr<CreateSessionDescriptionObserver> observer;
3512 RTCError error;
3513 };
3514 async_invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(),
3515 Functor{observer, std::move(error)});
deadbeefab9b2d12015-10-14 11:33:11 -07003516}
3517
zhihuang1c378ed2017-08-17 14:10:50 -07003518void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003519 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003520 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003521 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003522
Steve Antondcc3c022017-12-22 16:02:54 -08003523 if (IsUnifiedPlan()) {
3524 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3525 } else {
3526 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3527 }
3528
Steve Antonfa2260d2017-12-28 16:38:23 -08003529 // Intentionally unset the data channel type for RTP data channel with the
3530 // second condition. Otherwise the RTP data channels would be successfully
3531 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3532 // when building with chromium. We want to leave RTP data channels broken, so
3533 // people won't try to use them.
3534 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3535 session_options->data_channel_type = data_channel_type();
3536 }
3537
Steve Antondcc3c022017-12-22 16:02:54 -08003538 // Apply ICE restart flag and renomination flag.
3539 for (auto& options : session_options->media_description_options) {
3540 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3541 options.transport_options.enable_ice_renomination =
3542 configuration_.enable_ice_renomination;
3543 }
3544
3545 session_options->rtcp_cname = rtcp_cname_;
3546 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003547 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003548}
3549
3550void PeerConnection::GetOptionsForPlanBOffer(
3551 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3552 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003553 // Figure out transceiver directional preferences.
3554 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3555 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3556
3557 // By default, generate sendrecv/recvonly m= sections.
3558 bool recv_audio = true;
3559 bool recv_video = true;
3560
3561 // By default, only offer a new m= section if we have media to send with it.
3562 bool offer_new_audio_description = send_audio;
3563 bool offer_new_video_description = send_video;
3564 bool offer_new_data_description = HasDataChannels();
3565
3566 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003567 if (offer_answer_options.offer_to_receive_audio !=
3568 RTCOfferAnswerOptions::kUndefined) {
3569 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003570 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003571 offer_new_audio_description ||
3572 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003573 }
Steve Antondcc3c022017-12-22 16:02:54 -08003574 if (offer_answer_options.offer_to_receive_video !=
3575 RTCOfferAnswerOptions::kUndefined) {
3576 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003577 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003578 offer_new_video_description ||
3579 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003580 }
3581
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003582 absl::optional<size_t> audio_index;
3583 absl::optional<size_t> video_index;
3584 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003585 // If a current description exists, generate m= sections in the same order,
3586 // using the first audio/video/data section that appears and rejecting
3587 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003588 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003589 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003590 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003591 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3592 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3593 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003594 }
3595
zhihuang1c378ed2017-08-17 14:10:50 -07003596 // Add audio/video/data m= sections to the end if needed.
3597 if (!audio_index && offer_new_audio_description) {
3598 session_options->media_description_options.push_back(
3599 cricket::MediaDescriptionOptions(
3600 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003601 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3602 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003603 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003604 }
zhihuang1c378ed2017-08-17 14:10:50 -07003605 if (!video_index && offer_new_video_description) {
3606 session_options->media_description_options.push_back(
3607 cricket::MediaDescriptionOptions(
3608 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003609 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3610 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003611 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003612 }
zhihuang1c378ed2017-08-17 14:10:50 -07003613 if (!data_index && offer_new_data_description) {
3614 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003615 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003616 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003617 }
3618
3619 cricket::MediaDescriptionOptions* audio_media_description_options =
3620 !audio_index ? nullptr
3621 : &session_options->media_description_options[*audio_index];
3622 cricket::MediaDescriptionOptions* video_media_description_options =
3623 !video_index ? nullptr
3624 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003625
Steve Anton4171afb2017-11-20 10:20:22 -08003626 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003627 video_media_description_options,
3628 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003629}
3630
3631// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3632// and return a reference to it.
3633// Generated MIDs should be no more than 3 bytes long to take up less space in
3634// the RTP packet.
3635static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3636 RTC_DCHECK(used_mids);
3637 // We're boring: just generate MIDs 0, 1, 2, ...
3638 size_t i = 0;
3639 std::set<std::string>::iterator it;
3640 bool inserted;
3641 do {
3642 std::string mid = rtc::ToString(i++);
3643 auto insert_result = used_mids->insert(mid);
3644 it = insert_result.first;
3645 inserted = insert_result.second;
3646 } while (!inserted);
3647 return *it;
3648}
3649
3650static cricket::MediaDescriptionOptions
3651GetMediaDescriptionOptionsForTransceiver(
3652 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3653 transceiver,
3654 const std::string& mid) {
3655 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003656 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003657 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003658 // This behavior is specified in JSEP. The gist is that:
3659 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3660 // sendrecv.
3661 // 2. If the MSID is included, then it must be included in any subsequent
3662 // offer/answer exactly the same until the RtpTransceiver is stopped.
3663 if (!transceiver->stopped() &&
3664 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3665 transceiver->internal()->has_ever_been_used_to_send())) {
3666 cricket::SenderOptions sender_options;
3667 sender_options.track_id = transceiver->sender()->id();
3668 sender_options.stream_ids = transceiver->sender()->stream_ids();
3669 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3670 // set in the RTP parameters when the transceiver was added.
3671 sender_options.num_sim_layers = 1;
3672 media_description_options.sender_options.push_back(sender_options);
3673 }
Steve Antondcc3c022017-12-22 16:02:54 -08003674 return media_description_options;
3675}
3676
3677void PeerConnection::GetOptionsForUnifiedPlanOffer(
3678 const RTCOfferAnswerOptions& offer_answer_options,
3679 cricket::MediaSessionOptions* session_options) {
3680 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3681 // Offers) and 5.2.2 (Subsequent Offers).
3682 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3683 const ContentInfos& local_contents =
3684 (local_description() ? local_description()->description()->contents()
3685 : ContentInfos());
3686 const ContentInfos& remote_contents =
3687 (remote_description() ? remote_description()->description()->contents()
3688 : ContentInfos());
3689 // The mline indices that can be recycled. New transceivers should reuse these
3690 // slots first.
3691 std::queue<size_t> recycleable_mline_indices;
3692 // Track the MIDs used in previous offer/answer exchanges and the current
3693 // offer so that new, unique MIDs are generated.
3694 std::set<std::string> used_mids = seen_mids_;
3695 // First, go through each media section that exists in either the local or
3696 // remote description and generate a media section in this offer for the
3697 // associated transceiver. If a media section can be recycled, generate a
3698 // default, rejected media section here that can be later overwritten.
3699 for (size_t i = 0;
3700 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3701 // Either |local_content| or |remote_content| is non-null.
3702 const ContentInfo* local_content =
3703 (i < local_contents.size() ? &local_contents[i] : nullptr);
3704 const ContentInfo* remote_content =
3705 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3706 bool had_been_rejected = (local_content && local_content->rejected) ||
3707 (remote_content && remote_content->rejected);
3708 const std::string& mid =
3709 (local_content ? local_content->name : remote_content->name);
3710 cricket::MediaType media_type =
3711 (local_content ? local_content->media_description()->type()
3712 : remote_content->media_description()->type());
3713 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3714 media_type == cricket::MEDIA_TYPE_VIDEO) {
3715 auto transceiver = GetAssociatedTransceiver(mid);
3716 RTC_CHECK(transceiver);
3717 // A media section is considered eligible for recycling if it is marked as
3718 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003719 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003720 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003721 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3722 RtpTransceiverDirection::kInactive,
3723 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003724 recycleable_mline_indices.push(i);
3725 } else {
3726 session_options->media_description_options.push_back(
3727 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3728 // CreateOffer shouldn't really cause any state changes in
3729 // PeerConnection, but we need a way to match new transceivers to new
3730 // media sections in SetLocalDescription and JSEP specifies this is done
3731 // by recording the index of the media section generated for the
3732 // transceiver in the offer.
3733 transceiver->internal()->set_mline_index(i);
3734 }
3735 } else {
3736 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003737 RTC_CHECK(GetDataMid());
3738 if (had_been_rejected || mid != *GetDataMid()) {
3739 session_options->media_description_options.push_back(
3740 GetMediaDescriptionOptionsForRejectedData(mid));
3741 } else {
3742 session_options->media_description_options.push_back(
3743 GetMediaDescriptionOptionsForActiveData(mid));
3744 }
Steve Antondcc3c022017-12-22 16:02:54 -08003745 }
3746 }
3747 // Next, look for transceivers that are newly added (that is, are not stopped
3748 // and not associated). Reuse media sections marked as recyclable first,
3749 // otherwise append to the end of the offer. New media sections should be
3750 // added in the order they were added to the PeerConnection.
3751 for (auto transceiver : transceivers_) {
3752 if (transceiver->mid() || transceiver->stopped()) {
3753 continue;
3754 }
3755 size_t mline_index;
3756 if (!recycleable_mline_indices.empty()) {
3757 mline_index = recycleable_mline_indices.front();
3758 recycleable_mline_indices.pop();
3759 session_options->media_description_options[mline_index] =
3760 GetMediaDescriptionOptionsForTransceiver(transceiver,
3761 AllocateMid(&used_mids));
3762 } else {
3763 mline_index = session_options->media_description_options.size();
3764 session_options->media_description_options.push_back(
3765 GetMediaDescriptionOptionsForTransceiver(transceiver,
3766 AllocateMid(&used_mids)));
3767 }
3768 // See comment above for why CreateOffer changes the transceiver's state.
3769 transceiver->internal()->set_mline_index(mline_index);
3770 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003771 // Lastly, add a m-section if we have local data channels and an m section
3772 // does not already exist.
3773 if (!GetDataMid() && HasDataChannels()) {
3774 session_options->media_description_options.push_back(
3775 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3776 }
Steve Antondcc3c022017-12-22 16:02:54 -08003777}
3778
3779void PeerConnection::GetOptionsForAnswer(
3780 const RTCOfferAnswerOptions& offer_answer_options,
3781 cricket::MediaSessionOptions* session_options) {
3782 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3783
3784 if (IsUnifiedPlan()) {
3785 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3786 } else {
3787 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3788 }
3789
Steve Antonfa2260d2017-12-28 16:38:23 -08003790 // Intentionally unset the data channel type for RTP data channel. Otherwise
3791 // the RTP data channels would be successfully negotiated by default and the
3792 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3793 // We want to leave RTP data channels broken, so people won't try to use them.
3794 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3795 session_options->data_channel_type = data_channel_type();
3796 }
3797
Steve Antondcc3c022017-12-22 16:02:54 -08003798 // Apply ICE renomination flag.
3799 for (auto& options : session_options->media_description_options) {
3800 options.transport_options.enable_ice_renomination =
3801 configuration_.enable_ice_renomination;
3802 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003803
3804 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003805 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003806 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003807}
3808
Steve Antondcc3c022017-12-22 16:02:54 -08003809void PeerConnection::GetOptionsForPlanBAnswer(
3810 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003811 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003812 // Figure out transceiver directional preferences.
3813 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3814 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3815
3816 // By default, generate sendrecv/recvonly m= sections. The direction is also
3817 // restricted by the direction in the offer.
3818 bool recv_audio = true;
3819 bool recv_video = true;
3820
3821 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003822 if (offer_answer_options.offer_to_receive_audio !=
3823 RTCOfferAnswerOptions::kUndefined) {
3824 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003825 }
Steve Antondcc3c022017-12-22 16:02:54 -08003826 if (offer_answer_options.offer_to_receive_video !=
3827 RTCOfferAnswerOptions::kUndefined) {
3828 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003829 }
3830
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003831 absl::optional<size_t> audio_index;
3832 absl::optional<size_t> video_index;
3833 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003834
3835 // Generate m= sections that match those in the offer.
3836 // Note that mediasession.cc will handle intersection our preferred
3837 // direction with the offered direction.
3838 GenerateMediaDescriptionOptions(
3839 remote_description(),
3840 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3841 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3842 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003843
3844 cricket::MediaDescriptionOptions* audio_media_description_options =
3845 !audio_index ? nullptr
3846 : &session_options->media_description_options[*audio_index];
3847 cricket::MediaDescriptionOptions* video_media_description_options =
3848 !video_index ? nullptr
3849 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003850
Steve Anton4171afb2017-11-20 10:20:22 -08003851 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003852 video_media_description_options,
3853 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003854}
zhihuangaf388472016-11-02 16:49:48 -07003855
Steve Antondcc3c022017-12-22 16:02:54 -08003856void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3857 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3858 cricket::MediaSessionOptions* session_options) {
3859 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3860 // Answers) and 5.3.2 (Subsequent Answers).
3861 RTC_DCHECK(remote_description());
3862 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3863 for (const ContentInfo& content :
3864 remote_description()->description()->contents()) {
3865 cricket::MediaType media_type = content.media_description()->type();
3866 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3867 media_type == cricket::MEDIA_TYPE_VIDEO) {
3868 auto transceiver = GetAssociatedTransceiver(content.name);
3869 RTC_CHECK(transceiver);
3870 session_options->media_description_options.push_back(
3871 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3872 } else {
3873 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003874 // Reject all data sections if data channels are disabled.
3875 // Reject a data section if it has already been rejected.
3876 // Reject all data sections except for the first one.
3877 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3878 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003879 session_options->media_description_options.push_back(
3880 GetMediaDescriptionOptionsForRejectedData(content.name));
3881 } else {
3882 session_options->media_description_options.push_back(
3883 GetMediaDescriptionOptionsForActiveData(content.name));
3884 }
Steve Antondcc3c022017-12-22 16:02:54 -08003885 }
3886 }
htaa2a49d92016-03-04 02:51:39 -08003887}
3888
zhihuang1c378ed2017-08-17 14:10:50 -07003889void PeerConnection::GenerateMediaDescriptionOptions(
3890 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003891 RtpTransceiverDirection audio_direction,
3892 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003893 absl::optional<size_t>* audio_index,
3894 absl::optional<size_t>* video_index,
3895 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003896 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003897 for (const cricket::ContentInfo& content :
3898 session_desc->description()->contents()) {
3899 if (IsAudioContent(&content)) {
3900 // If we already have an audio m= section, reject this extra one.
3901 if (*audio_index) {
3902 session_options->media_description_options.push_back(
3903 cricket::MediaDescriptionOptions(
3904 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003905 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003906 } else {
3907 session_options->media_description_options.push_back(
3908 cricket::MediaDescriptionOptions(
3909 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003910 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003911 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003912 }
3913 } else if (IsVideoContent(&content)) {
3914 // If we already have an video m= section, reject this extra one.
3915 if (*video_index) {
3916 session_options->media_description_options.push_back(
3917 cricket::MediaDescriptionOptions(
3918 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003919 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003920 } else {
3921 session_options->media_description_options.push_back(
3922 cricket::MediaDescriptionOptions(
3923 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003924 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003925 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003926 }
3927 } else {
3928 RTC_DCHECK(IsDataContent(&content));
3929 // If we already have an data m= section, reject this extra one.
3930 if (*data_index) {
3931 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003932 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003933 } else {
3934 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003935 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003936 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003937 }
3938 }
htaa2a49d92016-03-04 02:51:39 -08003939 }
deadbeefab9b2d12015-10-14 11:33:11 -07003940}
3941
Steve Antonfa2260d2017-12-28 16:38:23 -08003942cricket::MediaDescriptionOptions
3943PeerConnection::GetMediaDescriptionOptionsForActiveData(
3944 const std::string& mid) const {
3945 // Direction for data sections is meaningless, but legacy endpoints might
3946 // expect sendrecv.
3947 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3948 RtpTransceiverDirection::kSendRecv,
3949 /*stopped=*/false);
3950 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3951 return options;
3952}
3953
3954cricket::MediaDescriptionOptions
3955PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3956 const std::string& mid) const {
3957 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3958 RtpTransceiverDirection::kInactive,
3959 /*stopped=*/true);
3960 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3961 return options;
3962}
3963
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003964absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08003965 switch (data_channel_type_) {
3966 case cricket::DCT_RTP:
3967 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003968 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08003969 }
3970 return rtp_data_channel_->content_name();
3971 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07003972 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08003973 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003974 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08003975 }
3976}
3977
Steve Anton4171afb2017-11-20 10:20:22 -08003978void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3979 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3980 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003981 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003982}
3983
Steve Anton4171afb2017-11-20 10:20:22 -08003984void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003985 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003986 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003987 cricket::MediaType media_type,
3988 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07003989 RTC_DCHECK(!IsUnifiedPlan());
3990
Steve Anton4171afb2017-11-20 10:20:22 -08003991 std::vector<RtpSenderInfo>* current_senders =
3992 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003993
Steve Anton4171afb2017-11-20 10:20:22 -08003994 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003995 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003996 for (auto sender_it = current_senders->begin();
3997 sender_it != current_senders->end();
3998 /* incremented manually */) {
3999 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004000 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004001 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004002 std::string params_stream_id;
4003 if (params) {
4004 params_stream_id =
4005 (!params->first_stream_id().empty() ? params->first_stream_id()
4006 : kDefaultStreamId);
4007 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004008 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004009 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004010 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004011 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004012 sender_exists) {
4013 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004014 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004015 OnRemoteSenderRemoved(info, media_type);
4016 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004017 }
4018 }
4019
Steve Anton4171afb2017-11-20 10:20:22 -08004020 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004021 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004022 if (!params.has_ssrcs()) {
4023 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4024 // sender, this means it is coming from a Unified Plan endpoint,so we just
4025 // create a default.
4026 default_sender_needed = true;
4027 break;
4028 }
4029
Seth Hampson845e8782018-03-02 11:34:10 -08004030 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004031 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004032 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4033 // not supported in Plan B, we just take the first here and create the
4034 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004035 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004036 (!params.first_stream_id().empty() ? params.first_stream_id()
4037 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004038 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004039 uint32_t ssrc = params.first_ssrc();
4040
4041 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004042 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004043 if (!stream) {
4044 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004045 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004046 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004047 remote_streams_->AddStream(stream);
4048 new_streams->AddStream(stream);
4049 }
4050
Steve Anton4171afb2017-11-20 10:20:22 -08004051 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004052 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004053 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004054 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004055 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004056 }
4057 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004058
Steve Anton4171afb2017-11-20 10:20:22 -08004059 // Add default sender if necessary.
4060 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004061 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004062 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004063 if (!default_stream) {
4064 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004065 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004066 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004067 remote_streams_->AddStream(default_stream);
4068 new_streams->AddStream(default_stream);
4069 }
Steve Anton4171afb2017-11-20 10:20:22 -08004070 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4071 ? kDefaultAudioSenderId
4072 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004073 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004074 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004075 if (!default_sender_info) {
4076 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004077 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004078 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004079 }
4080 }
deadbeefab9b2d12015-10-14 11:33:11 -07004081}
4082
Steve Anton4171afb2017-11-20 10:20:22 -08004083void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4084 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004085 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4086 << " receiver for track_id=" << sender_info.sender_id
4087 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004088
Steve Anton3d954a62018-04-02 11:27:23 -07004089 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004090 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004091 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004092 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004093 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004094 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004095 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004096 }
4097}
4098
Steve Anton4171afb2017-11-20 10:20:22 -08004099void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4100 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004101 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4102 << " receiver for track_id=" << sender_info.sender_id
4103 << " and stream_id=" << sender_info.stream_id;
4104
Seth Hampson845e8782018-03-02 11:34:10 -08004105 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004106
Henrik Boström933d8b02017-10-10 10:05:16 -07004107 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004108 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004109 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4110 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004111 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004112 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004113 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004114 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004115 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004116 }
4117 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004118 // Stopping or destroying a VideoRtpReceiver will end the
4119 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004120 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004121 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004122 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004123 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004124 // There's no guarantee the track is still available, e.g. the track may
4125 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004126 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004127 }
4128 } else {
nisseede5da42017-01-12 05:15:36 -08004129 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004130 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004131 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004132 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004133 }
deadbeefab9b2d12015-10-14 11:33:11 -07004134}
4135
4136void PeerConnection::UpdateEndedRemoteMediaStreams() {
4137 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4138 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4139 MediaStreamInterface* stream = remote_streams_->at(i);
4140 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4141 streams_to_remove.push_back(stream);
4142 }
4143 }
4144
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004145 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004146 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004147 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004148 }
4149}
4150
Steve Anton4171afb2017-11-20 10:20:22 -08004151void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004152 const std::vector<cricket::StreamParams>& streams,
4153 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004154 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004155
Seth Hampson845e8782018-03-02 11:34:10 -08004156 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004157 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004158 for (auto sender_it = current_senders->begin();
4159 sender_it != current_senders->end();
4160 /* incremented manually */) {
4161 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004162 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004163 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4164 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004165 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004166 OnLocalSenderRemoved(info, media_type);
4167 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004168 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004169 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004170 }
4171 }
4172
Steve Anton4171afb2017-11-20 10:20:22 -08004173 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004174 for (const cricket::StreamParams& params : streams) {
4175 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004176 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004177 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004178 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004179 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004180 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004181 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004182 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004183 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004184 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004185 }
4186 }
4187}
4188
Steve Anton4171afb2017-11-20 10:20:22 -08004189void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4190 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004191 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004192 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004193 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004194 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4195 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004196 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004197 return;
4198 }
4199
deadbeeffac06552015-11-25 11:26:01 -08004200 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004201 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004202 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004203 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004204 }
deadbeeffac06552015-11-25 11:26:01 -08004205
Seth Hampson5b4f0752018-04-02 16:31:36 -07004206 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004207 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004208}
4209
Steve Anton4171afb2017-11-20 10:20:22 -08004210void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4211 cricket::MediaType media_type) {
4212 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004213 if (!sender) {
4214 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004215 // SessionDescriptions has been renegotiated.
4216 return;
4217 }
deadbeeffac06552015-11-25 11:26:01 -08004218
4219 // A sender has been removed from the SessionDescription but it's still
4220 // associated with the PeerConnection. This only occurs if the SDP doesn't
4221 // match with the calls to CreateSender, AddStream and RemoveStream.
4222 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004223 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004224 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004225 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004226 }
deadbeeffac06552015-11-25 11:26:01 -08004227
Steve Anton4171afb2017-11-20 10:20:22 -08004228 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004229}
4230
4231void PeerConnection::UpdateLocalRtpDataChannels(
4232 const cricket::StreamParamsVec& streams) {
4233 std::vector<std::string> existing_channels;
4234
4235 // Find new and active data channels.
4236 for (const cricket::StreamParams& params : streams) {
4237 // |it->sync_label| is actually the data channel label. The reason is that
4238 // we use the same naming of data channels as we do for
4239 // MediaStreams and Tracks.
4240 // For MediaStreams, the sync_label is the MediaStream label and the
4241 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004242 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004243 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004244 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004245 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004246 continue;
4247 }
4248 // Set the SSRC the data channel should use for sending.
4249 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4250 existing_channels.push_back(data_channel_it->first);
4251 }
4252
4253 UpdateClosingRtpDataChannels(existing_channels, true);
4254}
4255
4256void PeerConnection::UpdateRemoteRtpDataChannels(
4257 const cricket::StreamParamsVec& streams) {
4258 std::vector<std::string> existing_channels;
4259
4260 // Find new and active data channels.
4261 for (const cricket::StreamParams& params : streams) {
4262 // The data channel label is either the mslabel or the SSRC if the mslabel
4263 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004264 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004265 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004266 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004267 auto data_channel_it = rtp_data_channels_.find(label);
4268 if (data_channel_it == rtp_data_channels_.end()) {
4269 // This is a new data channel.
4270 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4271 } else {
4272 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4273 }
4274 existing_channels.push_back(label);
4275 }
4276
4277 UpdateClosingRtpDataChannels(existing_channels, false);
4278}
4279
4280void PeerConnection::UpdateClosingRtpDataChannels(
4281 const std::vector<std::string>& active_channels,
4282 bool is_local_update) {
4283 auto it = rtp_data_channels_.begin();
4284 while (it != rtp_data_channels_.end()) {
4285 DataChannel* data_channel = it->second;
4286 if (std::find(active_channels.begin(), active_channels.end(),
4287 data_channel->label()) != active_channels.end()) {
4288 ++it;
4289 continue;
4290 }
4291
4292 if (is_local_update) {
4293 data_channel->SetSendSsrc(0);
4294 } else {
4295 data_channel->RemotePeerRequestClose();
4296 }
4297
4298 if (data_channel->state() == DataChannel::kClosed) {
4299 rtp_data_channels_.erase(it);
4300 it = rtp_data_channels_.begin();
4301 } else {
4302 ++it;
4303 }
4304 }
4305}
4306
4307void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4308 uint32_t remote_ssrc) {
4309 rtc::scoped_refptr<DataChannel> channel(
4310 InternalCreateDataChannel(label, nullptr));
4311 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004312 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004313 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004314 return;
4315 }
4316 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004317 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4318 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004319 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004320}
4321
4322rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4323 const std::string& label,
4324 const InternalDataChannelInit* config) {
4325 if (IsClosed()) {
4326 return nullptr;
4327 }
Steve Anton75737c02017-11-06 10:37:17 -08004328 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004329 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004330 << "InternalCreateDataChannel: Data is not supported in this call.";
4331 return nullptr;
4332 }
4333 InternalDataChannelInit new_config =
4334 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004335 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004336 if (new_config.id < 0) {
4337 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004338 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004339 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004340 RTC_LOG(LS_ERROR)
4341 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004342 return nullptr;
4343 }
4344 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004345 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004346 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004347 return nullptr;
4348 }
4349 }
4350
Steve Anton75737c02017-11-06 10:37:17 -08004351 rtc::scoped_refptr<DataChannel> channel(
4352 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004353 if (!channel) {
4354 sid_allocator_.ReleaseSid(new_config.id);
4355 return nullptr;
4356 }
4357
4358 if (channel->data_channel_type() == cricket::DCT_RTP) {
4359 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004360 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4361 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004362 return nullptr;
4363 }
4364 rtp_data_channels_[channel->label()] = channel;
4365 } else {
4366 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4367 sctp_data_channels_.push_back(channel);
4368 channel->SignalClosed.connect(this,
4369 &PeerConnection::OnSctpDataChannelClosed);
4370 }
4371
Steve Anton2d8609c2018-01-23 16:38:46 -08004372 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004373 return channel;
4374}
4375
4376bool PeerConnection::HasDataChannels() const {
4377 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4378}
4379
4380void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4381 for (const auto& channel : sctp_data_channels_) {
4382 if (channel->id() < 0) {
4383 int sid;
4384 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004385 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004386 continue;
4387 }
4388 channel->SetSctpSid(sid);
4389 }
4390 }
4391}
4392
4393void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004394 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004395 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4396 ++it) {
4397 if (it->get() == channel) {
4398 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004399 // After the closing procedure is done, it's safe to use this ID for
4400 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004401 sid_allocator_.ReleaseSid(channel->id());
4402 }
deadbeefbd292462015-12-14 18:15:29 -08004403 // Since this method is triggered by a signal from the DataChannel,
4404 // we can't free it directly here; we need to free it asynchronously.
4405 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004406 sctp_data_channels_.erase(it);
Steve Antonbb192762018-08-31 11:57:02 -07004407 async_invoker_.AsyncInvoke<void>(
4408 RTC_FROM_HERE, signaling_thread(),
4409 [this] { sctp_data_channels_to_free_.clear(); });
deadbeefab9b2d12015-10-14 11:33:11 -07004410 return;
4411 }
4412 }
4413}
4414
deadbeefab9b2d12015-10-14 11:33:11 -07004415void PeerConnection::OnDataChannelDestroyed() {
4416 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4417 // DataChannel may callback to us and try to modify the list.
4418 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4419 temp_rtp_dcs.swap(rtp_data_channels_);
4420 for (const auto& kv : temp_rtp_dcs) {
4421 kv.second->OnTransportChannelDestroyed();
4422 }
4423
4424 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4425 temp_sctp_dcs.swap(sctp_data_channels_);
4426 for (const auto& channel : temp_sctp_dcs) {
4427 channel->OnTransportChannelDestroyed();
4428 }
4429}
4430
4431void PeerConnection::OnDataChannelOpenMessage(
4432 const std::string& label,
4433 const InternalDataChannelInit& config) {
4434 rtc::scoped_refptr<DataChannel> channel(
4435 InternalCreateDataChannel(label, &config));
4436 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004437 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004438 return;
4439 }
4440
deadbeefa601f5c2016-06-06 14:27:39 -07004441 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4442 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004443 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004444 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004445}
4446
Steve Anton4171afb2017-11-20 10:20:22 -08004447rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4448PeerConnection::GetAudioTransceiver() const {
4449 // This method only works with Plan B SDP, where there is a single
4450 // audio/video transceiver.
4451 RTC_DCHECK(!IsUnifiedPlan());
4452 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004453 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004454 return transceiver;
4455 }
4456 }
4457 RTC_NOTREACHED();
4458 return nullptr;
4459}
4460
4461rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4462PeerConnection::GetVideoTransceiver() const {
4463 // This method only works with Plan B SDP, where there is a single
4464 // audio/video transceiver.
4465 RTC_DCHECK(!IsUnifiedPlan());
4466 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004467 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004468 return transceiver;
4469 }
4470 }
4471 RTC_NOTREACHED();
4472 return nullptr;
4473}
4474
4475// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4476// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004477bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004478 switch (type) {
4479 case cricket::MEDIA_TYPE_AUDIO:
4480 return !GetAudioTransceiver()->internal()->senders().empty();
4481 case cricket::MEDIA_TYPE_VIDEO:
4482 return !GetVideoTransceiver()->internal()->senders().empty();
4483 case cricket::MEDIA_TYPE_DATA:
4484 return false;
4485 }
4486 RTC_NOTREACHED();
4487 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004488}
4489
Steve Anton4171afb2017-11-20 10:20:22 -08004490rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4491PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4492 for (auto transceiver : transceivers_) {
4493 for (auto sender : transceiver->internal()->senders()) {
4494 if (sender->track() == track) {
4495 return sender;
4496 }
4497 }
4498 }
4499 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004500}
4501
Steve Anton4171afb2017-11-20 10:20:22 -08004502rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4503PeerConnection::FindSenderById(const std::string& sender_id) const {
4504 for (auto transceiver : transceivers_) {
4505 for (auto sender : transceiver->internal()->senders()) {
4506 if (sender->id() == sender_id) {
4507 return sender;
4508 }
4509 }
4510 }
4511 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004512}
4513
Steve Anton4171afb2017-11-20 10:20:22 -08004514rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4515PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4516 for (auto transceiver : transceivers_) {
4517 for (auto receiver : transceiver->internal()->receivers()) {
4518 if (receiver->id() == receiver_id) {
4519 return receiver;
4520 }
4521 }
4522 }
4523 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004524}
4525
Steve Anton4171afb2017-11-20 10:20:22 -08004526std::vector<PeerConnection::RtpSenderInfo>*
4527PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4528 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4529 media_type == cricket::MEDIA_TYPE_VIDEO);
4530 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4531 ? &remote_audio_sender_infos_
4532 : &remote_video_sender_infos_;
4533}
4534
4535std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004536 cricket::MediaType media_type) {
4537 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4538 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004539 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4540 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004541}
4542
Steve Anton4171afb2017-11-20 10:20:22 -08004543const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4544 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004545 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004546 const std::string sender_id) const {
4547 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004548 if (sender_info.stream_id == stream_id &&
4549 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004550 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004551 }
4552 }
4553 return nullptr;
4554}
4555
4556DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4557 for (const auto& channel : sctp_data_channels_) {
4558 if (channel->id() == sid) {
4559 return channel;
4560 }
4561 }
4562 return nullptr;
4563}
4564
deadbeef91dd5672016-05-18 16:55:30 -07004565bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004566 const cricket::ServerAddresses& stun_servers,
4567 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004568 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004569 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004570 // To handle both internal and externally created port allocator, we will
4571 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004572 port_allocator_flags_ = port_allocator_->flags();
4573 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4574 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4575 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004576 // If the disable-IPv6 flag was specified, we'll not override it
4577 // by experiment.
4578 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004579 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004580 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4581 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004582 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004583 }
4584
zhihuangb09b3f92017-03-07 14:40:51 -08004585 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004586 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004587 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004588 }
4589
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004590 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004591 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004592 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004593 }
4594
honghaiz60347052016-05-31 18:29:12 -07004595 if (configuration.candidate_network_policy ==
4596 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004597 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004598 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004599 }
4600
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004601 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004602 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004603 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4604 }
4605
Qingsi Wanga2d60672018-04-11 16:57:45 -07004606 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004607 // No step delay is used while allocating ports.
4608 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4609 port_allocator_->set_candidate_filter(
4610 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004611 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004612
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004613 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004614 for (auto& turn_server : turn_servers_copy) {
4615 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004616 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004617 // Call this last since it may create pooled allocator sessions using the
4618 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004619 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004620 stun_servers, std::move(turn_servers_copy),
4621 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4622 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004623 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004624 return true;
4625}
4626
deadbeef91dd5672016-05-18 16:55:30 -07004627bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004628 const cricket::ServerAddresses& stun_servers,
4629 const std::vector<cricket::RelayServerConfig>& turn_servers,
4630 IceTransportsType type,
4631 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004632 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004633 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004634 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004635 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004636 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004637 // According to JSEP, after setLocalDescription, changing the candidate pool
4638 // size is not allowed, and changing the set of ICE servers will not result
4639 // in new candidates being gathered.
4640 if (local_description()) {
4641 port_allocator_->FreezeCandidatePool();
4642 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004643 // Add the custom tls turn servers if they exist.
4644 auto turn_servers_copy = turn_servers;
4645 for (auto& turn_server : turn_servers_copy) {
4646 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4647 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004648 // Call this last since it may create pooled allocator sessions using the
4649 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004650 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004651 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4652 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004653}
4654
Steve Antonba818672017-11-06 10:21:57 -08004655cricket::ChannelManager* PeerConnection::channel_manager() const {
4656 return factory_->channel_manager();
4657}
4658
Elad Alon99c3fe52017-10-13 16:29:40 +02004659bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004660 std::unique_ptr<RtcEventLogOutput> output,
4661 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004662 if (!event_log_) {
4663 return false;
4664 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004665 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004666}
4667
4668void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004669 if (event_log_) {
4670 event_log_->StopLogging();
4671 }
ivoc14d5dbe2016-07-04 07:06:55 -07004672}
nisseeaabdf62017-05-05 02:23:02 -07004673
Steve Anton75737c02017-11-06 10:37:17 -08004674cricket::BaseChannel* PeerConnection::GetChannel(
4675 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004676 for (auto transceiver : transceivers_) {
4677 cricket::BaseChannel* channel = transceiver->internal()->channel();
4678 if (channel && channel->content_name() == content_name) {
4679 return channel;
4680 }
Steve Anton75737c02017-11-06 10:37:17 -08004681 }
4682 if (rtp_data_channel() &&
4683 rtp_data_channel()->content_name() == content_name) {
4684 return rtp_data_channel();
4685 }
4686 return nullptr;
4687}
4688
4689bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4690 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004691 RTC_LOG(LS_INFO)
4692 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004693 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004694 return false;
4695 }
4696 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004697 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004698 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004699 return false;
4700 }
4701
Zhi Huange830e682018-03-30 10:48:35 -07004702 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4703 if (dtls_role) {
4704 *role = *dtls_role;
4705 return true;
4706 }
4707 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004708}
4709
4710bool PeerConnection::GetSslRole(const std::string& content_name,
4711 rtc::SSLRole* role) {
4712 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004713 RTC_LOG(LS_INFO)
4714 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004715 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004716 return false;
4717 }
4718
Zhi Huange830e682018-03-30 10:48:35 -07004719 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4720 if (dtls_role) {
4721 *role = *dtls_role;
4722 return true;
4723 }
4724 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004725}
4726
Steve Antonf8470812017-12-04 10:46:21 -08004727void PeerConnection::SetSessionError(SessionError error,
4728 const std::string& error_desc) {
4729 RTC_DCHECK_RUN_ON(signaling_thread());
4730 if (error != session_error_) {
4731 session_error_ = error;
4732 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004733 }
4734}
4735
Zhi Huange830e682018-03-30 10:48:35 -07004736RTCError PeerConnection::UpdateSessionState(
4737 SdpType type,
4738 cricket::ContentSource source,
4739 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004740 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004741
4742 // If there's already a pending error then no state transition should happen.
4743 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004744 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004745
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004746 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004747 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004748 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004749 }
4750
4751 // Update the signaling state according to the specified state machine (see
4752 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004753 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004754 ChangeSignalingState(source == cricket::CS_LOCAL
4755 ? PeerConnectionInterface::kHaveLocalOffer
4756 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004757 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004758 ChangeSignalingState(source == cricket::CS_LOCAL
4759 ? PeerConnectionInterface::kHaveLocalPrAnswer
4760 : PeerConnectionInterface::kHaveRemotePrAnswer);
4761 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004762 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004763 ChangeSignalingState(PeerConnectionInterface::kStable);
4764 }
4765
4766 // Update internal objects according to the session description's media
4767 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004768 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004769 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004770 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004771 }
4772
Steve Anton8a006912017-12-04 15:25:56 -08004773 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004774}
4775
Steve Anton8a006912017-12-04 15:25:56 -08004776RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004777 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004778 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004779 const SessionDescriptionInterface* sdesc =
4780 (source == cricket::CS_LOCAL ? local_description()
4781 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004782 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004783
4784 // Push down the new SDP media section for each audio/video transceiver.
4785 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004786 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004787 FindMediaSectionForTransceiver(transceiver, sdesc);
4788 cricket::BaseChannel* channel = transceiver->internal()->channel();
4789 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004790 continue;
4791 }
4792 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004793 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004794 if (!content_desc) {
4795 continue;
4796 }
4797 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004798 bool success = (source == cricket::CS_LOCAL)
4799 ? channel->SetLocalContent(content_desc, type, &error)
4800 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004801 if (!success) {
4802 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4803 }
4804 }
4805
4806 // If using the RtpDataChannel, push down the new SDP section for it too.
4807 if (rtp_data_channel_) {
4808 const ContentInfo* data_content =
4809 cricket::GetFirstDataContent(sdesc->description());
4810 if (data_content && !data_content->rejected) {
4811 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004812 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004813 if (data_desc) {
4814 std::string error;
4815 bool success =
4816 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004817 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004818 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004819 if (!success) {
4820 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4821 std::move(error));
4822 }
Steve Anton75737c02017-11-06 10:37:17 -08004823 }
4824 }
4825 }
Steve Antoned10bd92017-12-05 10:52:59 -08004826
Steve Anton75737c02017-11-06 10:37:17 -08004827 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4828 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4829 if (sctp_transport_ && local_description() && remote_description() &&
4830 cricket::GetFirstDataContent(local_description()->description()) &&
4831 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004832 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004833 RTC_FROM_HERE,
4834 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004835 if (!success) {
4836 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4837 "Failed to push down SCTP parameters.");
4838 }
Steve Anton75737c02017-11-06 10:37:17 -08004839 }
Steve Antoned10bd92017-12-05 10:52:59 -08004840
Steve Anton8a006912017-12-04 15:25:56 -08004841 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004842}
4843
4844bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4845 RTC_DCHECK(network_thread()->IsCurrent());
4846 RTC_DCHECK(local_description());
4847 RTC_DCHECK(remote_description());
4848 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4849 // When we support "max-message-size", that would also be pushed down here.
4850 return sctp_transport_->Start(
4851 GetSctpPort(local_description()->description()),
4852 GetSctpPort(remote_description()->description()));
4853}
4854
Steve Anton8a006912017-12-04 15:25:56 -08004855RTCError PeerConnection::PushdownTransportDescription(
4856 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004857 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004858 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004859
Zhi Huange830e682018-03-30 10:48:35 -07004860 if (source == cricket::CS_LOCAL) {
4861 const SessionDescriptionInterface* sdesc = local_description();
4862 RTC_DCHECK(sdesc);
4863 return transport_controller_->SetLocalDescription(type,
4864 sdesc->description());
4865 } else {
4866 const SessionDescriptionInterface* sdesc = remote_description();
4867 RTC_DCHECK(sdesc);
4868 return transport_controller_->SetRemoteDescription(type,
4869 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004870 }
Steve Anton75737c02017-11-06 10:37:17 -08004871}
4872
4873bool PeerConnection::GetTransportDescription(
4874 const SessionDescription* description,
4875 const std::string& content_name,
4876 cricket::TransportDescription* tdesc) {
4877 if (!description || !tdesc) {
4878 return false;
4879 }
4880 const TransportInfo* transport_info =
4881 description->GetTransportInfoByName(content_name);
4882 if (!transport_info) {
4883 return false;
4884 }
4885 *tdesc = transport_info->description;
4886 return true;
4887}
4888
Steve Anton75737c02017-11-06 10:37:17 -08004889cricket::IceConfig PeerConnection::ParseIceConfig(
4890 const PeerConnectionInterface::RTCConfiguration& config) const {
4891 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004892 switch (config.continual_gathering_policy) {
4893 case PeerConnectionInterface::GATHER_ONCE:
4894 gathering_policy = cricket::GATHER_ONCE;
4895 break;
4896 case PeerConnectionInterface::GATHER_CONTINUALLY:
4897 gathering_policy = cricket::GATHER_CONTINUALLY;
4898 break;
4899 default:
4900 RTC_NOTREACHED();
4901 gathering_policy = cricket::GATHER_ONCE;
4902 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004903
Steve Anton75737c02017-11-06 10:37:17 -08004904 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004905 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4906 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004907 ice_config.prioritize_most_likely_candidate_pairs =
4908 config.prioritize_most_likely_ice_candidate_pairs;
4909 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004910 RTCConfigurationToIceConfigOptionalInt(
4911 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004912 ice_config.continual_gathering_policy = gathering_policy;
4913 ice_config.presume_writable_when_fully_relayed =
4914 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004915 ice_config.ice_check_interval_strong_connectivity =
4916 config.ice_check_interval_strong_connectivity;
4917 ice_config.ice_check_interval_weak_connectivity =
4918 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004919 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004920 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004921 ice_config.regather_all_networks_interval_range =
4922 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004923 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004924 return ice_config;
4925}
4926
Steve Anton75737c02017-11-06 10:37:17 -08004927bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4928 std::string* track_id) {
4929 if (!local_description()) {
4930 return false;
4931 }
4932 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4933 track_id);
4934}
4935
4936bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4937 std::string* track_id) {
4938 if (!remote_description()) {
4939 return false;
4940 }
4941 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4942 track_id);
4943}
4944
4945bool PeerConnection::SendData(const cricket::SendDataParams& params,
4946 const rtc::CopyOnWriteBuffer& payload,
4947 cricket::SendDataResult* result) {
4948 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004949 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004950 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004951 return false;
4952 }
4953 return rtp_data_channel_
4954 ? rtp_data_channel_->SendData(params, payload, result)
4955 : network_thread()->Invoke<bool>(
4956 RTC_FROM_HERE,
4957 Bind(&cricket::SctpTransportInternal::SendData,
4958 sctp_transport_.get(), params, payload, result));
4959}
4960
4961bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4962 if (!rtp_data_channel_ && !sctp_transport_) {
4963 // Don't log an error here, because DataChannels are expected to call
4964 // ConnectDataChannel in this state. It's the only way to initially tell
4965 // whether or not the underlying transport is ready.
4966 return false;
4967 }
4968 if (rtp_data_channel_) {
4969 rtp_data_channel_->SignalReadyToSendData.connect(
4970 webrtc_data_channel, &DataChannel::OnChannelReady);
4971 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4972 &DataChannel::OnDataReceived);
4973 } else {
4974 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4975 &DataChannel::OnChannelReady);
4976 SignalSctpDataReceived.connect(webrtc_data_channel,
4977 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004978 SignalSctpClosingProcedureStartedRemotely.connect(
4979 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
4980 SignalSctpClosingProcedureComplete.connect(
4981 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08004982 }
4983 return true;
4984}
4985
4986void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4987 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004988 RTC_LOG(LS_ERROR)
4989 << "DisconnectDataChannel called when rtp_data_channel_ and "
4990 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004991 return;
4992 }
4993 if (rtp_data_channel_) {
4994 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4995 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4996 } else {
4997 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4998 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004999 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5000 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005001 }
5002}
5003
5004void PeerConnection::AddSctpDataStream(int sid) {
5005 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005006 RTC_LOG(LS_ERROR)
5007 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005008 return;
5009 }
5010 network_thread()->Invoke<void>(
5011 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5012 sctp_transport_.get(), sid));
5013}
5014
5015void PeerConnection::RemoveSctpDataStream(int sid) {
5016 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005017 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005018 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005019 return;
5020 }
5021 network_thread()->Invoke<void>(
5022 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5023 sctp_transport_.get(), sid));
5024}
5025
5026bool PeerConnection::ReadyToSendData() const {
5027 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5028 sctp_ready_to_send_data_;
5029}
5030
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005031absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005032 if (sctp_mid_ && transport_controller_) {
5033 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5034 if (dtls_transport) {
5035 return dtls_transport->transport_name();
5036 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005037 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005038 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005039 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005040}
5041
Qingsi Wang72a43a12018-02-20 16:03:18 -08005042cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5043 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005044 network_thread()->Invoke<void>(
5045 RTC_FROM_HERE,
5046 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5047 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005048 return candidate_states_list;
5049}
5050
Steve Anton5dfde182018-02-06 10:34:40 -08005051std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5052 const {
5053 std::map<std::string, std::string> transport_names_by_mid;
5054 for (auto transceiver : transceivers_) {
5055 cricket::BaseChannel* channel = transceiver->internal()->channel();
5056 if (channel) {
5057 transport_names_by_mid[channel->content_name()] =
5058 channel->transport_name();
5059 }
Steve Anton75737c02017-11-06 10:37:17 -08005060 }
Steve Anton5dfde182018-02-06 10:34:40 -08005061 if (rtp_data_channel_) {
5062 transport_names_by_mid[rtp_data_channel_->content_name()] =
5063 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005064 }
5065 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005066 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005067 RTC_DCHECK(transport_name);
5068 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005069 }
Steve Anton5dfde182018-02-06 10:34:40 -08005070 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005071}
5072
Steve Anton5dfde182018-02-06 10:34:40 -08005073std::map<std::string, cricket::TransportStats>
5074PeerConnection::GetTransportStatsByNames(
5075 const std::set<std::string>& transport_names) {
5076 if (!network_thread()->IsCurrent()) {
5077 return network_thread()
5078 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5079 RTC_FROM_HERE,
5080 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005081 }
Steve Anton5dfde182018-02-06 10:34:40 -08005082 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5083 for (const std::string& transport_name : transport_names) {
5084 cricket::TransportStats transport_stats;
5085 bool success =
5086 transport_controller_->GetStats(transport_name, &transport_stats);
5087 if (success) {
5088 transport_stats_by_name[transport_name] = std::move(transport_stats);
5089 } else {
5090 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5091 << transport_name;
5092 }
5093 }
5094 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005095}
5096
5097bool PeerConnection::GetLocalCertificate(
5098 const std::string& transport_name,
5099 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005100 if (!certificate) {
5101 return false;
5102 }
5103 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5104 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005105}
5106
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005107std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005108 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005109 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005110}
5111
5112cricket::DataChannelType PeerConnection::data_channel_type() const {
5113 return data_channel_type_;
5114}
5115
5116bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5117 return pending_ice_restarts_.find(content_name) !=
5118 pending_ice_restarts_.end();
5119}
5120
Steve Anton75737c02017-11-06 10:37:17 -08005121bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5122 return transport_controller_->NeedsIceRestart(content_name);
5123}
5124
5125void PeerConnection::OnCertificateReady(
5126 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5127 transport_controller_->SetLocalCertificate(certificate);
5128}
5129
5130void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005131 SetSessionError(SessionError::kTransport,
5132 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005133}
5134
5135void PeerConnection::OnTransportControllerConnectionState(
5136 cricket::IceConnectionState state) {
5137 switch (state) {
5138 case cricket::kIceConnectionConnecting:
5139 // If the current state is Connected or Completed, then there were
5140 // writable channels but now there are not, so the next state must
5141 // be Disconnected.
5142 // kIceConnectionConnecting is currently used as the default,
5143 // un-connected state by the TransportController, so its only use is
5144 // detecting disconnections.
5145 if (ice_connection_state_ ==
5146 PeerConnectionInterface::kIceConnectionConnected ||
5147 ice_connection_state_ ==
5148 PeerConnectionInterface::kIceConnectionCompleted) {
5149 SetIceConnectionState(
5150 PeerConnectionInterface::kIceConnectionDisconnected);
5151 }
5152 break;
5153 case cricket::kIceConnectionFailed:
5154 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5155 break;
5156 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005157 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005158 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005159 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005160 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005161 break;
5162 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005163 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005164 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005165 if (ice_connection_state_ !=
5166 PeerConnectionInterface::kIceConnectionConnected) {
5167 // If jumping directly from "checking" to "connected",
5168 // signal "connected" first.
5169 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5170 }
5171 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005172 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005173 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005174 break;
5175 default:
5176 RTC_NOTREACHED();
5177 }
5178}
5179
5180void PeerConnection::OnTransportControllerCandidatesGathered(
5181 const std::string& transport_name,
5182 const cricket::Candidates& candidates) {
5183 RTC_DCHECK(signaling_thread()->IsCurrent());
5184 int sdp_mline_index;
5185 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005186 RTC_LOG(LS_ERROR)
5187 << "OnTransportControllerCandidatesGathered: content name "
5188 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005189 return;
5190 }
5191
5192 for (cricket::Candidates::const_iterator citer = candidates.begin();
5193 citer != candidates.end(); ++citer) {
5194 // Use transport_name as the candidate media id.
5195 std::unique_ptr<JsepIceCandidate> candidate(
5196 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5197 if (local_description()) {
5198 mutable_local_description()->AddCandidate(candidate.get());
5199 }
5200 OnIceCandidate(std::move(candidate));
5201 }
5202}
5203
5204void PeerConnection::OnTransportControllerCandidatesRemoved(
5205 const std::vector<cricket::Candidate>& candidates) {
5206 RTC_DCHECK(signaling_thread()->IsCurrent());
5207 // Sanity check.
5208 for (const cricket::Candidate& candidate : candidates) {
5209 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005210 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005211 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005212 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005213 return;
5214 }
5215 }
5216
5217 if (local_description()) {
5218 mutable_local_description()->RemoveCandidates(candidates);
5219 }
5220 OnIceCandidatesRemoved(candidates);
5221}
5222
5223void PeerConnection::OnTransportControllerDtlsHandshakeError(
5224 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005225 RTC_HISTOGRAM_ENUMERATION(
5226 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5227 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005228}
5229
Steve Antoned10bd92017-12-05 10:52:59 -08005230void PeerConnection::EnableSending() {
5231 for (auto transceiver : transceivers_) {
5232 cricket::BaseChannel* channel = transceiver->internal()->channel();
5233 if (channel && !channel->enabled()) {
5234 channel->Enable(true);
5235 }
Steve Anton75737c02017-11-06 10:37:17 -08005236 }
5237
Steve Anton4171afb2017-11-20 10:20:22 -08005238 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005239 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005240 }
Steve Anton75737c02017-11-06 10:37:17 -08005241}
5242
5243// Returns the media index for a local ice candidate given the content name.
5244bool PeerConnection::GetLocalCandidateMediaIndex(
5245 const std::string& content_name,
5246 int* sdp_mline_index) {
5247 if (!local_description() || !sdp_mline_index) {
5248 return false;
5249 }
5250
5251 bool content_found = false;
5252 const ContentInfos& contents = local_description()->description()->contents();
5253 for (size_t index = 0; index < contents.size(); ++index) {
5254 if (contents[index].name == content_name) {
5255 *sdp_mline_index = static_cast<int>(index);
5256 content_found = true;
5257 break;
5258 }
5259 }
5260 return content_found;
5261}
5262
5263bool PeerConnection::UseCandidatesInSessionDescription(
5264 const SessionDescriptionInterface* remote_desc) {
5265 if (!remote_desc) {
5266 return true;
5267 }
5268 bool ret = true;
5269
5270 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5271 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5272 for (size_t n = 0; n < candidates->count(); ++n) {
5273 const IceCandidateInterface* candidate = candidates->at(n);
5274 bool valid = false;
5275 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5276 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005277 RTC_LOG(LS_INFO)
5278 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005279 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005280 }
5281 continue;
5282 }
5283 ret = UseCandidate(candidate);
5284 if (!ret) {
5285 break;
5286 }
5287 }
5288 }
5289 return ret;
5290}
5291
5292bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5293 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5294 size_t remote_content_size =
5295 remote_description()->description()->contents().size();
5296 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005297 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005298 return false;
5299 }
5300
5301 cricket::ContentInfo content =
5302 remote_description()->description()->contents()[mediacontent_index];
5303 std::vector<cricket::Candidate> candidates;
5304 candidates.push_back(candidate->candidate());
5305 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005306 RTCError error =
5307 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005308 if (error.ok()) {
5309 // Candidates successfully submitted for checking.
5310 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5311 ice_connection_state_ ==
5312 PeerConnectionInterface::kIceConnectionDisconnected) {
5313 // If state is New, then the session has just gotten its first remote ICE
5314 // candidates, so go to Checking.
5315 // If state is Disconnected, the session is re-using old candidates or
5316 // receiving additional ones, so go to Checking.
5317 // If state is Connected, stay Connected.
5318 // TODO(bemasc): If state is Connected, and the new candidates are for a
5319 // newly added transport, then the state actually _should_ move to
5320 // checking. Add a way to distinguish that case.
5321 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5322 }
5323 // TODO(bemasc): If state is Completed, go back to Connected.
5324 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005325 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005326 }
5327 return true;
5328}
5329
5330void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005331 // Destroy video channel first since it may have a pointer to the
5332 // voice channel.
5333 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005334 if (!video_info || video_info->rejected) {
5335 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005336 }
5337
Steve Anton6fec8802017-12-04 10:37:29 -08005338 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5339 if (!audio_info || audio_info->rejected) {
5340 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005341 }
5342
5343 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5344 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005345 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005346 }
5347}
5348
Steve Antondcc3c022017-12-22 16:02:54 -08005349RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5350 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005351 const cricket::ContentGroup* bundle_group = nullptr;
5352 if (configuration_.bundle_policy ==
5353 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005354 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005355 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005356 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5357 "max-bundle configured but session description "
5358 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005359 }
5360 }
Steve Antondcc3c022017-12-22 16:02:54 -08005361 return std::move(bundle_group);
5362}
5363
5364RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005365 // Creating the media channels. Transports should already have been created
5366 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005367 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005368 if (voice && !voice->rejected &&
5369 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005370 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005371 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005372 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5373 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005374 }
5375 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5376 }
5377
Steve Antondcc3c022017-12-22 16:02:54 -08005378 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005379 if (video && !video->rejected &&
5380 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005381 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005382 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005383 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5384 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005385 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005386 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005387 }
5388
Steve Antondcc3c022017-12-22 16:02:54 -08005389 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005390 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5391 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005392 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005393 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5394 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005395 }
5396 }
5397
Steve Anton8a006912017-12-04 15:25:56 -08005398 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005399}
5400
Steve Anton4171afb2017-11-20 10:20:22 -08005401// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005402cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005403 const std::string& mid) {
5404 RtpTransportInternal* rtp_transport =
5405 transport_controller_->GetRtpTransport(mid);
5406 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005407 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005408 call_.get(), configuration_.media_config, rtp_transport,
5409 signaling_thread(), mid, SrtpRequired(),
5410 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005411 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005412 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005413 }
Steve Anton75737c02017-11-06 10:37:17 -08005414 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5415 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005416 voice_channel->SignalSentPacket.connect(this,
5417 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005418 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005419
Steve Antoneda6ccd2017-12-04 10:21:55 -08005420 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005421}
5422
Steve Anton4171afb2017-11-20 10:20:22 -08005423// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005424cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005425 const std::string& mid) {
5426 RtpTransportInternal* rtp_transport =
5427 transport_controller_->GetRtpTransport(mid);
5428 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005429 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005430 call_.get(), configuration_.media_config, rtp_transport,
5431 signaling_thread(), mid, SrtpRequired(),
5432 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005433 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005434 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005435 }
Steve Anton75737c02017-11-06 10:37:17 -08005436 video_channel->SignalDtlsSrtpSetupFailure.connect(
5437 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005438 video_channel->SignalSentPacket.connect(this,
5439 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005440 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005441
Steve Antoneda6ccd2017-12-04 10:21:55 -08005442 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005443}
5444
Zhi Huange830e682018-03-30 10:48:35 -07005445bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005446 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5447 if (sctp) {
5448 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005449 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005450 << "Trying to create SCTP transport, but didn't compile with "
5451 "SCTP support (HAVE_SCTP)";
5452 return false;
5453 }
5454 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005455 RTC_FROM_HERE,
5456 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005457 return false;
5458 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005459 for (const auto& channel : sctp_data_channels_) {
5460 channel->OnTransportChannelCreated();
5461 }
Steve Anton75737c02017-11-06 10:37:17 -08005462 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005463 RtpTransportInternal* rtp_transport =
5464 transport_controller_->GetRtpTransport(mid);
5465 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005466 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005467 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5468 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005469 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005470 return false;
5471 }
Steve Anton75737c02017-11-06 10:37:17 -08005472 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5473 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5474 rtp_data_channel_->SignalSentPacket.connect(
5475 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005476 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005477 }
5478
Steve Anton75737c02017-11-06 10:37:17 -08005479 return true;
5480}
5481
5482Call::Stats PeerConnection::GetCallStats() {
5483 if (!worker_thread()->IsCurrent()) {
5484 return worker_thread()->Invoke<Call::Stats>(
5485 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5486 }
5487 if (call_) {
5488 return call_->GetStats();
5489 } else {
5490 return Call::Stats();
5491 }
5492}
5493
Zhi Huange830e682018-03-30 10:48:35 -07005494bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005495 RTC_DCHECK(network_thread()->IsCurrent());
5496 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005497 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005498 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005499 RTC_DCHECK(dtls_transport);
5500 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005501 RTC_DCHECK(sctp_transport_);
5502 sctp_invoker_.reset(new rtc::AsyncInvoker());
5503 sctp_transport_->SignalReadyToSendData.connect(
5504 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5505 sctp_transport_->SignalDataReceived.connect(
5506 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005507 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5508 // another thread. Would be nice if there was a helper class similar to
5509 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5510 // code.
5511 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5512 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5513 sctp_transport_->SignalClosingProcedureComplete.connect(
5514 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005515 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005516 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005517 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005518}
5519
5520void PeerConnection::DestroySctpTransport_n() {
5521 RTC_DCHECK(network_thread()->IsCurrent());
5522 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005523 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005524 sctp_invoker_.reset(nullptr);
5525 sctp_ready_to_send_data_ = false;
5526}
5527
5528void PeerConnection::OnSctpTransportReadyToSendData_n() {
5529 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5530 RTC_DCHECK(network_thread()->IsCurrent());
5531 // Note: Cannot use rtc::Bind here because it will grab a reference to
5532 // PeerConnection and potentially cause PeerConnection to live longer than
5533 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5534 // be destroyed before PeerConnection is destroyed, and at that point all
5535 // pending tasks will be cleared.
5536 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5537 OnSctpTransportReadyToSendData_s(true);
5538 });
5539}
5540
5541void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5542 RTC_DCHECK(signaling_thread()->IsCurrent());
5543 sctp_ready_to_send_data_ = ready;
5544 SignalSctpReadyToSendData(ready);
5545}
5546
5547void PeerConnection::OnSctpTransportDataReceived_n(
5548 const cricket::ReceiveDataParams& params,
5549 const rtc::CopyOnWriteBuffer& payload) {
5550 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5551 RTC_DCHECK(network_thread()->IsCurrent());
5552 // Note: Cannot use rtc::Bind here because it will grab a reference to
5553 // PeerConnection and potentially cause PeerConnection to live longer than
5554 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5555 // be destroyed before PeerConnection is destroyed, and at that point all
5556 // pending tasks will be cleared.
5557 sctp_invoker_->AsyncInvoke<void>(
5558 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5559 OnSctpTransportDataReceived_s(params, payload);
5560 });
5561}
5562
5563void PeerConnection::OnSctpTransportDataReceived_s(
5564 const cricket::ReceiveDataParams& params,
5565 const rtc::CopyOnWriteBuffer& payload) {
5566 RTC_DCHECK(signaling_thread()->IsCurrent());
5567 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5568 // Received OPEN message; parse and signal that a new data channel should
5569 // be created.
5570 std::string label;
5571 InternalDataChannelInit config;
5572 config.id = params.ssrc;
5573 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005574 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5575 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005576 return;
5577 }
5578 config.open_handshake_role = InternalDataChannelInit::kAcker;
5579 OnDataChannelOpenMessage(label, config);
5580 } else {
5581 // Otherwise just forward the signal.
5582 SignalSctpDataReceived(params, payload);
5583 }
5584}
5585
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005586void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005587 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5588 RTC_DCHECK(network_thread()->IsCurrent());
5589 sctp_invoker_->AsyncInvoke<void>(
5590 RTC_FROM_HERE, signaling_thread(),
5591 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005592 &SignalSctpClosingProcedureStartedRemotely, sid));
5593}
5594
5595void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5596 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5597 RTC_DCHECK(network_thread()->IsCurrent());
5598 sctp_invoker_->AsyncInvoke<void>(
5599 RTC_FROM_HERE, signaling_thread(),
5600 rtc::Bind(&sigslot::signal1<int>::operator(),
5601 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005602}
5603
5604// Returns false if bundle is enabled and rtcp_mux is disabled.
5605bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5606 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5607 if (!bundle_enabled)
5608 return true;
5609
5610 const cricket::ContentGroup* bundle_group =
5611 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5612 RTC_DCHECK(bundle_group != NULL);
5613
5614 const cricket::ContentInfos& contents = desc->contents();
5615 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5616 citer != contents.end(); ++citer) {
5617 const cricket::ContentInfo* content = (&*citer);
5618 RTC_DCHECK(content != NULL);
5619 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005620 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005621 if (!HasRtcpMuxEnabled(content))
5622 return false;
5623 }
5624 }
5625 // RTCP-MUX is enabled in all the contents.
5626 return true;
5627}
5628
5629bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005630 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005631}
5632
Steve Anton8a006912017-12-04 15:25:56 -08005633RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005634 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005635 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005636 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005637 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005638 }
5639
5640 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005641 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005642 }
5643
Steve Anton3828c062017-12-06 10:34:51 -08005644 SdpType type = sdesc->GetType();
5645 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5646 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005647 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005648 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005649 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005650 }
5651
5652 // Verify crypto settings.
5653 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005654 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5655 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005656 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005657 if (!crypto_error.ok()) {
5658 return crypto_error;
5659 }
Steve Anton75737c02017-11-06 10:37:17 -08005660 }
5661
5662 // Verify ice-ufrag and ice-pwd.
5663 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005664 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5665 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005666 }
5667
5668 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005669 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5670 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005671 }
5672
5673 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5674 // m-lines that do not rtcp-mux enabled.
5675
5676 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005677 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005678 // With an answer we want to compare the new answer session description with
5679 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005680 const cricket::SessionDescription* offer_desc =
5681 (source == cricket::CS_LOCAL) ? remote_description()->description()
5682 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005683 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5684 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5685 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005686 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5687 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005688 }
5689 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005690 // The re-offers should respect the order of m= sections in current
5691 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005692 // With a re-offer, either the current local or current remote descriptions
5693 // could be the most up to date, so we would like to check against both of
5694 // them if they exist. It could be the case that one of them has a 0 port
5695 // for a media section, but the other does not. This is important to check
5696 // against in the case that we are recycling an m= section.
5697 const cricket::SessionDescription* current_desc = nullptr;
5698 const cricket::SessionDescription* secondary_current_desc = nullptr;
5699 if (local_description()) {
5700 current_desc = local_description()->description();
5701 if (remote_description()) {
5702 secondary_current_desc = remote_description()->description();
5703 }
5704 } else if (remote_description()) {
5705 current_desc = remote_description()->description();
5706 }
Steve Anton75737c02017-11-06 10:37:17 -08005707 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005708 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5709 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005710 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5711 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005712 }
5713 }
5714
Steve Antonba42e992018-04-09 14:10:01 -07005715 if (IsUnifiedPlan()) {
5716 // Ensure that each audio and video media section has at most one
5717 // "StreamParams". This will return an error if receiving a session
5718 // description from a "Plan B" endpoint which adds multiple tracks of the
5719 // same type. With Unified Plan, there can only be at most one track per
5720 // media section.
5721 for (const ContentInfo& content : sdesc->description()->contents()) {
5722 const MediaContentDescription& desc = *content.description;
5723 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5724 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5725 desc.streams().size() > 1u) {
5726 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5727 "Media section has more than one track specified "
5728 "with a=ssrc lines which is not supported with "
5729 "Unified Plan.");
5730 }
5731 }
5732 }
5733
Steve Anton8a006912017-12-04 15:25:56 -08005734 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005735}
5736
Steve Anton3828c062017-12-06 10:34:51 -08005737bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005738 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005739 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005740 return (state == PeerConnectionInterface::kStable) ||
5741 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005742 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005743 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005744 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5745 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5746 }
5747}
5748
Steve Anton3828c062017-12-06 10:34:51 -08005749bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005750 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005751 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005752 return (state == PeerConnectionInterface::kStable) ||
5753 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005754 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005755 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005756 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5757 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5758 }
5759}
5760
Steve Antonf8470812017-12-04 10:46:21 -08005761const char* PeerConnection::SessionErrorToString(SessionError error) const {
5762 switch (error) {
5763 case SessionError::kNone:
5764 return "ERROR_NONE";
5765 case SessionError::kContent:
5766 return "ERROR_CONTENT";
5767 case SessionError::kTransport:
5768 return "ERROR_TRANSPORT";
5769 }
5770 RTC_NOTREACHED();
5771 return "";
5772}
5773
Steve Anton75737c02017-11-06 10:37:17 -08005774std::string PeerConnection::GetSessionErrorMsg() {
5775 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005776 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5777 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005778 return desc.str();
5779}
5780
Steve Anton8e20f172018-03-06 10:55:04 -08005781void PeerConnection::ReportSdpFormatReceived(
5782 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005783 int num_audio_mlines = 0;
5784 int num_video_mlines = 0;
5785 int num_audio_tracks = 0;
5786 int num_video_tracks = 0;
5787 for (const ContentInfo& content : remote_offer.description()->contents()) {
5788 cricket::MediaType media_type = content.media_description()->type();
5789 int num_tracks = std::max(
5790 1, static_cast<int>(content.media_description()->streams().size()));
5791 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5792 num_audio_mlines += 1;
5793 num_audio_tracks += num_tracks;
5794 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5795 num_video_mlines += 1;
5796 num_video_tracks += num_tracks;
5797 }
5798 }
5799 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5800 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5801 format = kSdpFormatReceivedComplexUnifiedPlan;
5802 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5803 format = kSdpFormatReceivedComplexPlanB;
5804 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5805 format = kSdpFormatReceivedSimple;
5806 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005807 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5808 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005809}
5810
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005811void PeerConnection::NoteUsageEvent(UsageEvent event) {
5812 RTC_DCHECK_RUN_ON(signaling_thread());
5813 usage_event_accumulator_ |= static_cast<int>(event);
5814}
5815
5816void PeerConnection::ReportUsagePattern() const {
5817 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005818 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5819 usage_event_accumulator_,
5820 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005821 const int bad_bits =
5822 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5823 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5824 const int good_bits =
5825 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5826 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5827 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5828 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5829 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005830 // If called after close(), we can't report, because observer may have
5831 // been deallocated, and therefore pointer is null. Write to log instead.
5832 if (observer_) {
5833 Observer()->OnInterestingUsage(usage_event_accumulator_);
5834 } else {
5835 RTC_LOG(LS_INFO) << "Interesting usage signature "
5836 << usage_event_accumulator_
5837 << " observed after observer shutdown";
5838 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005839 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005840}
5841
Steve Anton0ffaaa22018-02-23 10:31:30 -08005842void PeerConnection::ReportNegotiatedSdpSemantics(
5843 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005844 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005845 switch (answer.description()->msid_signaling()) {
5846 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005847 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005848 break;
5849 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005850 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005851 break;
5852 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005853 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005854 break;
5855 case cricket::kMsidSignalingMediaSection |
5856 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005857 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005858 break;
5859 default:
5860 RTC_NOTREACHED();
5861 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005862 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5863 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005864}
5865
Steve Anton75737c02017-11-06 10:37:17 -08005866// We need to check the local/remote description for the Transport instead of
5867// the session, because a new Transport added during renegotiation may have
5868// them unset while the session has them set from the previous negotiation.
5869// Not doing so may trigger the auto generation of transport description and
5870// mess up DTLS identity information, ICE credential, etc.
5871bool PeerConnection::ReadyToUseRemoteCandidate(
5872 const IceCandidateInterface* candidate,
5873 const SessionDescriptionInterface* remote_desc,
5874 bool* valid) {
5875 *valid = true;
5876
5877 const SessionDescriptionInterface* current_remote_desc =
5878 remote_desc ? remote_desc : remote_description();
5879
5880 if (!current_remote_desc) {
5881 return false;
5882 }
5883
5884 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5885 size_t remote_content_size =
5886 current_remote_desc->description()->contents().size();
5887 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005888 RTC_LOG(LS_ERROR)
5889 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5890 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005891
5892 *valid = false;
5893 return false;
5894 }
5895
5896 cricket::ContentInfo content =
5897 current_remote_desc->description()->contents()[mediacontent_index];
5898
5899 const std::string transport_name = GetTransportName(content.name);
5900 if (transport_name.empty()) {
5901 return false;
5902 }
Zhi Huange830e682018-03-30 10:48:35 -07005903 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005904}
5905
5906bool PeerConnection::SrtpRequired() const {
5907 return dtls_enabled_ ||
5908 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5909}
5910
5911void PeerConnection::OnTransportControllerGatheringState(
5912 cricket::IceGatheringState state) {
5913 RTC_DCHECK(signaling_thread()->IsCurrent());
5914 if (state == cricket::kIceGatheringGathering) {
5915 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5916 } else if (state == cricket::kIceGatheringComplete) {
5917 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5918 }
5919}
5920
5921void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005922 std::map<std::string, std::set<cricket::MediaType>>
5923 media_types_by_transport_name;
5924 for (auto transceiver : transceivers_) {
5925 if (transceiver->internal()->channel()) {
5926 const std::string& transport_name =
5927 transceiver->internal()->channel()->transport_name();
5928 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005929 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005930 }
Steve Anton75737c02017-11-06 10:37:17 -08005931 }
5932 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005933 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5934 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005935 }
Zhi Huange830e682018-03-30 10:48:35 -07005936
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005937 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005938 if (transport_name) {
5939 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08005940 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005941 }
Zhi Huange830e682018-03-30 10:48:35 -07005942
Steve Antonc7b964c2018-02-01 14:39:45 -08005943 for (const auto& entry : media_types_by_transport_name) {
5944 const std::string& transport_name = entry.first;
5945 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005946 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005947 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005948 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005949 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005950 }
5951 }
5952}
5953// Walk through the ConnectionInfos to gather best connection usage
5954// for IPv4 and IPv6.
5955void PeerConnection::ReportBestConnectionState(
5956 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005957 for (const cricket::TransportChannelStats& channel_stats :
5958 stats.channel_stats) {
5959 for (const cricket::ConnectionInfo& connection_info :
5960 channel_stats.connection_infos) {
5961 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005962 continue;
5963 }
5964
Steve Antonc7b964c2018-02-01 14:39:45 -08005965 const cricket::Candidate& local = connection_info.local_candidate;
5966 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005967
5968 // Increment the counter for IceCandidatePairType.
5969 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5970 (local.type() == RELAY_PORT_TYPE &&
5971 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005972 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
5973 GetIceCandidatePairCounter(local, remote),
5974 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08005975 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005976 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
5977 GetIceCandidatePairCounter(local, remote),
5978 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08005979 } else {
5980 RTC_CHECK(0);
5981 }
Steve Anton75737c02017-11-06 10:37:17 -08005982
5983 // Increment the counter for IP type.
5984 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005985 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
5986 kBestConnections_IPv4,
5987 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08005988 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005989 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
5990 kBestConnections_IPv6,
5991 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08005992 } else {
5993 RTC_CHECK(0);
5994 }
5995
5996 return;
5997 }
5998 }
5999}
6000
6001void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006002 const cricket::TransportStats& stats,
6003 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006004 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6005 return;
6006 }
6007
6008 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6009 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6010 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6011 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6012 return;
6013 }
6014
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006015 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6016 for (cricket::MediaType media_type : media_types) {
6017 switch (media_type) {
6018 case cricket::MEDIA_TYPE_AUDIO:
6019 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6020 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6021 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6022 break;
6023 case cricket::MEDIA_TYPE_VIDEO:
6024 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6025 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6026 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6027 break;
6028 case cricket::MEDIA_TYPE_DATA:
6029 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6030 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6031 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6032 break;
6033 default:
6034 RTC_NOTREACHED();
6035 continue;
6036 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006037 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006038 }
6039
6040 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6041 for (cricket::MediaType media_type : media_types) {
6042 switch (media_type) {
6043 case cricket::MEDIA_TYPE_AUDIO:
6044 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6045 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6046 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6047 break;
6048 case cricket::MEDIA_TYPE_VIDEO:
6049 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6050 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6051 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6052 break;
6053 case cricket::MEDIA_TYPE_DATA:
6054 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6055 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6056 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6057 break;
6058 default:
6059 RTC_NOTREACHED();
6060 continue;
6061 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006062 }
Steve Anton75737c02017-11-06 10:37:17 -08006063 }
6064}
6065
6066void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6067 RTC_DCHECK(worker_thread()->IsCurrent());
6068 RTC_DCHECK(call_);
6069 call_->OnSentPacket(sent_packet);
6070}
6071
6072const std::string PeerConnection::GetTransportName(
6073 const std::string& content_name) {
6074 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006075 if (channel) {
6076 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006077 }
Steve Anton6fec8802017-12-04 10:37:29 -08006078 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006079 RTC_DCHECK(sctp_mid_);
6080 if (content_name == *sctp_mid_) {
6081 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006082 }
6083 }
6084 // Return an empty string if failed to retrieve the transport name.
6085 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006086}
6087
Steve Anton6fec8802017-12-04 10:37:29 -08006088void PeerConnection::DestroyTransceiverChannel(
6089 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6090 transceiver) {
6091 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006092
Steve Anton6fec8802017-12-04 10:37:29 -08006093 cricket::BaseChannel* channel = transceiver->internal()->channel();
6094 if (channel) {
6095 transceiver->internal()->SetChannel(nullptr);
6096 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006097 }
6098}
6099
6100void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006101 if (rtp_data_channel_) {
6102 OnDataChannelDestroyed();
6103 DestroyBaseChannel(rtp_data_channel_);
6104 rtp_data_channel_ = nullptr;
6105 }
6106
6107 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6108 // grab a reference to this PeerConnection. If this is called from the
6109 // PeerConnection destructor, the RefCountedObject vtable will have already
6110 // been destroyed (since it is a subclass of PeerConnection) and using
6111 // rtc::Bind will cause "Pure virtual function called" error to appear.
6112
6113 if (sctp_transport_) {
6114 OnDataChannelDestroyed();
6115 network_thread()->Invoke<void>(RTC_FROM_HERE,
6116 [this] { DestroySctpTransport_n(); });
6117 }
6118}
6119
6120void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6121 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006122 switch (channel->media_type()) {
6123 case cricket::MEDIA_TYPE_AUDIO:
6124 channel_manager()->DestroyVoiceChannel(
6125 static_cast<cricket::VoiceChannel*>(channel));
6126 break;
6127 case cricket::MEDIA_TYPE_VIDEO:
6128 channel_manager()->DestroyVideoChannel(
6129 static_cast<cricket::VideoChannel*>(channel));
6130 break;
6131 case cricket::MEDIA_TYPE_DATA:
6132 channel_manager()->DestroyRtpDataChannel(
6133 static_cast<cricket::RtpDataChannel*>(channel));
6134 break;
6135 default:
6136 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6137 break;
6138 }
Zhi Huange830e682018-03-30 10:48:35 -07006139}
Steve Anton6fec8802017-12-04 10:37:29 -08006140
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006141bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006142 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006143 RtpTransportInternal* rtp_transport,
6144 cricket::DtlsTransportInternal* dtls_transport) {
6145 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006146 auto base_channel = GetChannel(mid);
6147 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006148 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006149 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006150 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006151 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006152 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006153 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006154}
6155
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006156PeerConnectionObserver* PeerConnection::Observer() const {
6157 // In earlier production code, the pointer was not cleared on close,
6158 // which might have led to undefined behavior if the observer was not
6159 // deallocated, or strange crashes if it was.
6160 // We use CHECK in order to catch such behavior if it exists.
6161 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6162 RTC_CHECK(observer_);
6163 return observer_;
6164}
6165
Harald Alvestrand89061872018-01-02 14:08:34 +01006166void PeerConnection::ClearStatsCache() {
6167 if (stats_collector_) {
6168 stats_collector_->ClearCachedStatsReport();
6169 }
6170}
6171
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006172void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonbb192762018-08-31 11:57:02 -07006173 async_invoker_.AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(),
6174 [this] { ReportUsagePattern(); });
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006175}
6176
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006177} // namespace webrtc