blob: 6c543f90ef85e3041575bcfd80910c0e8ae4ab3c [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
Steve Antonad182762018-09-05 20:22:40 +0000103enum {
104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
105 MSG_SET_SESSIONDESCRIPTION_FAILED,
106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
107 MSG_GETSTATS,
108 MSG_FREE_DATACHANNELS,
109 MSG_REPORT_USAGE_PATTERN,
110};
111
Harald Alvestrand19793842018-06-25 12:03:50 +0200112static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
113
Steve Antonad182762018-09-05 20:22:40 +0000114struct SetSessionDescriptionMsg : public rtc::MessageData {
115 explicit SetSessionDescriptionMsg(
116 webrtc::SetSessionDescriptionObserver* observer)
117 : observer(observer) {}
118
119 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
120 RTCError error;
121};
122
123struct CreateSessionDescriptionMsg : public rtc::MessageData {
124 explicit CreateSessionDescriptionMsg(
125 webrtc::CreateSessionDescriptionObserver* observer)
126 : observer(observer) {}
127
128 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
129 RTCError error;
130};
131
132struct GetStatsMsg : public rtc::MessageData {
133 GetStatsMsg(webrtc::StatsObserver* observer,
134 webrtc::MediaStreamTrackInterface* track)
135 : observer(observer), track(track) {}
136 rtc::scoped_refptr<webrtc::StatsObserver> observer;
137 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
138};
139
deadbeefab9b2d12015-10-14 11:33:11 -0700140// Check if we can send |new_stream| on a PeerConnection.
141bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
142 webrtc::MediaStreamInterface* new_stream) {
143 if (!new_stream || !current_streams) {
144 return false;
145 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700146 if (current_streams->find(new_stream->id()) != nullptr) {
147 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100148 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700149 return false;
150 }
151 return true;
152}
153
deadbeef5e97fb52015-10-15 12:49:08 -0700154// If the direction is "recvonly" or "inactive", treat the description
155// as containing no streams.
156// See: https://code.google.com/p/webrtc/issues/detail?id=5054
157std::vector<cricket::StreamParams> GetActiveStreams(
158 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800159 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700160 ? desc->streams()
161 : std::vector<cricket::StreamParams>();
162}
163
deadbeefab9b2d12015-10-14 11:33:11 -0700164bool IsValidOfferToReceiveMedia(int value) {
165 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
166 return (value >= Options::kUndefined) &&
167 (value <= Options::kMaxOfferToReceiveMedia);
168}
169
zhihuang1c378ed2017-08-17 14:10:50 -0700170// Add options to |[audio/video]_media_description_options| from |senders|.
171void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700172 const std::vector<rtc::scoped_refptr<
173 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700174 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200175 cricket::MediaDescriptionOptions* video_media_description_options,
176 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700177 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700178 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
179 if (audio_media_description_options) {
180 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700181 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700182 }
183 } else {
184 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
185 if (video_media_description_options) {
186 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200187 sender->id(), sender->internal()->stream_ids(),
188 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700189 }
190 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700191 }
zhihuang1c378ed2017-08-17 14:10:50 -0700192}
olka3c747662017-08-17 06:50:32 -0700193
zhihuang1c378ed2017-08-17 14:10:50 -0700194// Add options to |session_options| from |rtp_data_channels|.
195void AddRtpDataChannelOptions(
196 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
197 rtp_data_channels,
198 cricket::MediaDescriptionOptions* data_media_description_options) {
199 if (!data_media_description_options) {
200 return;
201 }
deadbeefab9b2d12015-10-14 11:33:11 -0700202 // Check for data channels.
203 for (const auto& kv : rtp_data_channels) {
204 const DataChannel* channel = kv.second;
205 if (channel->state() == DataChannel::kConnecting ||
206 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700207 // Legacy RTP data channels are signaled with the track/stream ID set to
208 // the data channel's label.
209 data_media_description_options->AddRtpDataChannel(channel->label(),
210 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700211 }
212 }
213}
214
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700215uint32_t ConvertIceTransportTypeToCandidateFilter(
216 PeerConnectionInterface::IceTransportsType type) {
217 switch (type) {
218 case PeerConnectionInterface::kNone:
219 return cricket::CF_NONE;
220 case PeerConnectionInterface::kRelay:
221 return cricket::CF_RELAY;
222 case PeerConnectionInterface::kNoHost:
223 return (cricket::CF_ALL & ~cricket::CF_HOST);
224 case PeerConnectionInterface::kAll:
225 return cricket::CF_ALL;
226 default:
nissec80e7412017-01-11 05:56:46 -0800227 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700228 }
229 return cricket::CF_NONE;
230}
231
deadbeef293e9262017-01-11 12:28:30 -0800232// Helper to set an error and return from a method.
233bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
234 if (error) {
235 error->set_type(type);
236 }
237 return type == webrtc::RTCErrorType::NONE;
238}
239
Steve Anton038834f2017-07-14 15:59:59 -0700240bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700241 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700242 if (error_out) {
243 *error_out = std::move(error);
244 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700245 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700246}
247
Steve Antonba818672017-11-06 10:21:57 -0800248std::string GetSignalingStateString(
249 PeerConnectionInterface::SignalingState state) {
250 switch (state) {
251 case PeerConnectionInterface::kStable:
252 return "kStable";
253 case PeerConnectionInterface::kHaveLocalOffer:
254 return "kHaveLocalOffer";
255 case PeerConnectionInterface::kHaveLocalPrAnswer:
256 return "kHavePrAnswer";
257 case PeerConnectionInterface::kHaveRemoteOffer:
258 return "kHaveRemoteOffer";
259 case PeerConnectionInterface::kHaveRemotePrAnswer:
260 return "kHaveRemotePrAnswer";
261 case PeerConnectionInterface::kClosed:
262 return "kClosed";
263 }
264 RTC_NOTREACHED();
265 return "";
266}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700267
Steve Anton75737c02017-11-06 10:37:17 -0800268IceCandidatePairType GetIceCandidatePairCounter(
269 const cricket::Candidate& local,
270 const cricket::Candidate& remote) {
271 const auto& l = local.type();
272 const auto& r = remote.type();
273 const auto& host = LOCAL_PORT_TYPE;
274 const auto& srflx = STUN_PORT_TYPE;
275 const auto& relay = RELAY_PORT_TYPE;
276 const auto& prflx = PRFLX_PORT_TYPE;
277 if (l == host && r == host) {
278 bool local_private = IPIsPrivate(local.address().ipaddr());
279 bool remote_private = IPIsPrivate(remote.address().ipaddr());
280 if (local_private) {
281 if (remote_private) {
282 return kIceCandidatePairHostPrivateHostPrivate;
283 } else {
284 return kIceCandidatePairHostPrivateHostPublic;
285 }
286 } else {
287 if (remote_private) {
288 return kIceCandidatePairHostPublicHostPrivate;
289 } else {
290 return kIceCandidatePairHostPublicHostPublic;
291 }
292 }
293 }
294 if (l == host && r == srflx)
295 return kIceCandidatePairHostSrflx;
296 if (l == host && r == relay)
297 return kIceCandidatePairHostRelay;
298 if (l == host && r == prflx)
299 return kIceCandidatePairHostPrflx;
300 if (l == srflx && r == host)
301 return kIceCandidatePairSrflxHost;
302 if (l == srflx && r == srflx)
303 return kIceCandidatePairSrflxSrflx;
304 if (l == srflx && r == relay)
305 return kIceCandidatePairSrflxRelay;
306 if (l == srflx && r == prflx)
307 return kIceCandidatePairSrflxPrflx;
308 if (l == relay && r == host)
309 return kIceCandidatePairRelayHost;
310 if (l == relay && r == srflx)
311 return kIceCandidatePairRelaySrflx;
312 if (l == relay && r == relay)
313 return kIceCandidatePairRelayRelay;
314 if (l == relay && r == prflx)
315 return kIceCandidatePairRelayPrflx;
316 if (l == prflx && r == host)
317 return kIceCandidatePairPrflxHost;
318 if (l == prflx && r == srflx)
319 return kIceCandidatePairPrflxSrflx;
320 if (l == prflx && r == relay)
321 return kIceCandidatePairPrflxRelay;
322 return kIceCandidatePairMax;
323}
324
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800325// Logic to decide if an m= section can be recycled. This means that the new
326// m= section is not rejected, but the old local or remote m= section is
327// rejected. |old_content_one| and |old_content_two| refer to the m= section
328// of the old remote and old local descriptions in no particular order.
329// We need to check both the old local and remote because either
330// could be the most current from the latest negotation.
331bool IsMediaSectionBeingRecycled(SdpType type,
332 const ContentInfo& content,
333 const ContentInfo* old_content_one,
334 const ContentInfo* old_content_two) {
335 return type == SdpType::kOffer && !content.rejected &&
336 ((old_content_one && old_content_one->rejected) ||
337 (old_content_two && old_content_two->rejected));
338}
339
Steve Anton75737c02017-11-06 10:37:17 -0800340// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800341// |current_desc|. The number of m= sections in |new_desc| should be no
342// less than |current_desc|. In the case of checking an answer's
343// |new_desc|, the |current_desc| is the last offer that was set as the
344// local or remote. In the case of checking an offer's |new_desc| we
345// check against the local and remote descriptions stored from the last
346// negotiation, because either of these could be the most up to date for
347// possible rejected m sections. These are the |current_desc| and
348// |secondary_current_desc|.
349bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
350 const SessionDescription* secondary_current_desc,
351 const SessionDescription& new_desc,
352 const SdpType type) {
353 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800354 return false;
355 }
356
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800357 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
358 const cricket::ContentInfo* secondary_content_info = nullptr;
359 if (secondary_current_desc &&
360 i < secondary_current_desc->contents().size()) {
361 secondary_content_info = &secondary_current_desc->contents()[i];
362 }
363 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
364 &current_desc.contents()[i],
365 secondary_content_info)) {
366 // For new offer descriptions, if the media section can be recycled, it's
367 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800368 continue;
369 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800371 return false;
372 }
373 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800374 new_desc.contents()[i].media_description();
375 const MediaContentDescription* current_desc_mdesc =
376 current_desc.contents()[i].media_description();
377 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800378 return false;
379 }
380 }
381 return true;
382}
383
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800384bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
385 const SessionDescription& desc2) {
386 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800387}
388
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700389void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
390 cricket::MediaType media_type) {
391 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
392 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100393 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
394 KeyExchangeProtocolMedia>
395 proto_media_counter_map = {
396 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
397 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
398 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
399 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
400 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
401 kEnumCounterKeyProtocolMediaTypeDtlsData},
402 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
403 kEnumCounterKeyProtocolMediaTypeSdesAudio},
404 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
405 kEnumCounterKeyProtocolMediaTypeSdesVideo},
406 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
407 kEnumCounterKeyProtocolMediaTypeSdesData}};
408
409 auto it = proto_media_counter_map.find({protocol_type, media_type});
410 if (it != proto_media_counter_map.end()) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700411 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
412 it->second, kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100413 }
414}
415
Harald Alvestrand76829d72018-07-18 23:24:36 +0200416void NoteAddIceCandidateResult(int result) {
417 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
418 kAddIceCandidateMax);
419}
420
Steve Anton75737c02017-11-06 10:37:17 -0800421// Checks that each non-rejected content has SDES crypto keys or a DTLS
422// fingerprint, unless it's in a BUNDLE group, in which case only the
423// BUNDLE-tag section (first media section/description in the BUNDLE group)
424// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
425// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
426// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700427RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800428 const cricket::ContentGroup* bundle =
429 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800430 for (const cricket::ContentInfo& content_info : desc->contents()) {
431 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800432 continue;
433 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100434 // Note what media is used with each crypto protocol, for all sections.
435 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
436 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700437 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
470 }
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800482 continue;
483 }
Steve Anton8a006912017-12-04 15:25:56 -0800484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Seth Hampson5b4f0752018-04-02 16:31:36 -0700603std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
604 std::string output = "streams=[";
605 const char* separator = "";
606 for (const auto& stream_id : stream_ids) {
607 output.append(separator).append(stream_id);
608 separator = ", ";
609 }
610 output.append("]");
611 return output;
612}
613
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200614absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700615 int rtc_configuration_parameter) {
616 if (rtc_configuration_parameter ==
617 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200618 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700619 }
620 return rtc_configuration_parameter;
621}
622
Steve Anton75737c02017-11-06 10:37:17 -0800623} // namespace
624
Henrik Boström31638672017-11-23 17:48:32 +0100625// Upon completion, posts a task to execute the callback of the
626// SetSessionDescriptionObserver asynchronously on the same thread. At this
627// point, the state of the peer connection might no longer reflect the effects
628// of the SetRemoteDescription operation, as the peer connection could have been
629// modified during the post.
630// TODO(hbos): Remove this class once we remove the version of
631// PeerConnectionInterface::SetRemoteDescription() that takes a
632// SetSessionDescriptionObserver as an argument.
633class PeerConnection::SetRemoteDescriptionObserverAdapter
634 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
635 public:
636 SetRemoteDescriptionObserverAdapter(
637 rtc::scoped_refptr<PeerConnection> pc,
638 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
639 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
640
641 // SetRemoteDescriptionObserverInterface implementation.
642 void OnSetRemoteDescriptionComplete(RTCError error) override {
643 if (error.ok())
644 pc_->PostSetSessionDescriptionSuccess(wrapper_);
645 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100646 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100647 }
648
649 private:
650 rtc::scoped_refptr<PeerConnection> pc_;
651 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
652};
653
deadbeef293e9262017-01-11 12:28:30 -0800654bool PeerConnectionInterface::RTCConfiguration::operator==(
655 const PeerConnectionInterface::RTCConfiguration& o) const {
656 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700657 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800658 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000659 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700660 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800661 BundlePolicy bundle_policy;
662 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700663 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
664 int ice_candidate_pool_size;
665 bool disable_ipv6;
666 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700667 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100668 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700669 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200670 absl::optional<int> screencast_min_bitrate;
671 absl::optional<bool> combined_audio_video_bwe;
672 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800673 TcpCandidatePolicy tcp_candidate_policy;
674 CandidateNetworkPolicy candidate_network_policy;
675 int audio_jitter_buffer_max_packets;
676 bool audio_jitter_buffer_fast_accelerate;
677 int ice_connection_receiving_timeout;
678 int ice_backup_candidate_pair_ping_interval;
679 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800680 bool prioritize_most_likely_ice_candidate_pairs;
681 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800682 bool prune_turn_ports;
683 bool presume_writable_when_fully_relayed;
684 bool enable_ice_renomination;
685 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200686 absl::optional<int> ice_check_interval_strong_connectivity;
687 absl::optional<int> ice_check_interval_weak_connectivity;
688 absl::optional<int> ice_check_min_interval;
689 absl::optional<int> ice_unwritable_timeout;
690 absl::optional<int> ice_unwritable_min_checks;
691 absl::optional<int> stun_candidate_keepalive_interval;
692 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200693 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800694 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200695 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700696 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800697 };
698 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
699 "Did you add something to RTCConfiguration and forget to "
700 "update operator==?");
701 return type == o.type && servers == o.servers &&
702 bundle_policy == o.bundle_policy &&
703 rtcp_mux_policy == o.rtcp_mux_policy &&
704 tcp_candidate_policy == o.tcp_candidate_policy &&
705 candidate_network_policy == o.candidate_network_policy &&
706 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
707 audio_jitter_buffer_fast_accelerate ==
708 o.audio_jitter_buffer_fast_accelerate &&
709 ice_connection_receiving_timeout ==
710 o.ice_connection_receiving_timeout &&
711 ice_backup_candidate_pair_ping_interval ==
712 o.ice_backup_candidate_pair_ping_interval &&
713 continual_gathering_policy == o.continual_gathering_policy &&
714 certificates == o.certificates &&
715 prioritize_most_likely_ice_candidate_pairs ==
716 o.prioritize_most_likely_ice_candidate_pairs &&
717 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800718 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700719 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100720 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800721 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800722 screencast_min_bitrate == o.screencast_min_bitrate &&
723 combined_audio_video_bwe == o.combined_audio_video_bwe &&
724 enable_dtls_srtp == o.enable_dtls_srtp &&
725 ice_candidate_pool_size == o.ice_candidate_pool_size &&
726 prune_turn_ports == o.prune_turn_ports &&
727 presume_writable_when_fully_relayed ==
728 o.presume_writable_when_fully_relayed &&
729 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800730 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800731 ice_check_interval_strong_connectivity ==
732 o.ice_check_interval_strong_connectivity &&
733 ice_check_interval_weak_connectivity ==
734 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700735 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700736 ice_unwritable_timeout == o.ice_unwritable_timeout &&
737 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800738 stun_candidate_keepalive_interval ==
739 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200740 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800741 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800742 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700743 network_preference == o.network_preference &&
744 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800745}
746
747bool PeerConnectionInterface::RTCConfiguration::operator!=(
748 const PeerConnectionInterface::RTCConfiguration& o) const {
749 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800750}
751
zhihuang8f65cdf2016-05-06 18:40:30 -0700752// Generate a RTCP CNAME when a PeerConnection is created.
753std::string GenerateRtcpCname() {
754 std::string cname;
755 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100756 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800757 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700758 }
759 return cname;
760}
761
zhihuang1c378ed2017-08-17 14:10:50 -0700762bool ValidateOfferAnswerOptions(
763 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
764 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
765 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700766}
767
zhihuang1c378ed2017-08-17 14:10:50 -0700768// From |rtc_options|, fill parts of |session_options| shared by all generated
769// m= sections (in other words, nothing that involves a map/array).
770void ExtractSharedMediaSessionOptions(
771 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
772 cricket::MediaSessionOptions* session_options) {
773 session_options->vad_enabled = rtc_options.voice_activity_detection;
774 session_options->bundle_enabled = rtc_options.use_rtp_mux;
775}
zhihuanga77e6bb2017-08-14 18:17:48 -0700776
zhihuang38ede132017-06-15 12:52:32 -0700777PeerConnection::PeerConnection(PeerConnectionFactory* factory,
778 std::unique_ptr<RtcEventLog> event_log,
779 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700781 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700782 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700783 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700784 remote_streams_(StreamCollection::Create()),
785 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000786
787PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100788 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800789 RTC_DCHECK_RUN_ON(signaling_thread());
790
Steve Anton8af21862017-12-15 11:20:13 -0800791 // Need to stop transceivers before destroying the stats collector because
792 // AudioRtpSender has a reference to the StatsCollector it will update when
793 // stopping.
794 for (auto transceiver : transceivers_) {
795 transceiver->Stop();
796 }
Steve Anton4171afb2017-11-20 10:20:22 -0800797
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700798 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800799 if (stats_collector_) {
800 stats_collector_->WaitForPendingRequest();
801 stats_collector_ = nullptr;
802 }
Steve Anton75737c02017-11-06 10:37:17 -0800803
Steve Anton8af21862017-12-15 11:20:13 -0800804 // Don't destroy BaseChannels until after stats has been cleaned up so that
805 // the last stats request can still read from the channels.
806 DestroyAllChannels();
807
Mirko Bonadei675513b2017-11-09 11:09:25 +0100808 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800809
810 webrtc_session_desc_factory_.reset();
811 sctp_invoker_.reset();
812 sctp_factory_.reset();
813 transport_controller_.reset();
814
deadbeef91dd5672016-05-18 16:55:30 -0700815 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700816 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700817 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700818 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700819 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700820 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800821 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700822 event_log_.reset();
823 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000824}
825
Steve Anton8af21862017-12-15 11:20:13 -0800826void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800827 // Destroy video channels first since they may have a pointer to a voice
828 // channel.
829 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800830 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800831 DestroyTransceiverChannel(transceiver);
832 }
833 }
834 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800835 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800836 DestroyTransceiverChannel(transceiver);
837 }
838 }
839 DestroyDataChannel();
840}
841
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000843 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700844 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100845 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700846
847 RTCError config_error = ValidateConfiguration(configuration);
848 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100849 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700850 return false;
851 }
852
Benjamin Wrightcab58882018-05-02 15:12:47 -0700853 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100854 RTC_LOG(LS_ERROR)
855 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100856 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800857 return false;
858 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200859
Benjamin Wrightcab58882018-05-02 15:12:47 -0700860 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800861 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100862 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100863 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800864 return false;
865 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700866
Benjamin Wrightcab58882018-05-02 15:12:47 -0700867 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700868 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700869 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700870 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800871
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200872 cricket::ServerAddresses stun_servers;
873 std::vector<cricket::RelayServerConfig> turn_servers;
874
875 RTCErrorType parse_error =
876 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
877 if (parse_error != RTCErrorType::NONE) {
878 return false;
879 }
880
deadbeef91dd5672016-05-18 16:55:30 -0700881 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700882 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700883 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200884 RTC_FROM_HERE,
885 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
886 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887 return false;
888 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200889 // If initialization was successful, note if STUN or TURN servers
890 // were supplied.
891 if (!stun_servers.empty()) {
892 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
893 }
894 if (!turn_servers.empty()) {
895 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
896 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700898 // Send information about IPv4/IPv6 status.
899 PeerConnectionAddressFamilyCounter address_family;
900 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
901 address_family = kPeerConnection_IPv6;
902 } else {
903 address_family = kPeerConnection_IPv4;
904 }
905 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
906 kPeerConnectionAddressFamilyCounter_Max);
907
Zhi Huange830e682018-03-30 10:48:35 -0700908 const PeerConnectionFactoryInterface::Options& options = factory_->options();
909
Steve Anton75737c02017-11-06 10:37:17 -0800910 // RFC 3264: The numeric value of the session id and version in the
911 // o line MUST be representable with a "64 bit signed integer".
912 // Due to this constraint session id |session_id_| is max limited to
913 // LLONG_MAX.
914 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700915 JsepTransportController::Config config;
916 config.redetermine_role_on_ice_restart =
917 configuration.redetermine_role_on_ice_restart;
918 config.ssl_max_version = factory_->options().ssl_max_version;
919 config.disable_encryption = options.disable_encryption;
920 config.bundle_policy = configuration.bundle_policy;
921 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
922 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700923 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700924 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700925#if defined(ENABLE_EXTERNAL_AUTH)
926 config.enable_external_auth = true;
927#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700928 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700929 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700930 signaling_thread(), network_thread(), port_allocator_.get(),
931 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700932 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800933 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700934 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800935 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700936 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800937 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700938 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800939 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
940 transport_controller_->SignalDtlsHandshakeError.connect(
941 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
942
943 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700944
deadbeefab9b2d12015-10-14 11:33:11 -0700945 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700946 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947
Steve Antonba818672017-11-06 10:21:57 -0800948 configuration_ = configuration;
949
Steve Anton75737c02017-11-06 10:37:17 -0800950 // Obtain a certificate from RTCConfiguration if any were provided (optional).
951 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
952 if (!configuration.certificates.empty()) {
953 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
954 // just picking the first one. The decision should be made based on the DTLS
955 // handshake. The DTLS negotiations need to know about all certificates.
956 certificate = configuration.certificates[0];
957 }
958
Steve Antond25da372017-11-06 14:50:29 -0800959 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800960
961 if (options.disable_encryption) {
962 dtls_enabled_ = false;
963 } else {
964 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700965 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800966 // |configuration| can override the default |dtls_enabled_| value.
967 if (configuration.enable_dtls_srtp) {
968 dtls_enabled_ = *(configuration.enable_dtls_srtp);
969 }
970 }
971
972 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
973 // It takes precendence over the disable_sctp_data_channels
974 // PeerConnectionFactoryInterface::Options.
975 if (configuration.enable_rtp_data_channel) {
976 data_channel_type_ = cricket::DCT_RTP;
977 } else {
978 // DTLS has to be enabled to use SCTP.
979 if (!options.disable_sctp_data_channels && dtls_enabled_) {
980 data_channel_type_ = cricket::DCT_SCTP;
981 }
982 }
983
984 video_options_.screencast_min_bitrate_kbps =
985 configuration.screencast_min_bitrate;
986 audio_options_.combined_audio_video_bwe =
987 configuration.combined_audio_video_bwe;
988
989 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100990 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800991
992 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100993 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800994
995 // Whether the certificate generator/certificate is null or not determines
996 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
997 // the right instructions by clearing the variables if needed.
998 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -0700999 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001000 certificate = nullptr;
1001 } else if (certificate) {
1002 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001003 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001004 }
1005
1006 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1007 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001008 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001009 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1010 this, &PeerConnection::OnCertificateReady);
1011
1012 if (options.disable_encryption) {
1013 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1014 }
1015
1016 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1017 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018
Steve Anton4171afb2017-11-20 10:20:22 -08001019 // Add default audio/video transceivers for Plan B SDP.
1020 if (!IsUnifiedPlan()) {
1021 transceivers_.push_back(
1022 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1023 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1024 transceivers_.push_back(
1025 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1026 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1027 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001028 int delay_ms =
1029 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001030 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1031 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032 return true;
1033}
1034
Steve Anton038834f2017-07-14 15:59:59 -07001035RTCError PeerConnection::ValidateConfiguration(
1036 const RTCConfiguration& config) const {
1037 if (config.ice_regather_interval_range &&
1038 config.continual_gathering_policy == GATHER_ONCE) {
1039 return RTCError(RTCErrorType::INVALID_PARAMETER,
1040 "ice_regather_interval_range specified but continual "
1041 "gathering policy is GATHER_ONCE");
1042 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001043 auto result =
1044 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1045 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001046}
1047
Yves Gerey665174f2018-06-19 15:03:05 +02001048rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001049 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1050 "Plan SdpSemantics. Please use GetSenders "
1051 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001052 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001053}
1054
Yves Gerey665174f2018-06-19 15:03:05 +02001055rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001056 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1057 "Plan SdpSemantics. Please use GetReceivers "
1058 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001059 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060}
1061
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001062bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001063 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1064 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001065 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066 if (IsClosed()) {
1067 return false;
1068 }
deadbeefab9b2d12015-10-14 11:33:11 -07001069 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001070 return false;
1071 }
deadbeefab9b2d12015-10-14 11:33:11 -07001072
1073 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001074 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1075 observer->SignalAudioTrackAdded.connect(this,
1076 &PeerConnection::OnAudioTrackAdded);
1077 observer->SignalAudioTrackRemoved.connect(
1078 this, &PeerConnection::OnAudioTrackRemoved);
1079 observer->SignalVideoTrackAdded.connect(this,
1080 &PeerConnection::OnVideoTrackAdded);
1081 observer->SignalVideoTrackRemoved.connect(
1082 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001083 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001084
deadbeefab9b2d12015-10-14 11:33:11 -07001085 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001086 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001087 }
1088 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001089 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001090 }
1091
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001092 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001093 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094 return true;
1095}
1096
1097void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001098 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1099 "Plan SdpSemantics. Please use RemoveTrack "
1100 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001101 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001102 if (!IsClosed()) {
1103 for (const auto& track : local_stream->GetAudioTracks()) {
1104 RemoveAudioTrack(track.get(), local_stream);
1105 }
1106 for (const auto& track : local_stream->GetVideoTracks()) {
1107 RemoveVideoTrack(track.get(), local_stream);
1108 }
deadbeefab9b2d12015-10-14 11:33:11 -07001109 }
deadbeefab9b2d12015-10-14 11:33:11 -07001110 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001111 stream_observers_.erase(
1112 std::remove_if(
1113 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001114 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001115 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001116 }),
1117 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001118
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119 if (IsClosed()) {
1120 return;
1121 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001122 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001123}
1124
Steve Anton2d6c76a2018-01-05 17:10:52 -08001125RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001126 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001127 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001128 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001129 if (!track) {
1130 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1131 }
1132 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1133 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1134 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1135 "Track has invalid kind: " + track->kind());
1136 }
Steve Antonf9381f02017-12-14 10:23:57 -08001137 if (IsClosed()) {
1138 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1139 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001140 }
Steve Anton4171afb2017-11-20 10:20:22 -08001141 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001142 LOG_AND_RETURN_ERROR(
1143 RTCErrorType::INVALID_PARAMETER,
1144 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001145 }
Steve Antonf9381f02017-12-14 10:23:57 -08001146 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001147 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1148 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001149 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001150 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001151 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001152 }
1153 return sender_or_error;
1154}
deadbeefe1f9d832016-01-14 15:35:42 -08001155
Steve Antonf9381f02017-12-14 10:23:57 -08001156RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1157PeerConnection::AddTrackPlanB(
1158 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001159 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001160 if (stream_ids.size() > 1u) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1162 "AddTrack with more than one stream is not "
1163 "supported with Plan B semantics.");
1164 }
1165 std::vector<std::string> adjusted_stream_ids = stream_ids;
1166 if (adjusted_stream_ids.empty()) {
1167 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1168 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001169 cricket::MediaType media_type =
1170 (track->kind() == MediaStreamTrackInterface::kAudioKind
1171 ? cricket::MEDIA_TYPE_AUDIO
1172 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001173 auto new_sender =
1174 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001175 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001176 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001177 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001178 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001179 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001180 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001181 if (sender_info) {
1182 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001183 }
Steve Antonf9381f02017-12-14 10:23:57 -08001184 } else {
1185 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001186 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001187 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001188 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001189 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001190 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001191 if (sender_info) {
1192 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001193 }
deadbeefe1f9d832016-01-14 15:35:42 -08001194 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001195 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001196}
deadbeefe1f9d832016-01-14 15:35:42 -08001197
Steve Antonf9381f02017-12-14 10:23:57 -08001198RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1199PeerConnection::AddTrackUnifiedPlan(
1200 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001201 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001202 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1203 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001204 RTC_LOG(LS_INFO) << "Reusing an existing "
1205 << cricket::MediaTypeToString(transceiver->media_type())
1206 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001207 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001208 transceiver->internal()->set_direction(
1209 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001210 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001211 transceiver->internal()->set_direction(
1212 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001213 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001214 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001215 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001216 } else {
1217 cricket::MediaType media_type =
1218 (track->kind() == MediaStreamTrackInterface::kAudioKind
1219 ? cricket::MEDIA_TYPE_AUDIO
1220 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001221 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1222 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001223 std::string sender_id = track->id();
1224 // Avoid creating a sender with an existing ID by generating a random ID.
1225 // This can happen if this is the second time AddTrack has created a sender
1226 // for this track.
1227 if (FindSenderById(sender_id)) {
1228 sender_id = rtc::CreateRandomUuid();
1229 }
1230 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001231 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1232 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001233 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001234 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001235 }
Steve Antonf9381f02017-12-14 10:23:57 -08001236 return transceiver->sender();
1237}
1238
1239rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1240PeerConnection::FindFirstTransceiverForAddedTrack(
1241 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1242 RTC_DCHECK(track);
1243 for (auto transceiver : transceivers_) {
1244 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001245 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001246 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001247 !transceiver->internal()->has_ever_been_used_to_send() &&
1248 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001249 return transceiver;
1250 }
1251 }
1252 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001253}
1254
1255bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1256 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001257 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001258}
1259
Steve Anton24db5732018-07-23 10:27:33 -07001260RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001261 rtc::scoped_refptr<RtpSenderInterface> sender) {
1262 if (!sender) {
1263 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1264 }
deadbeefe1f9d832016-01-14 15:35:42 -08001265 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001266 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1267 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001268 }
Steve Antonf9381f02017-12-14 10:23:57 -08001269 if (IsUnifiedPlan()) {
1270 auto transceiver = FindTransceiverBySender(sender);
1271 if (!transceiver || !sender->track()) {
1272 return RTCError::OK();
1273 }
1274 sender->SetTrack(nullptr);
1275 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001276 transceiver->internal()->set_direction(
1277 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001278 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001279 transceiver->internal()->set_direction(
1280 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001281 }
Steve Anton4171afb2017-11-20 10:20:22 -08001282 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001283 bool removed;
1284 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1285 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1286 } else {
1287 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1288 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1289 }
1290 if (!removed) {
1291 LOG_AND_RETURN_ERROR(
1292 RTCErrorType::INVALID_PARAMETER,
1293 "Couldn't find sender " + sender->id() + " to remove.");
1294 }
Steve Anton4171afb2017-11-20 10:20:22 -08001295 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001296 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001297 return RTCError::OK();
1298}
1299
1300rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1301PeerConnection::FindTransceiverBySender(
1302 rtc::scoped_refptr<RtpSenderInterface> sender) {
1303 for (auto transceiver : transceivers_) {
1304 if (transceiver->sender() == sender) {
1305 return transceiver;
1306 }
1307 }
1308 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001309}
1310
Steve Anton9158ef62017-11-27 13:01:52 -08001311RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1312PeerConnection::AddTransceiver(
1313 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1314 return AddTransceiver(track, RtpTransceiverInit());
1315}
1316
1317RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1318PeerConnection::AddTransceiver(
1319 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1320 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001321 RTC_CHECK(IsUnifiedPlan())
1322 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001323 if (!track) {
1324 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1325 }
1326 cricket::MediaType media_type;
1327 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1328 media_type = cricket::MEDIA_TYPE_AUDIO;
1329 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1330 media_type = cricket::MEDIA_TYPE_VIDEO;
1331 } else {
1332 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1333 "Track kind is not audio or video");
1334 }
1335 return AddTransceiver(media_type, track, init);
1336}
1337
1338RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1339PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1340 return AddTransceiver(media_type, RtpTransceiverInit());
1341}
1342
1343RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1344PeerConnection::AddTransceiver(cricket::MediaType media_type,
1345 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001346 RTC_CHECK(IsUnifiedPlan())
1347 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001348 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1349 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1350 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1351 "media type is not audio or video");
1352 }
1353 return AddTransceiver(media_type, nullptr, init);
1354}
1355
1356RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1357PeerConnection::AddTransceiver(
1358 cricket::MediaType media_type,
1359 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001360 const RtpTransceiverInit& init,
1361 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001362 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1363 media_type == cricket::MEDIA_TYPE_VIDEO));
1364 if (track) {
1365 RTC_DCHECK_EQ(media_type,
1366 (track->kind() == MediaStreamTrackInterface::kAudioKind
1367 ? cricket::MEDIA_TYPE_AUDIO
1368 : cricket::MEDIA_TYPE_VIDEO));
1369 }
1370
1371 // TODO(bugs.webrtc.org/7600): Verify init.
1372
Steve Anton3d954a62018-04-02 11:27:23 -07001373 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1374 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001375 // Set the sender ID equal to the track ID if the track is specified unless
1376 // that sender ID is already in use.
1377 std::string sender_id =
1378 (track && !FindSenderById(track->id()) ? track->id()
1379 : rtc::CreateRandomUuid());
1380 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001381 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1382 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1383 transceiver->internal()->set_direction(init.direction);
1384
Steve Anton22da89f2018-01-25 13:58:07 -08001385 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001386 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001387 }
Steve Antonf9381f02017-12-14 10:23:57 -08001388
1389 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1390}
1391
Steve Anton02ee47c2018-01-10 16:26:06 -08001392rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1393PeerConnection::CreateSender(
1394 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001395 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001396 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001397 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001398 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001399 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1400 RTC_DCHECK(!track ||
1401 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1402 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1403 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001404 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001405 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001406 } else {
1407 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1408 RTC_DCHECK(!track ||
1409 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1410 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001411 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001412 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001413 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001414 bool set_track_succeeded = sender->SetTrack(track);
1415 RTC_DCHECK(set_track_succeeded);
1416 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001417 return sender;
1418}
1419
1420rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1421PeerConnection::CreateReceiver(cricket::MediaType media_type,
1422 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001423 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1424 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001425 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001426 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001427 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1428 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001429 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001430 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001431 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001432 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001433 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1434 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001435 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001436 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001437 return receiver;
1438}
1439
1440rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1441PeerConnection::CreateAndAddTransceiver(
1442 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1443 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1444 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001445 // Ensure that the new sender does not have an ID that is already in use by
1446 // another sender.
1447 // Allow receiver IDs to conflict since those come from remote SDP (which
1448 // could be invalid, but should not cause a crash).
1449 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001450 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1451 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001452 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001453 transceiver->internal()->SignalNegotiationNeeded.connect(
1454 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001455 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001456}
1457
Steve Anton52d86772018-02-20 15:48:12 -08001458void PeerConnection::OnNegotiationNeeded() {
1459 RTC_DCHECK_RUN_ON(signaling_thread());
1460 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001461 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001462}
1463
deadbeeffac06552015-11-25 11:26:01 -08001464rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001465 const std::string& kind,
1466 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001467 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1468 "Plan SdpSemantics. Please use AddTransceiver "
1469 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001470 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001471 if (IsClosed()) {
1472 return nullptr;
1473 }
Steve Anton4171afb2017-11-20 10:20:22 -08001474
Seth Hampson5b4f0752018-04-02 16:31:36 -07001475 // Internally we need to have one stream with Plan B semantics, so we
1476 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001477 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001478 if (stream_id.empty()) {
1479 stream_ids.push_back(rtc::CreateRandomUuid());
1480 RTC_LOG(LS_INFO)
1481 << "No stream_id specified for sender. Generated stream ID: "
1482 << stream_ids[0];
1483 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001484 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001485 }
1486
Steve Anton4171afb2017-11-20 10:20:22 -08001487 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001488 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001489 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001490 auto* audio_sender = new AudioRtpSender(
1491 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001492 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001493 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001494 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001495 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001496 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001497 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001498 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001499 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001500 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001501 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001502 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001503 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001504 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001505 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001506 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001507 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001508
deadbeefe1f9d832016-01-14 15:35:42 -08001509 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001510}
1511
deadbeef70ab1a12015-09-28 16:53:55 -07001512std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1513 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001514 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001515 for (auto sender : GetSendersInternal()) {
1516 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001517 }
1518 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001519}
1520
Steve Anton4171afb2017-11-20 10:20:22 -08001521std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1522PeerConnection::GetSendersInternal() const {
1523 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1524 all_senders;
1525 for (auto transceiver : transceivers_) {
1526 auto senders = transceiver->internal()->senders();
1527 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1528 }
1529 return all_senders;
1530}
1531
deadbeef70ab1a12015-09-28 16:53:55 -07001532std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1533PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001534 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001535 for (const auto& receiver : GetReceiversInternal()) {
1536 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001537 }
1538 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001539}
1540
Steve Anton4171afb2017-11-20 10:20:22 -08001541std::vector<
1542 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1543PeerConnection::GetReceiversInternal() const {
1544 std::vector<
1545 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1546 all_receivers;
1547 for (auto transceiver : transceivers_) {
1548 auto receivers = transceiver->internal()->receivers();
1549 all_receivers.insert(all_receivers.end(), receivers.begin(),
1550 receivers.end());
1551 }
1552 return all_receivers;
1553}
1554
Steve Anton9158ef62017-11-27 13:01:52 -08001555std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1556PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001557 RTC_CHECK(IsUnifiedPlan())
1558 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001559 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1560 for (auto transceiver : transceivers_) {
1561 all_transceivers.push_back(transceiver);
1562 }
1563 return all_transceivers;
1564}
1565
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001567 MediaStreamTrackInterface* track,
1568 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001569 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001570 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001571 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001572 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573 return false;
1574 }
1575
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001576 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001577 // The StatsCollector is used to tell if a track is valid because it may
1578 // remember tracks that the PeerConnection previously removed.
1579 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001580 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1581 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001582 return false;
1583 }
Steve Antonad182762018-09-05 20:22:40 +00001584 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1585 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 return true;
1587}
1588
hbos74e1a4f2016-09-15 23:33:01 -07001589void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001590 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001591 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001592 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001593 stats_collector_->GetStatsReport(callback);
1594}
1595
Henrik Boström1df1bf82018-03-20 13:24:20 +01001596void PeerConnection::GetStats(
1597 rtc::scoped_refptr<RtpSenderInterface> selector,
1598 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1599 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1600 RTC_DCHECK(callback);
1601 RTC_DCHECK(stats_collector_);
1602 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1603 if (selector) {
1604 for (const auto& proxy_transceiver : transceivers_) {
1605 for (const auto& proxy_sender :
1606 proxy_transceiver->internal()->senders()) {
1607 if (proxy_sender == selector) {
1608 internal_sender = proxy_sender->internal();
1609 break;
1610 }
1611 }
1612 if (internal_sender)
1613 break;
1614 }
1615 }
1616 // If there is no |internal_sender| then |selector| is either null or does not
1617 // belong to the PeerConnection (in Plan B, senders can be removed from the
1618 // PeerConnection). This means that "all the stats objects representing the
1619 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1620 // produces an empty stats report.
1621 stats_collector_->GetStatsReport(internal_sender, callback);
1622}
1623
1624void PeerConnection::GetStats(
1625 rtc::scoped_refptr<RtpReceiverInterface> selector,
1626 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1627 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1628 RTC_DCHECK(callback);
1629 RTC_DCHECK(stats_collector_);
1630 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1631 if (selector) {
1632 for (const auto& proxy_transceiver : transceivers_) {
1633 for (const auto& proxy_receiver :
1634 proxy_transceiver->internal()->receivers()) {
1635 if (proxy_receiver == selector) {
1636 internal_receiver = proxy_receiver->internal();
1637 break;
1638 }
1639 }
1640 if (internal_receiver)
1641 break;
1642 }
1643 }
1644 // If there is no |internal_receiver| then |selector| is either null or does
1645 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1646 // the PeerConnection). This means that "all the stats objects representing
1647 // the selector" is an empty set. Invoking GetStatsReport() with a null
1648 // selector produces an empty stats report.
1649 stats_collector_->GetStatsReport(internal_receiver, callback);
1650}
1651
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1653 return signaling_state_;
1654}
1655
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001656PeerConnectionInterface::IceConnectionState
1657PeerConnection::ice_connection_state() {
1658 return ice_connection_state_;
1659}
1660
1661PeerConnectionInterface::IceGatheringState
1662PeerConnection::ice_gathering_state() {
1663 return ice_gathering_state_;
1664}
1665
Yves Gerey665174f2018-06-19 15:03:05 +02001666rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001667 const std::string& label,
1668 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001669 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001670
deadbeefab9b2d12015-10-14 11:33:11 -07001671 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001672
kwibergd1fe2812016-04-27 06:47:29 -07001673 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001674 if (config) {
1675 internal_config.reset(new InternalDataChannelInit(*config));
1676 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001677 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001678 InternalCreateDataChannel(label, internal_config.get()));
1679 if (!channel.get()) {
1680 return nullptr;
1681 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001682
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001683 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1684 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001685 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001686 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001687 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001688 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001689 return DataChannelProxy::Create(signaling_thread(), channel.get());
1690}
1691
1692void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001693 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001694 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001695
nisse7ce109a2017-01-31 00:57:56 -08001696 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001697 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001698 return;
1699 }
deadbeefab9b2d12015-10-14 11:33:11 -07001700
Steve Anton8d3444d2017-10-20 15:30:51 -07001701 if (IsClosed()) {
1702 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001703 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001704 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001705 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001706 return;
1707 }
1708
zhihuang1c378ed2017-08-17 14:10:50 -07001709 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001710 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001711 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001712 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001713 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001714 return;
1715 }
1716
Steve Anton22da89f2018-01-25 13:58:07 -08001717 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1718 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1719 if (IsUnifiedPlan()) {
1720 RTCError error = HandleLegacyOfferOptions(options);
1721 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001722 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001723 return;
1724 }
1725 }
1726
zhihuang1c378ed2017-08-17 14:10:50 -07001727 cricket::MediaSessionOptions session_options;
1728 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001729 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001730}
1731
Steve Anton22da89f2018-01-25 13:58:07 -08001732RTCError PeerConnection::HandleLegacyOfferOptions(
1733 const RTCOfferAnswerOptions& options) {
1734 RTC_DCHECK(IsUnifiedPlan());
1735
1736 if (options.offer_to_receive_audio == 0) {
1737 RemoveRecvDirectionFromReceivingTransceiversOfType(
1738 cricket::MEDIA_TYPE_AUDIO);
1739 } else if (options.offer_to_receive_audio == 1) {
1740 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1741 } else if (options.offer_to_receive_audio > 1) {
1742 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1743 "offer_to_receive_audio > 1 is not supported.");
1744 }
1745
1746 if (options.offer_to_receive_video == 0) {
1747 RemoveRecvDirectionFromReceivingTransceiversOfType(
1748 cricket::MEDIA_TYPE_VIDEO);
1749 } else if (options.offer_to_receive_video == 1) {
1750 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1751 } else if (options.offer_to_receive_video > 1) {
1752 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1753 "offer_to_receive_video > 1 is not supported.");
1754 }
1755
1756 return RTCError::OK();
1757}
1758
1759void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1760 cricket::MediaType media_type) {
1761 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001762 RtpTransceiverDirection new_direction =
1763 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1764 if (new_direction != transceiver->direction()) {
1765 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1766 << " transceiver (MID="
1767 << transceiver->mid().value_or("<not set>") << ") from "
1768 << RtpTransceiverDirectionToString(
1769 transceiver->direction())
1770 << " to "
1771 << RtpTransceiverDirectionToString(new_direction)
1772 << " since CreateOffer specified offer_to_receive=0";
1773 transceiver->internal()->set_direction(new_direction);
1774 }
Steve Anton22da89f2018-01-25 13:58:07 -08001775 }
1776}
1777
1778void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1779 cricket::MediaType media_type) {
1780 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001781 RTC_LOG(LS_INFO)
1782 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1783 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001784 RtpTransceiverInit init;
1785 init.direction = RtpTransceiverDirection::kRecvOnly;
1786 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1787 }
1788}
1789
1790std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1791PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1792 std::vector<
1793 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1794 receiving_transceivers;
1795 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001796 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001797 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1798 receiving_transceivers.push_back(transceiver);
1799 }
1800 }
1801 return receiving_transceivers;
1802}
1803
htaa2a49d92016-03-04 02:51:39 -08001804void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1805 const RTCOfferAnswerOptions& options) {
1806 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001807 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001808 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001809 return;
1810 }
1811
Steve Antondffead82018-02-06 10:31:29 -08001812 if (!(signaling_state_ == kHaveRemoteOffer ||
1813 signaling_state_ == kHaveLocalPrAnswer)) {
1814 std::string error =
1815 "PeerConnection cannot create an answer in a state other than "
1816 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001817 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001818 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001819 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001820 return;
1821 }
1822
Steve Antondffead82018-02-06 10:31:29 -08001823 // The remote description should be set if we're in the right state.
1824 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001825
Steve Anton22da89f2018-01-25 13:58:07 -08001826 if (IsUnifiedPlan()) {
1827 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1828 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1829 "supported with Unified Plan semantics. Use the "
1830 "RtpTransceiver API instead.";
1831 }
1832 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1833 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1834 "supported with Unified Plan semantics. Use the "
1835 "RtpTransceiver API instead.";
1836 }
1837 }
1838
htaa2a49d92016-03-04 02:51:39 -08001839 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001840 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001841
Steve Antond25da372017-11-06 14:50:29 -08001842 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001843}
1844
1845void PeerConnection::SetLocalDescription(
1846 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001847 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001848 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001849
Steve Anton80dd7b52018-02-16 17:08:42 -08001850 // The SetLocalDescription contract is that we take ownership of the session
1851 // description regardless of the outcome, so wrap it in a unique_ptr right
1852 // away. Ideally, SetLocalDescription's signature will be changed to take the
1853 // description as a unique_ptr argument to formalize this agreement.
1854 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1855
nisse7ce109a2017-01-31 00:57:56 -08001856 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001857 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858 return;
1859 }
Steve Anton8a006912017-12-04 15:25:56 -08001860
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001862 PostSetSessionDescriptionFailure(
1863 observer,
1864 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 return;
1866 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001867
Steve Anton80dd7b52018-02-16 17:08:42 -08001868 // If a session error has occurred the PeerConnection is in a possibly
1869 // inconsistent state so fail right away.
1870 if (session_error() != SessionError::kNone) {
1871 std::string error_message = GetSessionErrorMsg();
1872 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001873 PostSetSessionDescriptionFailure(
1874 observer,
1875 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001876 return;
1877 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001878
Steve Anton80dd7b52018-02-16 17:08:42 -08001879 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1880 if (!error.ok()) {
1881 std::string error_message = GetSetDescriptionErrorMessage(
1882 cricket::CS_LOCAL, desc->GetType(), error);
1883 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001884 PostSetSessionDescriptionFailure(
1885 observer,
1886 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001887 return;
1888 }
1889
1890 // Grab the description type before moving ownership to ApplyLocalDescription,
1891 // which may destroy it before returning.
1892 const SdpType type = desc->GetType();
1893
1894 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001895 // |desc| may be destroyed at this point.
1896
1897 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001898 // If ApplyLocalDescription fails, the PeerConnection could be in an
1899 // inconsistent state, so act conservatively here and set the session error
1900 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1901 SetSessionError(SessionError::kContent, error.message());
1902 std::string error_message =
1903 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1904 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001905 PostSetSessionDescriptionFailure(
1906 observer,
1907 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001908 return;
1909 }
Steve Anton8a006912017-12-04 15:25:56 -08001910 RTC_DCHECK(local_description());
1911
1912 PostSetSessionDescriptionSuccess(observer);
1913
Steve Antonad182762018-09-05 20:22:40 +00001914 // MaybeStartGathering needs to be called after posting
1915 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1916 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001917 transport_controller_->MaybeStartGathering();
1918
Steve Antona3a92c22017-12-07 10:27:41 -08001919 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001920 // TODO(deadbeef): We already had to hop to the network thread for
1921 // MaybeStartGathering...
1922 network_thread()->Invoke<void>(
1923 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1924 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001925 // Make UMA notes about what was agreed to.
1926 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001927 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001928 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001929}
1930
1931RTCError PeerConnection::ApplyLocalDescription(
1932 std::unique_ptr<SessionDescriptionInterface> desc) {
1933 RTC_DCHECK_RUN_ON(signaling_thread());
1934 RTC_DCHECK(desc);
1935
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 // Update stats here so that we have the most recent stats for tracks and
1937 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001938 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001939
Steve Antondcc3c022017-12-22 16:02:54 -08001940 // Take a reference to the old local description since it's used below to
1941 // compare against the new local description. When setting the new local
1942 // description, grab ownership of the replaced session description in case it
1943 // is the same as |old_local_description|, to keep it alive for the duration
1944 // of the method.
1945 const SessionDescriptionInterface* old_local_description =
1946 local_description();
1947 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001948 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001949 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001950 replaced_local_description = pending_local_description_
1951 ? std::move(pending_local_description_)
1952 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001953 current_local_description_ = std::move(desc);
1954 pending_local_description_ = nullptr;
1955 current_remote_description_ = std::move(pending_remote_description_);
1956 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001957 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001958 pending_local_description_ = std::move(desc);
1959 }
1960 // The session description to apply now must be accessed by
1961 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001962 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001963
Zhi Huange830e682018-03-30 10:48:35 -07001964 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
1965 if (!error.ok()) {
1966 return error;
1967 }
1968
Steve Antondcc3c022017-12-22 16:02:54 -08001969 if (IsUnifiedPlan()) {
1970 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001971 cricket::CS_LOCAL, *local_description(), old_local_description,
1972 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001973 if (!error.ok()) {
1974 return error;
1975 }
Steve Anton0f5400a2018-07-17 14:25:36 -07001976 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
1977 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08001978 for (auto transceiver : transceivers_) {
1979 const ContentInfo* content =
1980 FindMediaSectionForTransceiver(transceiver, local_description());
1981 if (!content) {
1982 continue;
1983 }
1984 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07001985 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
1986 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08001987 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07001988 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
1989 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
1990 // "recvonly", process the removal of a remote track for the media
1991 // description, given transceiver, removeList, and muteTracks.
1992 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
1993 (transceiver->internal()->fired_direction() &&
1994 RtpTransceiverDirectionHasRecv(
1995 *transceiver->internal()->fired_direction()))) {
1996 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
1997 &removed_streams);
1998 }
1999 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2000 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002001 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002002 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002003 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002004 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002005 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002006 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002007 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002008 }
2009 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002010 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002011 }
2012 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002013 // Media channels will be created only when offer is set. These may use new
2014 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002015 if (type == SdpType::kOffer) {
2016 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2017 // description is applied. Restore back to old description.
2018 RTCError error = CreateChannels(*local_description()->description());
2019 if (!error.ok()) {
2020 return error;
2021 }
2022 }
Steve Antondcc3c022017-12-22 16:02:54 -08002023 // Remove unused channels if MediaContentDescription is rejected.
2024 RemoveUnusedChannels(local_description()->description());
2025 }
Steve Anton8a006912017-12-04 15:25:56 -08002026
Zhi Huange830e682018-03-30 10:48:35 -07002027 error = UpdateSessionState(type, cricket::CS_LOCAL,
2028 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002029 if (!error.ok()) {
2030 return error;
2031 }
Steve Antondcc3c022017-12-22 16:02:54 -08002032
Steve Anton8a006912017-12-04 15:25:56 -08002033 if (remote_description()) {
2034 // Now that we have a local description, we can push down remote candidates.
2035 UseCandidatesInSessionDescription(remote_description());
2036 }
2037
2038 pending_ice_restarts_.clear();
2039 if (session_error() != SessionError::kNone) {
2040 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2041 }
2042
deadbeefab9b2d12015-10-14 11:33:11 -07002043 // If setting the description decided our SSL role, allocate any necessary
2044 // SCTP sids.
2045 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002046 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002047 AllocateSctpSids(role);
2048 }
2049
Steve Antond3679212018-01-17 17:41:02 -08002050 if (IsUnifiedPlan()) {
2051 for (auto transceiver : transceivers_) {
2052 const ContentInfo* content =
2053 FindMediaSectionForTransceiver(transceiver, local_description());
2054 if (!content) {
2055 continue;
2056 }
Steve Anton74255ff2018-01-24 18:32:57 -08002057 const auto& streams = content->media_description()->streams();
2058 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002059 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002060 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002061 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002062 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002063 } else {
2064 // 0 is a special value meaning "this sender has no associated send
2065 // stream". Need to call this so the sender won't attempt to configure
2066 // a no longer existing stream and run into DCHECKs in the lower
2067 // layers.
2068 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002069 }
2070 }
2071 } else {
2072 // Plan B semantics.
2073
Steve Antondcc3c022017-12-22 16:02:54 -08002074 // Update state and SSRC of local MediaStreams and DataChannels based on the
2075 // local session description.
2076 const cricket::ContentInfo* audio_content =
2077 GetFirstAudioContent(local_description()->description());
2078 if (audio_content) {
2079 if (audio_content->rejected) {
2080 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2081 } else {
2082 const cricket::AudioContentDescription* audio_desc =
2083 audio_content->media_description()->as_audio();
2084 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2085 }
deadbeeffaac4972015-11-12 15:33:07 -08002086 }
deadbeefab9b2d12015-10-14 11:33:11 -07002087
Steve Antondcc3c022017-12-22 16:02:54 -08002088 const cricket::ContentInfo* video_content =
2089 GetFirstVideoContent(local_description()->description());
2090 if (video_content) {
2091 if (video_content->rejected) {
2092 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2093 } else {
2094 const cricket::VideoContentDescription* video_desc =
2095 video_content->media_description()->as_video();
2096 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2097 }
deadbeeffaac4972015-11-12 15:33:07 -08002098 }
deadbeefab9b2d12015-10-14 11:33:11 -07002099 }
2100
2101 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002102 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002103 if (data_content) {
2104 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002105 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002106 if (rtc::starts_with(data_desc->protocol().data(),
2107 cricket::kMediaProtocolRtpPrefix)) {
2108 UpdateLocalRtpDataChannels(data_desc->streams());
2109 }
2110 }
2111
Steve Anton8a006912017-12-04 15:25:56 -08002112 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002113}
2114
2115void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002116 SetSessionDescriptionObserver* observer,
2117 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002118 SetRemoteDescription(
2119 std::unique_ptr<SessionDescriptionInterface>(desc),
2120 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2121 new SetRemoteDescriptionObserverAdapter(this, observer)));
2122}
2123
2124void PeerConnection::SetRemoteDescription(
2125 std::unique_ptr<SessionDescriptionInterface> desc,
2126 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002127 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002128
nisse7ce109a2017-01-31 00:57:56 -08002129 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002130 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002131 return;
2132 }
Steve Anton8a006912017-12-04 15:25:56 -08002133
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002135 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002136 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137 return;
2138 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002139
Steve Anton80dd7b52018-02-16 17:08:42 -08002140 // If a session error has occurred the PeerConnection is in a possibly
2141 // inconsistent state so fail right away.
2142 if (session_error() != SessionError::kNone) {
2143 std::string error_message = GetSessionErrorMsg();
2144 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2145 observer->OnSetRemoteDescriptionComplete(
2146 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2147 return;
2148 }
Steve Anton71439a62018-02-15 11:53:06 -08002149
Steve Antonba42e992018-04-09 14:10:01 -07002150 if (desc->GetType() == SdpType::kOffer) {
2151 // Report to UMA the format of the received offer.
2152 ReportSdpFormatReceived(*desc);
2153 }
2154
Steve Anton80dd7b52018-02-16 17:08:42 -08002155 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002156 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002157 std::string error_message = GetSetDescriptionErrorMessage(
2158 cricket::CS_REMOTE, desc->GetType(), error);
2159 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002160 observer->OnSetRemoteDescriptionComplete(
2161 RTCError(error.type(), std::move(error_message)));
2162 return;
2163 }
Steve Anton71439a62018-02-15 11:53:06 -08002164
Steve Anton80dd7b52018-02-16 17:08:42 -08002165 // Grab the description type before moving ownership to
2166 // ApplyRemoteDescription, which may destroy it before returning.
2167 const SdpType type = desc->GetType();
2168
2169 error = ApplyRemoteDescription(std::move(desc));
2170 // |desc| may be destroyed at this point.
2171
2172 if (!error.ok()) {
2173 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2174 // inconsistent state, so act conservatively here and set the session error
2175 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2176 SetSessionError(SessionError::kContent, error.message());
2177 std::string error_message =
2178 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2179 RTC_LOG(LS_ERROR) << error_message;
2180 observer->OnSetRemoteDescriptionComplete(
2181 RTCError(error.type(), std::move(error_message)));
2182 return;
2183 }
2184 RTC_DCHECK(remote_description());
2185
2186 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002187 // TODO(deadbeef): We already had to hop to the network thread for
2188 // MaybeStartGathering...
2189 network_thread()->Invoke<void>(
2190 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2191 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002192 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002193 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002194 }
2195
2196 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002197 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002198}
2199
2200RTCError PeerConnection::ApplyRemoteDescription(
2201 std::unique_ptr<SessionDescriptionInterface> desc) {
2202 RTC_DCHECK_RUN_ON(signaling_thread());
2203 RTC_DCHECK(desc);
2204
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 // Update stats here so that we have the most recent stats for tracks and
2206 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002207 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002208
Steve Antondcc3c022017-12-22 16:02:54 -08002209 // Take a reference to the old remote description since it's used below to
2210 // compare against the new remote description. When setting the new remote
2211 // description, grab ownership of the replaced session description in case it
2212 // is the same as |old_remote_description|, to keep it alive for the duration
2213 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002214 const SessionDescriptionInterface* old_remote_description =
2215 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002216 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002217 SdpType type = desc->GetType();
2218 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002219 replaced_remote_description = pending_remote_description_
2220 ? std::move(pending_remote_description_)
2221 : std::move(current_remote_description_);
2222 current_remote_description_ = std::move(desc);
2223 pending_remote_description_ = nullptr;
2224 current_local_description_ = std::move(pending_local_description_);
2225 } else {
2226 replaced_remote_description = std::move(pending_remote_description_);
2227 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228 }
Steve Anton8a006912017-12-04 15:25:56 -08002229 // The session description to apply now must be accessed by
2230 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002231 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002232
Zhi Huange830e682018-03-30 10:48:35 -07002233 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2234 if (!error.ok()) {
2235 return error;
2236 }
Steve Anton8a006912017-12-04 15:25:56 -08002237 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002238 if (IsUnifiedPlan()) {
2239 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002240 cricket::CS_REMOTE, *remote_description(), local_description(),
2241 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002242 if (!error.ok()) {
2243 return error;
2244 }
Steve Antondcc3c022017-12-22 16:02:54 -08002245 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002246 // Media channels will be created only when offer is set. These may use new
2247 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002248 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002249 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002250 // description is applied. Restore back to old description.
2251 RTCError error = CreateChannels(*remote_description()->description());
2252 if (!error.ok()) {
2253 return error;
2254 }
2255 }
Steve Antondcc3c022017-12-22 16:02:54 -08002256 // Remove unused channels if MediaContentDescription is rejected.
2257 RemoveUnusedChannels(remote_description()->description());
2258 }
Steve Anton8a006912017-12-04 15:25:56 -08002259
Zhi Huange830e682018-03-30 10:48:35 -07002260 // NOTE: Candidates allocation will be initiated only when
2261 // SetLocalDescription is called.
2262 error = UpdateSessionState(type, cricket::CS_REMOTE,
2263 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002264 if (!error.ok()) {
2265 return error;
2266 }
2267
2268 if (local_description() &&
2269 !UseCandidatesInSessionDescription(remote_description())) {
2270 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2271 }
2272
2273 if (old_remote_description) {
2274 for (const cricket::ContentInfo& content :
2275 old_remote_description->description()->contents()) {
2276 // Check if this new SessionDescription contains new ICE ufrag and
2277 // password that indicates the remote peer requests an ICE restart.
2278 // TODO(deadbeef): When we start storing both the current and pending
2279 // remote description, this should reset pending_ice_restarts and compare
2280 // against the current description.
2281 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2282 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002283 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002284 pending_ice_restarts_.insert(content.name);
2285 }
2286 } else {
2287 // We retain all received candidates only if ICE is not restarted.
2288 // When ICE is restarted, all previous candidates belong to an old
2289 // generation and should not be kept.
2290 // TODO(deadbeef): This goes against the W3C spec which says the remote
2291 // description should only contain candidates from the last set remote
2292 // description plus any candidates added since then. We should remove
2293 // this once we're sure it won't break anything.
2294 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2295 old_remote_description, content.name, mutable_remote_description());
2296 }
2297 }
2298 }
2299
2300 if (session_error() != SessionError::kNone) {
2301 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2302 }
2303
2304 // Set the the ICE connection state to connecting since the connection may
2305 // become writable with peer reflexive candidates before any remote candidate
2306 // is signaled.
2307 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2308 // is to have a new signal the indicates a change in checking state from the
2309 // transport and expose a new checking() member from transport that can be
2310 // read to determine the current checking state. The existing SignalConnecting
2311 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002312 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002313 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002314 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2315 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2316 }
2317
deadbeefab9b2d12015-10-14 11:33:11 -07002318 // If setting the description decided our SSL role, allocate any necessary
2319 // SCTP sids.
2320 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002321 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002322 AllocateSctpSids(role);
2323 }
2324
Steve Antondcc3c022017-12-22 16:02:54 -08002325 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002326 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002327 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002328 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002329 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002330 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002331 for (auto transceiver : transceivers_) {
2332 const ContentInfo* content =
2333 FindMediaSectionForTransceiver(transceiver, remote_description());
2334 if (!content) {
2335 continue;
2336 }
2337 const MediaContentDescription* media_desc = content->media_description();
2338 RtpTransceiverDirection local_direction =
2339 RtpTransceiverDirectionReversed(media_desc->direction());
2340 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2341 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2342 // transceiver's current direction is neither sendrecv nor recvonly,
2343 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002344 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002345 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002346 // The remote description has signaled the stream IDs.
2347 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002348 }
Steve Antondcc3c022017-12-22 16:02:54 -08002349 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002350 (!transceiver->fired_direction() ||
2351 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002352 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002353 << content->name << " (added to "
2354 << GetStreamIdsString(stream_ids) << ").";
2355
2356 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2357 for (const std::string& stream_id : stream_ids) {
2358 rtc::scoped_refptr<MediaStreamInterface> stream =
2359 remote_streams_->find(stream_id);
2360 if (!stream) {
2361 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2362 MediaStream::Create(stream_id));
2363 remote_streams_->AddStream(stream);
2364 added_streams.push_back(stream);
2365 }
2366 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002367 }
Steve Anton3172c032018-05-03 15:30:18 -07002368 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002369 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2370 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002371 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002372 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002373 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002374 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2375 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2376 // removal of a remote track for the media description, given transceiver,
2377 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002378 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002379 (transceiver->fired_direction() &&
2380 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2381 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2382 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002383 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002384 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2385 transceiver->internal()->set_fired_direction(local_direction);
2386 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2387 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002388 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002389 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2390 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002391 transceiver->internal()->set_current_direction(local_direction);
2392 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002393 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2394 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002395 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002396 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2397 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002398 transceiver->Stop();
2399 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002400 if (!content->rejected &&
2401 RtpTransceiverDirectionHasRecv(local_direction)) {
2402 // Set ssrc to 0 in the case of an unsignalled ssrc.
2403 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002404 if (!media_desc->streams().empty() &&
2405 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002406 ssrc = media_desc->streams()[0].first_ssrc();
2407 }
2408 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002409 }
Steve Antondcc3c022017-12-22 16:02:54 -08002410 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002411 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002412 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002413 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002414 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002415 observer->OnTrack(transceiver);
2416 observer->OnAddTrack(transceiver->receiver(),
2417 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002418 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002419 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002420 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002421 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002422 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002423 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002424 }
2425 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002426 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002427 }
Steve Antondcc3c022017-12-22 16:02:54 -08002428 }
2429
Henrik Boströmfdb92012017-11-09 19:55:44 +01002430 const cricket::ContentInfo* audio_content =
2431 GetFirstAudioContent(remote_description()->description());
2432 const cricket::ContentInfo* video_content =
2433 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002434 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002435 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002436 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002437 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002438 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002439 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002440
2441 // Check if the descriptions include streams, just in case the peer supports
2442 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002443 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002444 (audio_desc && !audio_desc->streams().empty()) ||
2445 (video_desc && !video_desc->streams().empty())) {
2446 remote_peer_supports_msid_ = true;
2447 }
deadbeefab9b2d12015-10-14 11:33:11 -07002448
2449 // We wait to signal new streams until we finish processing the description,
2450 // since only at that point will new streams have all their tracks.
2451 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2452
Steve Antondcc3c022017-12-22 16:02:54 -08002453 if (!IsUnifiedPlan()) {
2454 // TODO(steveanton): When removing RTP senders/receivers in response to a
2455 // rejected media section, there is some cleanup logic that expects the
2456 // voice/ video channel to still be set. But in this method the voice/video
2457 // channel would have been destroyed by the SetRemoteDescription caller
2458 // above so the cleanup that relies on them fails to run. The RemoveSenders
2459 // calls should be moved to right before the DestroyChannel calls to fix
2460 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002461
Steve Antondcc3c022017-12-22 16:02:54 -08002462 // Find all audio rtp streams and create corresponding remote AudioTracks
2463 // and MediaStreams.
2464 if (audio_content) {
2465 if (audio_content->rejected) {
2466 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2467 } else {
2468 bool default_audio_track_needed =
2469 !remote_peer_supports_msid_ &&
2470 RtpTransceiverDirectionHasSend(audio_desc->direction());
2471 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2472 default_audio_track_needed, audio_desc->type(),
2473 new_streams);
2474 }
deadbeeffaac4972015-11-12 15:33:07 -08002475 }
deadbeefab9b2d12015-10-14 11:33:11 -07002476
Steve Antondcc3c022017-12-22 16:02:54 -08002477 // Find all video rtp streams and create corresponding remote VideoTracks
2478 // and MediaStreams.
2479 if (video_content) {
2480 if (video_content->rejected) {
2481 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2482 } else {
2483 bool default_video_track_needed =
2484 !remote_peer_supports_msid_ &&
2485 RtpTransceiverDirectionHasSend(video_desc->direction());
2486 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2487 default_video_track_needed, video_desc->type(),
2488 new_streams);
2489 }
deadbeeffaac4972015-11-12 15:33:07 -08002490 }
deadbeefab9b2d12015-10-14 11:33:11 -07002491
Steve Antondcc3c022017-12-22 16:02:54 -08002492 // Update the DataChannels with the information from the remote peer.
2493 if (data_desc) {
2494 if (rtc::starts_with(data_desc->protocol().data(),
2495 cricket::kMediaProtocolRtpPrefix)) {
2496 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2497 }
deadbeefab9b2d12015-10-14 11:33:11 -07002498 }
deadbeefab9b2d12015-10-14 11:33:11 -07002499
Steve Antondcc3c022017-12-22 16:02:54 -08002500 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002501 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002502 for (size_t i = 0; i < new_streams->count(); ++i) {
2503 MediaStreamInterface* new_stream = new_streams->at(i);
2504 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002505 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002506 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2507 }
deadbeefab9b2d12015-10-14 11:33:11 -07002508
Steve Antondcc3c022017-12-22 16:02:54 -08002509 UpdateEndedRemoteMediaStreams();
2510 }
deadbeefab9b2d12015-10-14 11:33:11 -07002511
Steve Anton8a006912017-12-04 15:25:56 -08002512 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002513}
2514
Steve Anton0f5400a2018-07-17 14:25:36 -07002515void PeerConnection::ProcessRemovalOfRemoteTrack(
2516 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2517 transceiver,
2518 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2519 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2520 RTC_DCHECK(transceiver->mid());
2521 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2522 << *transceiver->mid();
2523 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2524 transceiver->internal()->receiver_internal()->streams();
2525 // This will remove the remote track from the streams.
2526 transceiver->internal()->receiver_internal()->set_stream_ids({});
2527 remove_list->push_back(transceiver);
2528 // Remove any streams that no longer have tracks.
2529 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2530 // of streams, see if the stream was removed by checking if this was the
2531 // last receiver with that stream ID.
2532 for (auto stream : media_streams) {
2533 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2534 remote_streams_->RemoveStream(stream);
2535 removed_streams->push_back(stream);
2536 }
2537 }
2538}
2539
Steve Antondcc3c022017-12-22 16:02:54 -08002540RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2541 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002542 const SessionDescriptionInterface& new_session,
2543 const SessionDescriptionInterface* old_local_description,
2544 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002545 RTC_DCHECK(IsUnifiedPlan());
2546
Steve Anton7464fca2018-01-19 11:10:37 -08002547 const cricket::ContentGroup* bundle_group = nullptr;
2548 if (new_session.GetType() == SdpType::kOffer) {
2549 auto bundle_group_or_error =
2550 GetEarlyBundleGroup(*new_session.description());
2551 if (!bundle_group_or_error.ok()) {
2552 return bundle_group_or_error.MoveError();
2553 }
2554 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002555 }
Steve Antondcc3c022017-12-22 16:02:54 -08002556
Steve Antondcc3c022017-12-22 16:02:54 -08002557 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002558 for (size_t i = 0; i < new_contents.size(); ++i) {
2559 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002560 cricket::MediaType media_type = new_content.media_description()->type();
2561 seen_mids_.insert(new_content.name);
2562 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2563 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002564 const cricket::ContentInfo* old_local_content = nullptr;
2565 if (old_local_description &&
2566 i < old_local_description->description()->contents().size()) {
2567 old_local_content =
2568 &old_local_description->description()->contents()[i];
2569 }
2570 const cricket::ContentInfo* old_remote_content = nullptr;
2571 if (old_remote_description &&
2572 i < old_remote_description->description()->contents().size()) {
2573 old_remote_content =
2574 &old_remote_description->description()->contents()[i];
2575 }
Steve Antondcc3c022017-12-22 16:02:54 -08002576 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002577 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2578 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002579 if (!transceiver_or_error.ok()) {
2580 return transceiver_or_error.MoveError();
2581 }
2582 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002583 RTCError error =
2584 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2585 if (!error.ok()) {
2586 return error;
2587 }
2588 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002589 if (GetDataMid() && new_content.name != *GetDataMid()) {
2590 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002591 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2592 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002593 continue;
2594 }
2595 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2596 if (!error.ok()) {
2597 return error;
2598 }
Steve Antondcc3c022017-12-22 16:02:54 -08002599 } else {
2600 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2601 "Unknown section type.");
2602 }
2603 }
2604
2605 return RTCError::OK();
2606}
2607
2608RTCError PeerConnection::UpdateTransceiverChannel(
2609 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2610 transceiver,
2611 const cricket::ContentInfo& content,
2612 const cricket::ContentGroup* bundle_group) {
2613 RTC_DCHECK(IsUnifiedPlan());
2614 RTC_DCHECK(transceiver);
2615 cricket::BaseChannel* channel = transceiver->internal()->channel();
2616 if (content.rejected) {
2617 if (channel) {
2618 transceiver->internal()->SetChannel(nullptr);
2619 DestroyBaseChannel(channel);
2620 }
2621 } else {
2622 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002623 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002624 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002625 } else {
Steve Anton69470252018-02-09 11:43:08 -08002626 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002627 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002628 }
2629 if (!channel) {
2630 LOG_AND_RETURN_ERROR(
2631 RTCErrorType::INTERNAL_ERROR,
2632 "Failed to create channel for mid=" + content.name);
2633 }
2634 transceiver->internal()->SetChannel(channel);
2635 }
2636 }
2637 return RTCError::OK();
2638}
2639
Steve Antonfa2260d2017-12-28 16:38:23 -08002640RTCError PeerConnection::UpdateDataChannel(
2641 cricket::ContentSource source,
2642 const cricket::ContentInfo& content,
2643 const cricket::ContentGroup* bundle_group) {
2644 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002645 // If data channels are disabled, ignore this media section. CreateAnswer
2646 // will take care of rejecting it.
2647 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002648 }
2649 if (content.rejected) {
2650 DestroyDataChannel();
2651 } else {
2652 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002653 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002654 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2655 "Failed to create data channel.");
2656 }
2657 }
2658 if (source == cricket::CS_REMOTE) {
2659 const MediaContentDescription* data_desc = content.media_description();
2660 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2661 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2662 }
2663 }
2664 }
2665 return RTCError::OK();
2666}
2667
Steve Antondcc3c022017-12-22 16:02:54 -08002668RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2669PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002670 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002671 size_t mline_index,
2672 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002673 const ContentInfo* old_local_content,
2674 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002675 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002676 // If this is an offer then the m= section might be recycled. If the m=
2677 // section is being recycled (defined as: rejected in the current local or
2678 // remote description and not rejected in new description), dissociate the
2679 // currently associated RtpTransceiver by setting its mid property to null,
2680 // and discard the mapping between the transceiver and its m= section index.
2681 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2682 old_remote_content)) {
2683 // We want to dissociate the transceiver that has the rejected mid.
2684 const std::string& old_mid =
2685 (old_local_content && old_local_content->rejected)
2686 ? old_local_content->name
2687 : old_remote_content->name;
2688 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002689 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002690 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2691 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002692 old_transceiver->internal()->set_mid(absl::nullopt);
2693 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002694 }
2695 }
2696 const MediaContentDescription* media_desc = content.media_description();
2697 auto transceiver = GetAssociatedTransceiver(content.name);
2698 if (source == cricket::CS_LOCAL) {
2699 // Find the RtpTransceiver that corresponds to this m= section, using the
2700 // mapping between transceivers and m= section indices established when
2701 // creating the offer.
2702 if (!transceiver) {
2703 transceiver = GetTransceiverByMLineIndex(mline_index);
2704 }
2705 if (!transceiver) {
2706 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2707 "Unknown transceiver");
2708 }
2709 } else {
2710 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2711 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2712 // of the same type...
2713 if (!transceiver &&
2714 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2715 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2716 }
2717 // If no RtpTransceiver was found in the previous step, create one with a
2718 // recvonly direction.
2719 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002720 RTC_LOG(LS_INFO) << "Adding "
2721 << cricket::MediaTypeToString(media_desc->type())
2722 << " transceiver for MID=" << content.name
2723 << " at i=" << mline_index
2724 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002725 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002726 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002727 std::string receiver_id;
2728 if (!media_desc->streams().empty()) {
2729 receiver_id = media_desc->streams()[0].id;
2730 } else {
2731 receiver_id = rtc::CreateRandomUuid();
2732 }
2733 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002734 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002735 transceiver->internal()->set_direction(
2736 RtpTransceiverDirection::kRecvOnly);
2737 }
2738 }
2739 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002740 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002741 LOG_AND_RETURN_ERROR(
2742 RTCErrorType::INVALID_PARAMETER,
2743 "Transceiver type does not match media description type.");
2744 }
2745 // Associate the found or created RtpTransceiver with the m= section by
2746 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2747 // section, and establish a mapping between the transceiver and the index of
2748 // the m= section.
2749 transceiver->internal()->set_mid(content.name);
2750 transceiver->internal()->set_mline_index(mline_index);
2751 return std::move(transceiver);
2752}
2753
2754rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2755PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2756 RTC_DCHECK(IsUnifiedPlan());
2757 for (auto transceiver : transceivers_) {
2758 if (transceiver->mid() == mid) {
2759 return transceiver;
2760 }
2761 }
2762 return nullptr;
2763}
2764
2765rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2766PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2767 RTC_DCHECK(IsUnifiedPlan());
2768 for (auto transceiver : transceivers_) {
2769 if (transceiver->internal()->mline_index() == mline_index) {
2770 return transceiver;
2771 }
2772 }
2773 return nullptr;
2774}
2775
2776rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2777PeerConnection::FindAvailableTransceiverToReceive(
2778 cricket::MediaType media_type) const {
2779 RTC_DCHECK(IsUnifiedPlan());
2780 // From JSEP section 5.10 (Applying a Remote Description):
2781 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2782 // the same type that were added to the PeerConnection by addTrack and are not
2783 // associated with any m= section and are not stopped, find the first such
2784 // RtpTransceiver.
2785 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002786 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002787 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2788 !transceiver->stopped()) {
2789 return transceiver;
2790 }
2791 }
2792 return nullptr;
2793}
2794
Steve Antoned10bd92017-12-05 10:52:59 -08002795const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2796 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2797 transceiver,
2798 const SessionDescriptionInterface* sdesc) const {
2799 RTC_DCHECK(transceiver);
2800 RTC_DCHECK(sdesc);
2801 if (IsUnifiedPlan()) {
2802 if (!transceiver->internal()->mid()) {
2803 // This transceiver is not associated with a media section yet.
2804 return nullptr;
2805 }
2806 return sdesc->description()->GetContentByName(
2807 *transceiver->internal()->mid());
2808 } else {
2809 // Plan B only allows at most one audio and one video section, so use the
2810 // first media section of that type.
2811 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002812 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002813 }
2814}
2815
deadbeef46c73892016-11-16 19:42:04 -08002816PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2817 return configuration_;
2818}
2819
deadbeef293e9262017-01-11 12:28:30 -08002820bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2821 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002822 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002823 if (IsClosed()) {
2824 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2825 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2826 }
2827
Qingsi Wanga2d60672018-04-11 16:57:45 -07002828 // According to JSEP, after setLocalDescription, changing the candidate pool
2829 // size is not allowed, and changing the set of ICE servers will not result
2830 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002831 if (local_description() && configuration.ice_candidate_pool_size !=
2832 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002833 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2834 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002835 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002836 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002837
deadbeef293e9262017-01-11 12:28:30 -08002838 // The simplest (and most future-compatible) way to tell if the config was
2839 // modified in an invalid way is to copy each property we do support
2840 // modifying, then use operator==. There are far more properties we don't
2841 // support modifying than those we do, and more could be added.
2842 RTCConfiguration modified_config = configuration_;
2843 modified_config.servers = configuration.servers;
2844 modified_config.type = configuration.type;
2845 modified_config.ice_candidate_pool_size =
2846 configuration.ice_candidate_pool_size;
2847 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002848 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002849 modified_config.ice_check_interval_strong_connectivity =
2850 configuration.ice_check_interval_strong_connectivity;
2851 modified_config.ice_check_interval_weak_connectivity =
2852 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002853 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2854 modified_config.ice_unwritable_min_checks =
2855 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002856 modified_config.stun_candidate_keepalive_interval =
2857 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002858 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002859 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002860 modified_config.active_reset_srtp_params =
2861 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002862 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002863 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002864 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2865 }
2866
Steve Anton038834f2017-07-14 15:59:59 -07002867 // Validate the modified configuration.
2868 RTCError validate_error = ValidateConfiguration(modified_config);
2869 if (!validate_error.ok()) {
2870 return SafeSetError(std::move(validate_error), error);
2871 }
2872
deadbeef293e9262017-01-11 12:28:30 -08002873 // Note that this isn't possible through chromium, since it's an unsigned
2874 // short in WebIDL.
2875 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002876 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002877 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2878 }
2879
2880 // Parse ICE servers before hopping to network thread.
2881 cricket::ServerAddresses stun_servers;
2882 std::vector<cricket::RelayServerConfig> turn_servers;
2883 RTCErrorType parse_error =
2884 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2885 if (parse_error != RTCErrorType::NONE) {
2886 return SafeSetError(parse_error, error);
2887 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002888 // Note if STUN or TURN servers were supplied.
2889 if (!stun_servers.empty()) {
2890 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2891 }
2892 if (!turn_servers.empty()) {
2893 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2894 }
deadbeef293e9262017-01-11 12:28:30 -08002895
2896 // In theory this shouldn't fail.
2897 if (!network_thread()->Invoke<bool>(
2898 RTC_FROM_HERE,
2899 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2900 stun_servers, turn_servers, modified_config.type,
2901 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002902 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002903 modified_config.turn_customizer,
2904 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002905 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002906 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2907 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002908
deadbeefd1a38b52016-12-10 13:15:33 -08002909 // As described in JSEP, calling setConfiguration with new ICE servers or
2910 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2911 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002912 if (modified_config.servers != configuration_.servers ||
2913 modified_config.type != configuration_.type ||
2914 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002915 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002916 }
skvladd1f5fda2017-02-03 16:54:05 -08002917
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002918 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002919
Zhi Huangb57e1692018-06-12 11:41:11 -07002920 if (configuration_.active_reset_srtp_params !=
2921 modified_config.active_reset_srtp_params) {
2922 transport_controller_->SetActiveResetSrtpParams(
2923 modified_config.active_reset_srtp_params);
2924 }
2925
deadbeef293e9262017-01-11 12:28:30 -08002926 configuration_ = modified_config;
2927 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002928}
2929
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002930bool PeerConnection::AddIceCandidate(
2931 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002932 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002933 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002934 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002935 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07002936 return false;
2937 }
Steve Antond25da372017-11-06 14:50:29 -08002938
2939 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002940 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002941 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002942 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002943 return false;
2944 }
2945
2946 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002947 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002948 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08002949 return false;
2950 }
2951
2952 bool valid = false;
2953 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2954 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002955 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08002956 return false;
2957 }
2958
2959 // Add this candidate to the remote session description.
2960 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002961 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002962 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08002963 return false;
2964 }
2965
2966 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002967 bool result = UseCandidate(ice_candidate);
2968 if (result) {
2969 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
2970 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
2971 } else {
2972 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
2973 }
2974 return result;
Steve Antond25da372017-11-06 14:50:29 -08002975 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002976 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002977 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08002978 return true;
2979 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002980}
2981
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002982bool PeerConnection::RemoveIceCandidates(
2983 const std::vector<cricket::Candidate>& candidates) {
2984 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002985 if (IsClosed()) {
2986 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2987 return false;
2988 }
2989
Steve Antond25da372017-11-06 14:50:29 -08002990 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002991 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2992 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002993 return false;
2994 }
2995
2996 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002997 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002998 return false;
2999 }
3000
3001 size_t number_removed =
3002 mutable_remote_description()->RemoveCandidates(candidates);
3003 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003004 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003005 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003006 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003007 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003008 }
3009
3010 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003011 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3012 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003013 RTC_LOG(LS_ERROR)
3014 << "RemoveIceCandidates: Error when removing remote candidates: "
3015 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003016 }
3017 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003018}
3019
Niels Möller0c4f7be2018-05-07 14:01:37 +02003020RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003021 if (!worker_thread()->IsCurrent()) {
3022 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003023 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003024 }
3025
Niels Möller0c4f7be2018-05-07 14:01:37 +02003026 const bool has_min = bitrate.min_bitrate_bps.has_value();
3027 const bool has_start = bitrate.start_bitrate_bps.has_value();
3028 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003029 if (has_min && *bitrate.min_bitrate_bps < 0) {
3030 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3031 "min_bitrate_bps <= 0");
3032 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003033 if (has_start) {
3034 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003035 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003036 "start_bitrate_bps < min_bitrate_bps");
3037 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003038 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3039 "curent_bitrate_bps < 0");
3040 }
3041 }
3042 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003043 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003044 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003045 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003046 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3047 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3048 "max_bitrate_bps < min_bitrate_bps");
3049 } else if (*bitrate.max_bitrate_bps < 0) {
3050 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3051 "max_bitrate_bps < 0");
3052 }
3053 }
3054
zstein4b979802017-06-02 14:37:37 -07003055 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003056 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003057
3058 return RTCError::OK();
3059}
3060
Alex Narest78609d52017-10-20 10:37:47 +02003061void PeerConnection::SetBitrateAllocationStrategy(
3062 std::unique_ptr<rtc::BitrateAllocationStrategy>
3063 bitrate_allocation_strategy) {
3064 rtc::Thread* worker_thread = factory_->worker_thread();
3065 if (!worker_thread->IsCurrent()) {
3066 rtc::BitrateAllocationStrategy* strategy_raw =
3067 bitrate_allocation_strategy.release();
3068 auto functor = [this, strategy_raw]() {
3069 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003070 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003071 };
3072 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3073 return;
3074 }
3075 RTC_DCHECK(call_.get());
3076 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3077}
3078
henrika5f6bf242017-11-01 11:06:56 +01003079void PeerConnection::SetAudioPlayout(bool playout) {
3080 if (!worker_thread()->IsCurrent()) {
3081 worker_thread()->Invoke<void>(
3082 RTC_FROM_HERE,
3083 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3084 return;
3085 }
3086 auto audio_state =
3087 factory_->channel_manager()->media_engine()->GetAudioState();
3088 audio_state->SetPlayout(playout);
3089}
3090
3091void PeerConnection::SetAudioRecording(bool recording) {
3092 if (!worker_thread()->IsCurrent()) {
3093 worker_thread()->Invoke<void>(
3094 RTC_FROM_HERE,
3095 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3096 return;
3097 }
3098 auto audio_state =
3099 factory_->channel_manager()->media_engine()->GetAudioState();
3100 audio_state->SetRecording(recording);
3101}
3102
Steve Anton8c0f7a72017-10-03 10:03:10 -07003103std::unique_ptr<rtc::SSLCertificate>
3104PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003105 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3106 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003107 return nullptr;
3108 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003109 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003110}
3111
Zhi Huang70b820f2018-01-27 14:16:15 -08003112std::unique_ptr<rtc::SSLCertChain>
3113PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003114 auto audio_transceiver = GetFirstAudioTransceiver();
3115 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003116 return nullptr;
3117 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003118 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003119 audio_transceiver->internal()->channel()->transport_name());
3120}
3121
3122rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3123PeerConnection::GetFirstAudioTransceiver() const {
3124 for (auto transceiver : transceivers_) {
3125 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3126 return transceiver;
3127 }
3128 }
3129 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003130}
3131
ivoc14d5dbe2016-07-04 07:06:55 -07003132bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3133 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003134 // TODO(eladalon): It would be better to not allow negative values into PC.
3135 const size_t max_size = (max_size_bytes < 0)
3136 ? RtcEventLog::kUnlimitedOutput
3137 : rtc::saturated_cast<size_t>(max_size_bytes);
3138 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003139 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003140 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003141}
3142
Bjorn Tereliusde939432017-11-20 17:38:14 +01003143bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3144 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003145 // TODO(eladalon): In C++14, this can be done with a lambda.
3146 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003147 bool operator()() {
3148 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3149 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003150 PeerConnection* const pc;
3151 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003152 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003153 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003154 return worker_thread()->Invoke<bool>(
3155 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003156}
3157
3158void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003159 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003160 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3161}
3162
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003163const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003164 return pending_local_description_ ? pending_local_description_.get()
3165 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166}
3167
3168const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003169 return pending_remote_description_ ? pending_remote_description_.get()
3170 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003171}
3172
deadbeeffe4a8a42016-12-20 17:56:17 -08003173const SessionDescriptionInterface* PeerConnection::current_local_description()
3174 const {
Steve Anton75737c02017-11-06 10:37:17 -08003175 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003176}
3177
3178const SessionDescriptionInterface* PeerConnection::current_remote_description()
3179 const {
Steve Anton75737c02017-11-06 10:37:17 -08003180 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003181}
3182
3183const SessionDescriptionInterface* PeerConnection::pending_local_description()
3184 const {
Steve Anton75737c02017-11-06 10:37:17 -08003185 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003186}
3187
3188const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3189 const {
Steve Anton75737c02017-11-06 10:37:17 -08003190 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003191}
3192
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003193void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003194 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003195 // Update stats here so that we have the most recent stats for tracks and
3196 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003197 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003198
Steve Anton75737c02017-11-06 10:37:17 -08003199 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003200 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003201
Steve Anton8af21862017-12-15 11:20:13 -08003202 for (auto transceiver : transceivers_) {
3203 transceiver->Stop();
3204 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003205
3206 // Ensure that all asynchronous stats requests are completed before destroying
3207 // the transport controller below.
3208 if (stats_collector_) {
3209 stats_collector_->WaitForPendingRequest();
3210 }
3211
3212 // Don't destroy BaseChannels until after stats has been cleaned up so that
3213 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003214 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003215
Qingsi Wang93a84392018-01-30 17:13:09 -08003216 // The event log is used in the transport controller, which must be outlived
3217 // by the former. CreateOffer by the peer connection is implemented
3218 // asynchronously and if the peer connection is closed without resetting the
3219 // WebRTC session description factory, the session description factory would
3220 // call the transport controller.
3221 webrtc_session_desc_factory_.reset();
3222 transport_controller_.reset();
3223
deadbeef42a42632017-03-10 15:18:00 -08003224 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003225 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3226 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003227
Steve Anton978b8762017-09-29 12:15:02 -07003228 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003229 call_.reset();
3230 // The event log must outlive call (and any other object that uses it).
3231 event_log_.reset();
3232 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003233 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003234 // The .h file says that observer can be discarded after close() returns.
3235 // Make sure this is true.
3236 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003237}
3238
Steve Antonad182762018-09-05 20:22:40 +00003239void PeerConnection::OnMessage(rtc::Message* msg) {
3240 switch (msg->message_id) {
3241 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3242 SetSessionDescriptionMsg* param =
3243 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3244 param->observer->OnSuccess();
3245 delete param;
3246 break;
3247 }
3248 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3249 SetSessionDescriptionMsg* param =
3250 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3251 param->observer->OnFailure(std::move(param->error));
3252 delete param;
3253 break;
3254 }
3255 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3256 CreateSessionDescriptionMsg* param =
3257 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3258 param->observer->OnFailure(std::move(param->error));
3259 delete param;
3260 break;
3261 }
3262 case MSG_GETSTATS: {
3263 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3264 StatsReports reports;
3265 stats_->GetStats(param->track, &reports);
3266 param->observer->OnComplete(reports);
3267 delete param;
3268 break;
3269 }
3270 case MSG_FREE_DATACHANNELS: {
3271 sctp_data_channels_to_free_.clear();
3272 break;
3273 }
3274 case MSG_REPORT_USAGE_PATTERN: {
3275 ReportUsagePattern();
3276 break;
3277 }
3278 default:
3279 RTC_NOTREACHED() << "Not implemented";
3280 break;
3281 }
3282}
3283
Steve Antonafb0bb72018-02-20 11:35:37 -08003284cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3285 RTC_DCHECK(!IsUnifiedPlan());
3286 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3287 GetAudioTransceiver()->internal()->channel());
3288 if (voice_channel) {
3289 return voice_channel->media_channel();
3290 } else {
3291 return nullptr;
3292 }
3293}
3294
3295cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3296 RTC_DCHECK(!IsUnifiedPlan());
3297 auto* video_channel = static_cast<cricket::VideoChannel*>(
3298 GetVideoTransceiver()->internal()->channel());
3299 if (video_channel) {
3300 return video_channel->media_channel();
3301 } else {
3302 return nullptr;
3303 }
3304}
3305
Steve Anton4171afb2017-11-20 10:20:22 -08003306void PeerConnection::CreateAudioReceiver(
3307 MediaStreamInterface* stream,
3308 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003309 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3310 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003311 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3312 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003313 auto* audio_receiver = new AudioRtpReceiver(
3314 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003315 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003316 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3317 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3318 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003319 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003320 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003321 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003322}
3323
Steve Anton4171afb2017-11-20 10:20:22 -08003324void PeerConnection::CreateVideoReceiver(
3325 MediaStreamInterface* stream,
3326 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003327 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3328 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003329 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3330 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003331 auto* video_receiver = new VideoRtpReceiver(
3332 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003333 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003334 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3335 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3336 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003337 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003338 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003339 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340}
3341
deadbeef70ab1a12015-09-28 16:53:55 -07003342// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3343// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003344rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003345 const RtpSenderInfo& remote_sender_info) {
3346 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3347 if (!receiver) {
3348 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3349 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003350 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003351 }
Steve Anton4171afb2017-11-20 10:20:22 -08003352 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3353 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3354 } else {
3355 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3356 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003357 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003358}
3359
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003360void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3361 MediaStreamInterface* stream) {
3362 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003363 RTC_DCHECK(track);
3364 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003365 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003366 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003367 // We already have a sender for this track, so just change the stream_id
3368 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003369 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003370 return;
3371 }
3372
3373 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003374 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3375 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003376 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003377 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003378 // If the sender has already been configured in SDP, we call SetSsrc,
3379 // which will connect the sender to the underlying transport. This can
3380 // occur if a local session description that contains the ID of the sender
3381 // is set before AddStream is called. It can also occur if the local
3382 // session description is not changed and RemoveStream is called, and
3383 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003384 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003385 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003386 if (sender_info) {
3387 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003388 }
3389}
3390
3391// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3392// indefinitely, when we have unified plan SDP.
3393void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3394 MediaStreamInterface* stream) {
3395 RTC_DCHECK(!IsClosed());
3396 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003397 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003398 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3399 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003400 return;
3401 }
Steve Anton4171afb2017-11-20 10:20:22 -08003402 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003403}
3404
3405void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3406 MediaStreamInterface* stream) {
3407 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003408 RTC_DCHECK(track);
3409 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003410 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003411 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003412 // We already have a sender for this track, so just change the stream_id
3413 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003414 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003415 return;
3416 }
3417
3418 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003419 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3420 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003421 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003422 GetVideoTransceiver()->internal()->AddSender(new_sender);
3423 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003424 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003425 if (sender_info) {
3426 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003427 }
3428}
3429
3430void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3431 MediaStreamInterface* stream) {
3432 RTC_DCHECK(!IsClosed());
3433 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003434 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003435 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3436 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003437 return;
3438 }
Steve Anton4171afb2017-11-20 10:20:22 -08003439 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003440}
3441
Steve Antonba818672017-11-06 10:21:57 -08003442void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003443 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003444 if (ice_connection_state_ == new_state) {
3445 return;
3446 }
3447
deadbeefcbecd352015-09-23 11:50:27 -07003448 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003449 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003450 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003451 return;
3452 }
Steve Antonba818672017-11-06 10:21:57 -08003453
Mirko Bonadei675513b2017-11-09 11:09:25 +01003454 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3455 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003456 RTC_DCHECK(ice_connection_state_ !=
3457 PeerConnectionInterface::kIceConnectionClosed);
3458
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003459 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003460 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003461}
3462
3463void PeerConnection::OnIceGatheringChange(
3464 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003465 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003466 if (IsClosed()) {
3467 return;
3468 }
3469 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003470 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003471}
3472
jbauch81bf7b02017-03-25 08:31:12 -07003473void PeerConnection::OnIceCandidate(
3474 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003475 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003476 if (IsClosed()) {
3477 return;
3478 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003479 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003480 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3481 candidate->candidate().address().IsPrivateIP()) {
3482 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3483 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003484 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003485}
3486
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003487void PeerConnection::OnIceCandidatesRemoved(
3488 const std::vector<cricket::Candidate>& candidates) {
3489 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003490 if (IsClosed()) {
3491 return;
3492 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003493 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003494}
3495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003496void PeerConnection::ChangeSignalingState(
3497 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003498 RTC_DCHECK(signaling_thread()->IsCurrent());
3499 if (signaling_state_ == signaling_state) {
3500 return;
3501 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003502 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3503 << GetSignalingStateString(signaling_state_)
3504 << " New state: "
3505 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506 signaling_state_ = signaling_state;
3507 if (signaling_state == kClosed) {
3508 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003509 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003510 if (ice_gathering_state_ != kIceGatheringComplete) {
3511 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003512 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003513 }
3514 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003515 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003516}
3517
deadbeefeb459812015-12-15 19:24:43 -08003518void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3519 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003520 if (IsClosed()) {
3521 return;
3522 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003523 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003524 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003525}
3526
deadbeefeb459812015-12-15 19:24:43 -08003527void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3528 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003529 if (IsClosed()) {
3530 return;
3531 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003532 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003533 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003534}
3535
3536void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3537 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003538 if (IsClosed()) {
3539 return;
3540 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003541 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003542 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003543}
3544
3545void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3546 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003547 if (IsClosed()) {
3548 return;
3549 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003550 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003551 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003552}
3553
Henrik Boström31638672017-11-23 17:48:32 +01003554void PeerConnection::PostSetSessionDescriptionSuccess(
3555 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003556 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3557 signaling_thread()->Post(RTC_FROM_HERE, this,
3558 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003559}
3560
deadbeefab9b2d12015-10-14 11:33:11 -07003561void PeerConnection::PostSetSessionDescriptionFailure(
3562 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003563 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003564 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003565 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3566 msg->error = std::move(error);
3567 signaling_thread()->Post(RTC_FROM_HERE, this,
3568 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003569}
3570
3571void PeerConnection::PostCreateSessionDescriptionFailure(
3572 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003573 RTCError error) {
3574 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003575 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3576 msg->error = std::move(error);
3577 signaling_thread()->Post(RTC_FROM_HERE, this,
3578 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003579}
3580
zhihuang1c378ed2017-08-17 14:10:50 -07003581void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003582 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003583 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003584 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003585
Steve Antondcc3c022017-12-22 16:02:54 -08003586 if (IsUnifiedPlan()) {
3587 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3588 } else {
3589 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3590 }
3591
Steve Antonfa2260d2017-12-28 16:38:23 -08003592 // Intentionally unset the data channel type for RTP data channel with the
3593 // second condition. Otherwise the RTP data channels would be successfully
3594 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3595 // when building with chromium. We want to leave RTP data channels broken, so
3596 // people won't try to use them.
3597 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3598 session_options->data_channel_type = data_channel_type();
3599 }
3600
Steve Antondcc3c022017-12-22 16:02:54 -08003601 // Apply ICE restart flag and renomination flag.
3602 for (auto& options : session_options->media_description_options) {
3603 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3604 options.transport_options.enable_ice_renomination =
3605 configuration_.enable_ice_renomination;
3606 }
3607
3608 session_options->rtcp_cname = rtcp_cname_;
3609 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003610 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003611}
3612
3613void PeerConnection::GetOptionsForPlanBOffer(
3614 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3615 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003616 // Figure out transceiver directional preferences.
3617 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3618 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3619
3620 // By default, generate sendrecv/recvonly m= sections.
3621 bool recv_audio = true;
3622 bool recv_video = true;
3623
3624 // By default, only offer a new m= section if we have media to send with it.
3625 bool offer_new_audio_description = send_audio;
3626 bool offer_new_video_description = send_video;
3627 bool offer_new_data_description = HasDataChannels();
3628
3629 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003630 if (offer_answer_options.offer_to_receive_audio !=
3631 RTCOfferAnswerOptions::kUndefined) {
3632 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003633 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003634 offer_new_audio_description ||
3635 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003636 }
Steve Antondcc3c022017-12-22 16:02:54 -08003637 if (offer_answer_options.offer_to_receive_video !=
3638 RTCOfferAnswerOptions::kUndefined) {
3639 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003640 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003641 offer_new_video_description ||
3642 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003643 }
3644
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003645 absl::optional<size_t> audio_index;
3646 absl::optional<size_t> video_index;
3647 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003648 // If a current description exists, generate m= sections in the same order,
3649 // using the first audio/video/data section that appears and rejecting
3650 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003651 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003652 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003653 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003654 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3655 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3656 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003657 }
3658
zhihuang1c378ed2017-08-17 14:10:50 -07003659 // Add audio/video/data m= sections to the end if needed.
3660 if (!audio_index && offer_new_audio_description) {
3661 session_options->media_description_options.push_back(
3662 cricket::MediaDescriptionOptions(
3663 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003664 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3665 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003666 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003667 }
zhihuang1c378ed2017-08-17 14:10:50 -07003668 if (!video_index && offer_new_video_description) {
3669 session_options->media_description_options.push_back(
3670 cricket::MediaDescriptionOptions(
3671 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003672 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3673 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003674 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003675 }
zhihuang1c378ed2017-08-17 14:10:50 -07003676 if (!data_index && offer_new_data_description) {
3677 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003678 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003679 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003680 }
3681
3682 cricket::MediaDescriptionOptions* audio_media_description_options =
3683 !audio_index ? nullptr
3684 : &session_options->media_description_options[*audio_index];
3685 cricket::MediaDescriptionOptions* video_media_description_options =
3686 !video_index ? nullptr
3687 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003688
Steve Anton4171afb2017-11-20 10:20:22 -08003689 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003690 video_media_description_options,
3691 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003692}
3693
3694// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3695// and return a reference to it.
3696// Generated MIDs should be no more than 3 bytes long to take up less space in
3697// the RTP packet.
3698static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3699 RTC_DCHECK(used_mids);
3700 // We're boring: just generate MIDs 0, 1, 2, ...
3701 size_t i = 0;
3702 std::set<std::string>::iterator it;
3703 bool inserted;
3704 do {
3705 std::string mid = rtc::ToString(i++);
3706 auto insert_result = used_mids->insert(mid);
3707 it = insert_result.first;
3708 inserted = insert_result.second;
3709 } while (!inserted);
3710 return *it;
3711}
3712
3713static cricket::MediaDescriptionOptions
3714GetMediaDescriptionOptionsForTransceiver(
3715 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3716 transceiver,
3717 const std::string& mid) {
3718 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003719 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003720 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003721 // This behavior is specified in JSEP. The gist is that:
3722 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3723 // sendrecv.
3724 // 2. If the MSID is included, then it must be included in any subsequent
3725 // offer/answer exactly the same until the RtpTransceiver is stopped.
3726 if (!transceiver->stopped() &&
3727 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3728 transceiver->internal()->has_ever_been_used_to_send())) {
3729 cricket::SenderOptions sender_options;
3730 sender_options.track_id = transceiver->sender()->id();
3731 sender_options.stream_ids = transceiver->sender()->stream_ids();
3732 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3733 // set in the RTP parameters when the transceiver was added.
3734 sender_options.num_sim_layers = 1;
3735 media_description_options.sender_options.push_back(sender_options);
3736 }
Steve Antondcc3c022017-12-22 16:02:54 -08003737 return media_description_options;
3738}
3739
3740void PeerConnection::GetOptionsForUnifiedPlanOffer(
3741 const RTCOfferAnswerOptions& offer_answer_options,
3742 cricket::MediaSessionOptions* session_options) {
3743 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3744 // Offers) and 5.2.2 (Subsequent Offers).
3745 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3746 const ContentInfos& local_contents =
3747 (local_description() ? local_description()->description()->contents()
3748 : ContentInfos());
3749 const ContentInfos& remote_contents =
3750 (remote_description() ? remote_description()->description()->contents()
3751 : ContentInfos());
3752 // The mline indices that can be recycled. New transceivers should reuse these
3753 // slots first.
3754 std::queue<size_t> recycleable_mline_indices;
3755 // Track the MIDs used in previous offer/answer exchanges and the current
3756 // offer so that new, unique MIDs are generated.
3757 std::set<std::string> used_mids = seen_mids_;
3758 // First, go through each media section that exists in either the local or
3759 // remote description and generate a media section in this offer for the
3760 // associated transceiver. If a media section can be recycled, generate a
3761 // default, rejected media section here that can be later overwritten.
3762 for (size_t i = 0;
3763 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3764 // Either |local_content| or |remote_content| is non-null.
3765 const ContentInfo* local_content =
3766 (i < local_contents.size() ? &local_contents[i] : nullptr);
3767 const ContentInfo* remote_content =
3768 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3769 bool had_been_rejected = (local_content && local_content->rejected) ||
3770 (remote_content && remote_content->rejected);
3771 const std::string& mid =
3772 (local_content ? local_content->name : remote_content->name);
3773 cricket::MediaType media_type =
3774 (local_content ? local_content->media_description()->type()
3775 : remote_content->media_description()->type());
3776 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3777 media_type == cricket::MEDIA_TYPE_VIDEO) {
3778 auto transceiver = GetAssociatedTransceiver(mid);
3779 RTC_CHECK(transceiver);
3780 // A media section is considered eligible for recycling if it is marked as
3781 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003782 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003783 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003784 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3785 RtpTransceiverDirection::kInactive,
3786 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003787 recycleable_mline_indices.push(i);
3788 } else {
3789 session_options->media_description_options.push_back(
3790 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3791 // CreateOffer shouldn't really cause any state changes in
3792 // PeerConnection, but we need a way to match new transceivers to new
3793 // media sections in SetLocalDescription and JSEP specifies this is done
3794 // by recording the index of the media section generated for the
3795 // transceiver in the offer.
3796 transceiver->internal()->set_mline_index(i);
3797 }
3798 } else {
3799 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003800 RTC_CHECK(GetDataMid());
3801 if (had_been_rejected || mid != *GetDataMid()) {
3802 session_options->media_description_options.push_back(
3803 GetMediaDescriptionOptionsForRejectedData(mid));
3804 } else {
3805 session_options->media_description_options.push_back(
3806 GetMediaDescriptionOptionsForActiveData(mid));
3807 }
Steve Antondcc3c022017-12-22 16:02:54 -08003808 }
3809 }
3810 // Next, look for transceivers that are newly added (that is, are not stopped
3811 // and not associated). Reuse media sections marked as recyclable first,
3812 // otherwise append to the end of the offer. New media sections should be
3813 // added in the order they were added to the PeerConnection.
3814 for (auto transceiver : transceivers_) {
3815 if (transceiver->mid() || transceiver->stopped()) {
3816 continue;
3817 }
3818 size_t mline_index;
3819 if (!recycleable_mline_indices.empty()) {
3820 mline_index = recycleable_mline_indices.front();
3821 recycleable_mline_indices.pop();
3822 session_options->media_description_options[mline_index] =
3823 GetMediaDescriptionOptionsForTransceiver(transceiver,
3824 AllocateMid(&used_mids));
3825 } else {
3826 mline_index = session_options->media_description_options.size();
3827 session_options->media_description_options.push_back(
3828 GetMediaDescriptionOptionsForTransceiver(transceiver,
3829 AllocateMid(&used_mids)));
3830 }
3831 // See comment above for why CreateOffer changes the transceiver's state.
3832 transceiver->internal()->set_mline_index(mline_index);
3833 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003834 // Lastly, add a m-section if we have local data channels and an m section
3835 // does not already exist.
3836 if (!GetDataMid() && HasDataChannels()) {
3837 session_options->media_description_options.push_back(
3838 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3839 }
Steve Antondcc3c022017-12-22 16:02:54 -08003840}
3841
3842void PeerConnection::GetOptionsForAnswer(
3843 const RTCOfferAnswerOptions& offer_answer_options,
3844 cricket::MediaSessionOptions* session_options) {
3845 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3846
3847 if (IsUnifiedPlan()) {
3848 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3849 } else {
3850 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3851 }
3852
Steve Antonfa2260d2017-12-28 16:38:23 -08003853 // Intentionally unset the data channel type for RTP data channel. Otherwise
3854 // the RTP data channels would be successfully negotiated by default and the
3855 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3856 // We want to leave RTP data channels broken, so people won't try to use them.
3857 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3858 session_options->data_channel_type = data_channel_type();
3859 }
3860
Steve Antondcc3c022017-12-22 16:02:54 -08003861 // Apply ICE renomination flag.
3862 for (auto& options : session_options->media_description_options) {
3863 options.transport_options.enable_ice_renomination =
3864 configuration_.enable_ice_renomination;
3865 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003866
3867 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003868 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003869 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003870}
3871
Steve Antondcc3c022017-12-22 16:02:54 -08003872void PeerConnection::GetOptionsForPlanBAnswer(
3873 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003874 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003875 // Figure out transceiver directional preferences.
3876 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3877 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3878
3879 // By default, generate sendrecv/recvonly m= sections. The direction is also
3880 // restricted by the direction in the offer.
3881 bool recv_audio = true;
3882 bool recv_video = true;
3883
3884 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003885 if (offer_answer_options.offer_to_receive_audio !=
3886 RTCOfferAnswerOptions::kUndefined) {
3887 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003888 }
Steve Antondcc3c022017-12-22 16:02:54 -08003889 if (offer_answer_options.offer_to_receive_video !=
3890 RTCOfferAnswerOptions::kUndefined) {
3891 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003892 }
3893
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003894 absl::optional<size_t> audio_index;
3895 absl::optional<size_t> video_index;
3896 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003897
3898 // Generate m= sections that match those in the offer.
3899 // Note that mediasession.cc will handle intersection our preferred
3900 // direction with the offered direction.
3901 GenerateMediaDescriptionOptions(
3902 remote_description(),
3903 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3904 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3905 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003906
3907 cricket::MediaDescriptionOptions* audio_media_description_options =
3908 !audio_index ? nullptr
3909 : &session_options->media_description_options[*audio_index];
3910 cricket::MediaDescriptionOptions* video_media_description_options =
3911 !video_index ? nullptr
3912 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003913
Steve Anton4171afb2017-11-20 10:20:22 -08003914 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003915 video_media_description_options,
3916 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003917}
zhihuangaf388472016-11-02 16:49:48 -07003918
Steve Antondcc3c022017-12-22 16:02:54 -08003919void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3920 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3921 cricket::MediaSessionOptions* session_options) {
3922 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3923 // Answers) and 5.3.2 (Subsequent Answers).
3924 RTC_DCHECK(remote_description());
3925 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3926 for (const ContentInfo& content :
3927 remote_description()->description()->contents()) {
3928 cricket::MediaType media_type = content.media_description()->type();
3929 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3930 media_type == cricket::MEDIA_TYPE_VIDEO) {
3931 auto transceiver = GetAssociatedTransceiver(content.name);
3932 RTC_CHECK(transceiver);
3933 session_options->media_description_options.push_back(
3934 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3935 } else {
3936 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003937 // Reject all data sections if data channels are disabled.
3938 // Reject a data section if it has already been rejected.
3939 // Reject all data sections except for the first one.
3940 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3941 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003942 session_options->media_description_options.push_back(
3943 GetMediaDescriptionOptionsForRejectedData(content.name));
3944 } else {
3945 session_options->media_description_options.push_back(
3946 GetMediaDescriptionOptionsForActiveData(content.name));
3947 }
Steve Antondcc3c022017-12-22 16:02:54 -08003948 }
3949 }
htaa2a49d92016-03-04 02:51:39 -08003950}
3951
zhihuang1c378ed2017-08-17 14:10:50 -07003952void PeerConnection::GenerateMediaDescriptionOptions(
3953 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003954 RtpTransceiverDirection audio_direction,
3955 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003956 absl::optional<size_t>* audio_index,
3957 absl::optional<size_t>* video_index,
3958 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003959 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003960 for (const cricket::ContentInfo& content :
3961 session_desc->description()->contents()) {
3962 if (IsAudioContent(&content)) {
3963 // If we already have an audio m= section, reject this extra one.
3964 if (*audio_index) {
3965 session_options->media_description_options.push_back(
3966 cricket::MediaDescriptionOptions(
3967 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003968 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003969 } else {
3970 session_options->media_description_options.push_back(
3971 cricket::MediaDescriptionOptions(
3972 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003973 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003974 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003975 }
3976 } else if (IsVideoContent(&content)) {
3977 // If we already have an video m= section, reject this extra one.
3978 if (*video_index) {
3979 session_options->media_description_options.push_back(
3980 cricket::MediaDescriptionOptions(
3981 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003982 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003983 } else {
3984 session_options->media_description_options.push_back(
3985 cricket::MediaDescriptionOptions(
3986 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003987 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003988 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003989 }
3990 } else {
3991 RTC_DCHECK(IsDataContent(&content));
3992 // If we already have an data m= section, reject this extra one.
3993 if (*data_index) {
3994 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003995 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003996 } else {
3997 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003998 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003999 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004000 }
4001 }
htaa2a49d92016-03-04 02:51:39 -08004002 }
deadbeefab9b2d12015-10-14 11:33:11 -07004003}
4004
Steve Antonfa2260d2017-12-28 16:38:23 -08004005cricket::MediaDescriptionOptions
4006PeerConnection::GetMediaDescriptionOptionsForActiveData(
4007 const std::string& mid) const {
4008 // Direction for data sections is meaningless, but legacy endpoints might
4009 // expect sendrecv.
4010 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4011 RtpTransceiverDirection::kSendRecv,
4012 /*stopped=*/false);
4013 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4014 return options;
4015}
4016
4017cricket::MediaDescriptionOptions
4018PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4019 const std::string& mid) const {
4020 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4021 RtpTransceiverDirection::kInactive,
4022 /*stopped=*/true);
4023 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4024 return options;
4025}
4026
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004027absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004028 switch (data_channel_type_) {
4029 case cricket::DCT_RTP:
4030 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004031 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004032 }
4033 return rtp_data_channel_->content_name();
4034 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004035 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004036 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004037 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004038 }
4039}
4040
Steve Anton4171afb2017-11-20 10:20:22 -08004041void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4042 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4043 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004044 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004045}
4046
Steve Anton4171afb2017-11-20 10:20:22 -08004047void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004048 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004049 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004050 cricket::MediaType media_type,
4051 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004052 RTC_DCHECK(!IsUnifiedPlan());
4053
Steve Anton4171afb2017-11-20 10:20:22 -08004054 std::vector<RtpSenderInfo>* current_senders =
4055 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004056
Steve Anton4171afb2017-11-20 10:20:22 -08004057 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004058 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004059 for (auto sender_it = current_senders->begin();
4060 sender_it != current_senders->end();
4061 /* incremented manually */) {
4062 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004063 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004064 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004065 std::string params_stream_id;
4066 if (params) {
4067 params_stream_id =
4068 (!params->first_stream_id().empty() ? params->first_stream_id()
4069 : kDefaultStreamId);
4070 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004071 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004072 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004073 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004074 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004075 sender_exists) {
4076 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004077 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004078 OnRemoteSenderRemoved(info, media_type);
4079 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004080 }
4081 }
4082
Steve Anton4171afb2017-11-20 10:20:22 -08004083 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004084 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004085 if (!params.has_ssrcs()) {
4086 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4087 // sender, this means it is coming from a Unified Plan endpoint,so we just
4088 // create a default.
4089 default_sender_needed = true;
4090 break;
4091 }
4092
Seth Hampson845e8782018-03-02 11:34:10 -08004093 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004094 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004095 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4096 // not supported in Plan B, we just take the first here and create the
4097 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004098 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004099 (!params.first_stream_id().empty() ? params.first_stream_id()
4100 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004101 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004102 uint32_t ssrc = params.first_ssrc();
4103
4104 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004105 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004106 if (!stream) {
4107 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004108 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004109 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004110 remote_streams_->AddStream(stream);
4111 new_streams->AddStream(stream);
4112 }
4113
Steve Anton4171afb2017-11-20 10:20:22 -08004114 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004115 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004116 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004117 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004118 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004119 }
4120 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004121
Steve Anton4171afb2017-11-20 10:20:22 -08004122 // Add default sender if necessary.
4123 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004124 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004125 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004126 if (!default_stream) {
4127 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004128 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004129 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004130 remote_streams_->AddStream(default_stream);
4131 new_streams->AddStream(default_stream);
4132 }
Steve Anton4171afb2017-11-20 10:20:22 -08004133 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4134 ? kDefaultAudioSenderId
4135 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004136 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004137 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004138 if (!default_sender_info) {
4139 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004140 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004141 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004142 }
4143 }
deadbeefab9b2d12015-10-14 11:33:11 -07004144}
4145
Steve Anton4171afb2017-11-20 10:20:22 -08004146void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4147 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004148 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4149 << " receiver for track_id=" << sender_info.sender_id
4150 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004151
Steve Anton3d954a62018-04-02 11:27:23 -07004152 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004153 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004154 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004155 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004156 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004157 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004158 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004159 }
4160}
4161
Steve Anton4171afb2017-11-20 10:20:22 -08004162void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4163 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004164 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4165 << " receiver for track_id=" << sender_info.sender_id
4166 << " and stream_id=" << sender_info.stream_id;
4167
Seth Hampson845e8782018-03-02 11:34:10 -08004168 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004169
Henrik Boström933d8b02017-10-10 10:05:16 -07004170 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004171 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004172 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4173 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004174 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004175 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004176 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004177 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004178 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004179 }
4180 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004181 // Stopping or destroying a VideoRtpReceiver will end the
4182 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004183 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004184 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004185 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004186 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004187 // There's no guarantee the track is still available, e.g. the track may
4188 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004189 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004190 }
4191 } else {
nisseede5da42017-01-12 05:15:36 -08004192 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004193 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004194 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004195 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004196 }
deadbeefab9b2d12015-10-14 11:33:11 -07004197}
4198
4199void PeerConnection::UpdateEndedRemoteMediaStreams() {
4200 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4201 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4202 MediaStreamInterface* stream = remote_streams_->at(i);
4203 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4204 streams_to_remove.push_back(stream);
4205 }
4206 }
4207
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004208 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004209 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004210 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004211 }
4212}
4213
Steve Anton4171afb2017-11-20 10:20:22 -08004214void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004215 const std::vector<cricket::StreamParams>& streams,
4216 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004217 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004218
Seth Hampson845e8782018-03-02 11:34:10 -08004219 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004220 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004221 for (auto sender_it = current_senders->begin();
4222 sender_it != current_senders->end();
4223 /* incremented manually */) {
4224 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004225 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004226 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4227 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004228 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004229 OnLocalSenderRemoved(info, media_type);
4230 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004231 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004232 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004233 }
4234 }
4235
Steve Anton4171afb2017-11-20 10:20:22 -08004236 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004237 for (const cricket::StreamParams& params : streams) {
4238 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004239 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004240 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004241 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004242 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004243 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004244 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004245 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004246 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004247 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004248 }
4249 }
4250}
4251
Steve Anton4171afb2017-11-20 10:20:22 -08004252void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4253 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004254 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004255 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004256 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004257 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4258 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004259 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004260 return;
4261 }
4262
deadbeeffac06552015-11-25 11:26:01 -08004263 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004264 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004265 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004266 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004267 }
deadbeeffac06552015-11-25 11:26:01 -08004268
Seth Hampson5b4f0752018-04-02 16:31:36 -07004269 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004270 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004271}
4272
Steve Anton4171afb2017-11-20 10:20:22 -08004273void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4274 cricket::MediaType media_type) {
4275 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004276 if (!sender) {
4277 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004278 // SessionDescriptions has been renegotiated.
4279 return;
4280 }
deadbeeffac06552015-11-25 11:26:01 -08004281
4282 // A sender has been removed from the SessionDescription but it's still
4283 // associated with the PeerConnection. This only occurs if the SDP doesn't
4284 // match with the calls to CreateSender, AddStream and RemoveStream.
4285 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004286 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004287 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004288 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004289 }
deadbeeffac06552015-11-25 11:26:01 -08004290
Steve Anton4171afb2017-11-20 10:20:22 -08004291 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004292}
4293
4294void PeerConnection::UpdateLocalRtpDataChannels(
4295 const cricket::StreamParamsVec& streams) {
4296 std::vector<std::string> existing_channels;
4297
4298 // Find new and active data channels.
4299 for (const cricket::StreamParams& params : streams) {
4300 // |it->sync_label| is actually the data channel label. The reason is that
4301 // we use the same naming of data channels as we do for
4302 // MediaStreams and Tracks.
4303 // For MediaStreams, the sync_label is the MediaStream label and the
4304 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004305 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004306 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004307 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004308 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004309 continue;
4310 }
4311 // Set the SSRC the data channel should use for sending.
4312 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4313 existing_channels.push_back(data_channel_it->first);
4314 }
4315
4316 UpdateClosingRtpDataChannels(existing_channels, true);
4317}
4318
4319void PeerConnection::UpdateRemoteRtpDataChannels(
4320 const cricket::StreamParamsVec& streams) {
4321 std::vector<std::string> existing_channels;
4322
4323 // Find new and active data channels.
4324 for (const cricket::StreamParams& params : streams) {
4325 // The data channel label is either the mslabel or the SSRC if the mslabel
4326 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004327 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004328 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004329 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004330 auto data_channel_it = rtp_data_channels_.find(label);
4331 if (data_channel_it == rtp_data_channels_.end()) {
4332 // This is a new data channel.
4333 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4334 } else {
4335 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4336 }
4337 existing_channels.push_back(label);
4338 }
4339
4340 UpdateClosingRtpDataChannels(existing_channels, false);
4341}
4342
4343void PeerConnection::UpdateClosingRtpDataChannels(
4344 const std::vector<std::string>& active_channels,
4345 bool is_local_update) {
4346 auto it = rtp_data_channels_.begin();
4347 while (it != rtp_data_channels_.end()) {
4348 DataChannel* data_channel = it->second;
4349 if (std::find(active_channels.begin(), active_channels.end(),
4350 data_channel->label()) != active_channels.end()) {
4351 ++it;
4352 continue;
4353 }
4354
4355 if (is_local_update) {
4356 data_channel->SetSendSsrc(0);
4357 } else {
4358 data_channel->RemotePeerRequestClose();
4359 }
4360
4361 if (data_channel->state() == DataChannel::kClosed) {
4362 rtp_data_channels_.erase(it);
4363 it = rtp_data_channels_.begin();
4364 } else {
4365 ++it;
4366 }
4367 }
4368}
4369
4370void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4371 uint32_t remote_ssrc) {
4372 rtc::scoped_refptr<DataChannel> channel(
4373 InternalCreateDataChannel(label, nullptr));
4374 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004375 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004376 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004377 return;
4378 }
4379 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004380 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4381 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004382 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004383}
4384
4385rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4386 const std::string& label,
4387 const InternalDataChannelInit* config) {
4388 if (IsClosed()) {
4389 return nullptr;
4390 }
Steve Anton75737c02017-11-06 10:37:17 -08004391 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004392 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004393 << "InternalCreateDataChannel: Data is not supported in this call.";
4394 return nullptr;
4395 }
4396 InternalDataChannelInit new_config =
4397 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004398 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004399 if (new_config.id < 0) {
4400 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004401 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004402 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004403 RTC_LOG(LS_ERROR)
4404 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004405 return nullptr;
4406 }
4407 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004408 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004409 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004410 return nullptr;
4411 }
4412 }
4413
Steve Anton75737c02017-11-06 10:37:17 -08004414 rtc::scoped_refptr<DataChannel> channel(
4415 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004416 if (!channel) {
4417 sid_allocator_.ReleaseSid(new_config.id);
4418 return nullptr;
4419 }
4420
4421 if (channel->data_channel_type() == cricket::DCT_RTP) {
4422 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004423 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4424 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004425 return nullptr;
4426 }
4427 rtp_data_channels_[channel->label()] = channel;
4428 } else {
4429 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4430 sctp_data_channels_.push_back(channel);
4431 channel->SignalClosed.connect(this,
4432 &PeerConnection::OnSctpDataChannelClosed);
4433 }
4434
Steve Anton2d8609c2018-01-23 16:38:46 -08004435 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004436 return channel;
4437}
4438
4439bool PeerConnection::HasDataChannels() const {
4440 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4441}
4442
4443void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4444 for (const auto& channel : sctp_data_channels_) {
4445 if (channel->id() < 0) {
4446 int sid;
4447 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004448 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004449 continue;
4450 }
4451 channel->SetSctpSid(sid);
4452 }
4453 }
4454}
4455
4456void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004457 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004458 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4459 ++it) {
4460 if (it->get() == channel) {
4461 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004462 // After the closing procedure is done, it's safe to use this ID for
4463 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004464 sid_allocator_.ReleaseSid(channel->id());
4465 }
deadbeefbd292462015-12-14 18:15:29 -08004466 // Since this method is triggered by a signal from the DataChannel,
4467 // we can't free it directly here; we need to free it asynchronously.
4468 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004469 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004470 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4471 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004472 return;
4473 }
4474 }
4475}
4476
deadbeefab9b2d12015-10-14 11:33:11 -07004477void PeerConnection::OnDataChannelDestroyed() {
4478 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4479 // DataChannel may callback to us and try to modify the list.
4480 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4481 temp_rtp_dcs.swap(rtp_data_channels_);
4482 for (const auto& kv : temp_rtp_dcs) {
4483 kv.second->OnTransportChannelDestroyed();
4484 }
4485
4486 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4487 temp_sctp_dcs.swap(sctp_data_channels_);
4488 for (const auto& channel : temp_sctp_dcs) {
4489 channel->OnTransportChannelDestroyed();
4490 }
4491}
4492
4493void PeerConnection::OnDataChannelOpenMessage(
4494 const std::string& label,
4495 const InternalDataChannelInit& config) {
4496 rtc::scoped_refptr<DataChannel> channel(
4497 InternalCreateDataChannel(label, &config));
4498 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004499 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004500 return;
4501 }
4502
deadbeefa601f5c2016-06-06 14:27:39 -07004503 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4504 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004505 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004506 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004507}
4508
Steve Anton4171afb2017-11-20 10:20:22 -08004509rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4510PeerConnection::GetAudioTransceiver() const {
4511 // This method only works with Plan B SDP, where there is a single
4512 // audio/video transceiver.
4513 RTC_DCHECK(!IsUnifiedPlan());
4514 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004515 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004516 return transceiver;
4517 }
4518 }
4519 RTC_NOTREACHED();
4520 return nullptr;
4521}
4522
4523rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4524PeerConnection::GetVideoTransceiver() const {
4525 // This method only works with Plan B SDP, where there is a single
4526 // audio/video transceiver.
4527 RTC_DCHECK(!IsUnifiedPlan());
4528 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004529 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004530 return transceiver;
4531 }
4532 }
4533 RTC_NOTREACHED();
4534 return nullptr;
4535}
4536
4537// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4538// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004539bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004540 switch (type) {
4541 case cricket::MEDIA_TYPE_AUDIO:
4542 return !GetAudioTransceiver()->internal()->senders().empty();
4543 case cricket::MEDIA_TYPE_VIDEO:
4544 return !GetVideoTransceiver()->internal()->senders().empty();
4545 case cricket::MEDIA_TYPE_DATA:
4546 return false;
4547 }
4548 RTC_NOTREACHED();
4549 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004550}
4551
Steve Anton4171afb2017-11-20 10:20:22 -08004552rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4553PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4554 for (auto transceiver : transceivers_) {
4555 for (auto sender : transceiver->internal()->senders()) {
4556 if (sender->track() == track) {
4557 return sender;
4558 }
4559 }
4560 }
4561 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004562}
4563
Steve Anton4171afb2017-11-20 10:20:22 -08004564rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4565PeerConnection::FindSenderById(const std::string& sender_id) const {
4566 for (auto transceiver : transceivers_) {
4567 for (auto sender : transceiver->internal()->senders()) {
4568 if (sender->id() == sender_id) {
4569 return sender;
4570 }
4571 }
4572 }
4573 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004574}
4575
Steve Anton4171afb2017-11-20 10:20:22 -08004576rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4577PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4578 for (auto transceiver : transceivers_) {
4579 for (auto receiver : transceiver->internal()->receivers()) {
4580 if (receiver->id() == receiver_id) {
4581 return receiver;
4582 }
4583 }
4584 }
4585 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004586}
4587
Steve Anton4171afb2017-11-20 10:20:22 -08004588std::vector<PeerConnection::RtpSenderInfo>*
4589PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4590 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4591 media_type == cricket::MEDIA_TYPE_VIDEO);
4592 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4593 ? &remote_audio_sender_infos_
4594 : &remote_video_sender_infos_;
4595}
4596
4597std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004598 cricket::MediaType media_type) {
4599 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4600 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004601 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4602 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004603}
4604
Steve Anton4171afb2017-11-20 10:20:22 -08004605const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4606 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004607 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004608 const std::string sender_id) const {
4609 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004610 if (sender_info.stream_id == stream_id &&
4611 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004612 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004613 }
4614 }
4615 return nullptr;
4616}
4617
4618DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4619 for (const auto& channel : sctp_data_channels_) {
4620 if (channel->id() == sid) {
4621 return channel;
4622 }
4623 }
4624 return nullptr;
4625}
4626
deadbeef91dd5672016-05-18 16:55:30 -07004627bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004628 const cricket::ServerAddresses& stun_servers,
4629 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004630 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004631 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004632 // To handle both internal and externally created port allocator, we will
4633 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004634 port_allocator_flags_ = port_allocator_->flags();
4635 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4636 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4637 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004638 // If the disable-IPv6 flag was specified, we'll not override it
4639 // by experiment.
4640 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004641 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004642 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4643 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004644 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004645 }
4646
zhihuangb09b3f92017-03-07 14:40:51 -08004647 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004648 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004649 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004650 }
4651
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004652 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004653 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004654 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004655 }
4656
honghaiz60347052016-05-31 18:29:12 -07004657 if (configuration.candidate_network_policy ==
4658 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004659 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004660 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004661 }
4662
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004663 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004664 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004665 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4666 }
4667
Qingsi Wanga2d60672018-04-11 16:57:45 -07004668 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004669 // No step delay is used while allocating ports.
4670 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4671 port_allocator_->set_candidate_filter(
4672 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004673 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004674
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004675 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004676 for (auto& turn_server : turn_servers_copy) {
4677 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004678 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004679 // Call this last since it may create pooled allocator sessions using the
4680 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004681 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004682 stun_servers, std::move(turn_servers_copy),
4683 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4684 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004685 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004686 return true;
4687}
4688
deadbeef91dd5672016-05-18 16:55:30 -07004689bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004690 const cricket::ServerAddresses& stun_servers,
4691 const std::vector<cricket::RelayServerConfig>& turn_servers,
4692 IceTransportsType type,
4693 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004694 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004695 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004696 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004697 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004698 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004699 // According to JSEP, after setLocalDescription, changing the candidate pool
4700 // size is not allowed, and changing the set of ICE servers will not result
4701 // in new candidates being gathered.
4702 if (local_description()) {
4703 port_allocator_->FreezeCandidatePool();
4704 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004705 // Add the custom tls turn servers if they exist.
4706 auto turn_servers_copy = turn_servers;
4707 for (auto& turn_server : turn_servers_copy) {
4708 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4709 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004710 // Call this last since it may create pooled allocator sessions using the
4711 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004712 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004713 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4714 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004715}
4716
Steve Antonba818672017-11-06 10:21:57 -08004717cricket::ChannelManager* PeerConnection::channel_manager() const {
4718 return factory_->channel_manager();
4719}
4720
Elad Alon99c3fe52017-10-13 16:29:40 +02004721bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004722 std::unique_ptr<RtcEventLogOutput> output,
4723 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004724 if (!event_log_) {
4725 return false;
4726 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004727 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004728}
4729
4730void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004731 if (event_log_) {
4732 event_log_->StopLogging();
4733 }
ivoc14d5dbe2016-07-04 07:06:55 -07004734}
nisseeaabdf62017-05-05 02:23:02 -07004735
Steve Anton75737c02017-11-06 10:37:17 -08004736cricket::BaseChannel* PeerConnection::GetChannel(
4737 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004738 for (auto transceiver : transceivers_) {
4739 cricket::BaseChannel* channel = transceiver->internal()->channel();
4740 if (channel && channel->content_name() == content_name) {
4741 return channel;
4742 }
Steve Anton75737c02017-11-06 10:37:17 -08004743 }
4744 if (rtp_data_channel() &&
4745 rtp_data_channel()->content_name() == content_name) {
4746 return rtp_data_channel();
4747 }
4748 return nullptr;
4749}
4750
4751bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4752 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004753 RTC_LOG(LS_INFO)
4754 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004755 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004756 return false;
4757 }
4758 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004759 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004760 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004761 return false;
4762 }
4763
Zhi Huange830e682018-03-30 10:48:35 -07004764 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4765 if (dtls_role) {
4766 *role = *dtls_role;
4767 return true;
4768 }
4769 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004770}
4771
4772bool PeerConnection::GetSslRole(const std::string& content_name,
4773 rtc::SSLRole* role) {
4774 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004775 RTC_LOG(LS_INFO)
4776 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004777 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004778 return false;
4779 }
4780
Zhi Huange830e682018-03-30 10:48:35 -07004781 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4782 if (dtls_role) {
4783 *role = *dtls_role;
4784 return true;
4785 }
4786 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004787}
4788
Steve Antonf8470812017-12-04 10:46:21 -08004789void PeerConnection::SetSessionError(SessionError error,
4790 const std::string& error_desc) {
4791 RTC_DCHECK_RUN_ON(signaling_thread());
4792 if (error != session_error_) {
4793 session_error_ = error;
4794 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004795 }
4796}
4797
Zhi Huange830e682018-03-30 10:48:35 -07004798RTCError PeerConnection::UpdateSessionState(
4799 SdpType type,
4800 cricket::ContentSource source,
4801 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004802 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004803
4804 // If there's already a pending error then no state transition should happen.
4805 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004806 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004807
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004808 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004809 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004810 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004811 }
4812
4813 // Update the signaling state according to the specified state machine (see
4814 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004815 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004816 ChangeSignalingState(source == cricket::CS_LOCAL
4817 ? PeerConnectionInterface::kHaveLocalOffer
4818 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004819 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004820 ChangeSignalingState(source == cricket::CS_LOCAL
4821 ? PeerConnectionInterface::kHaveLocalPrAnswer
4822 : PeerConnectionInterface::kHaveRemotePrAnswer);
4823 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004824 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004825 ChangeSignalingState(PeerConnectionInterface::kStable);
4826 }
4827
4828 // Update internal objects according to the session description's media
4829 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004830 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004831 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004832 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004833 }
4834
Steve Anton8a006912017-12-04 15:25:56 -08004835 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004836}
4837
Steve Anton8a006912017-12-04 15:25:56 -08004838RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004839 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004840 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004841 const SessionDescriptionInterface* sdesc =
4842 (source == cricket::CS_LOCAL ? local_description()
4843 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004844 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004845
4846 // Push down the new SDP media section for each audio/video transceiver.
4847 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004848 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004849 FindMediaSectionForTransceiver(transceiver, sdesc);
4850 cricket::BaseChannel* channel = transceiver->internal()->channel();
4851 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004852 continue;
4853 }
4854 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004855 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004856 if (!content_desc) {
4857 continue;
4858 }
4859 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004860 bool success = (source == cricket::CS_LOCAL)
4861 ? channel->SetLocalContent(content_desc, type, &error)
4862 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004863 if (!success) {
4864 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4865 }
4866 }
4867
4868 // If using the RtpDataChannel, push down the new SDP section for it too.
4869 if (rtp_data_channel_) {
4870 const ContentInfo* data_content =
4871 cricket::GetFirstDataContent(sdesc->description());
4872 if (data_content && !data_content->rejected) {
4873 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004874 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004875 if (data_desc) {
4876 std::string error;
4877 bool success =
4878 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004879 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004880 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004881 if (!success) {
4882 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4883 std::move(error));
4884 }
Steve Anton75737c02017-11-06 10:37:17 -08004885 }
4886 }
4887 }
Steve Antoned10bd92017-12-05 10:52:59 -08004888
Steve Anton75737c02017-11-06 10:37:17 -08004889 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4890 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4891 if (sctp_transport_ && local_description() && remote_description() &&
4892 cricket::GetFirstDataContent(local_description()->description()) &&
4893 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004894 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004895 RTC_FROM_HERE,
4896 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004897 if (!success) {
4898 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4899 "Failed to push down SCTP parameters.");
4900 }
Steve Anton75737c02017-11-06 10:37:17 -08004901 }
Steve Antoned10bd92017-12-05 10:52:59 -08004902
Steve Anton8a006912017-12-04 15:25:56 -08004903 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004904}
4905
4906bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4907 RTC_DCHECK(network_thread()->IsCurrent());
4908 RTC_DCHECK(local_description());
4909 RTC_DCHECK(remote_description());
4910 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4911 // When we support "max-message-size", that would also be pushed down here.
4912 return sctp_transport_->Start(
4913 GetSctpPort(local_description()->description()),
4914 GetSctpPort(remote_description()->description()));
4915}
4916
Steve Anton8a006912017-12-04 15:25:56 -08004917RTCError PeerConnection::PushdownTransportDescription(
4918 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004919 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004920 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004921
Zhi Huange830e682018-03-30 10:48:35 -07004922 if (source == cricket::CS_LOCAL) {
4923 const SessionDescriptionInterface* sdesc = local_description();
4924 RTC_DCHECK(sdesc);
4925 return transport_controller_->SetLocalDescription(type,
4926 sdesc->description());
4927 } else {
4928 const SessionDescriptionInterface* sdesc = remote_description();
4929 RTC_DCHECK(sdesc);
4930 return transport_controller_->SetRemoteDescription(type,
4931 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004932 }
Steve Anton75737c02017-11-06 10:37:17 -08004933}
4934
4935bool PeerConnection::GetTransportDescription(
4936 const SessionDescription* description,
4937 const std::string& content_name,
4938 cricket::TransportDescription* tdesc) {
4939 if (!description || !tdesc) {
4940 return false;
4941 }
4942 const TransportInfo* transport_info =
4943 description->GetTransportInfoByName(content_name);
4944 if (!transport_info) {
4945 return false;
4946 }
4947 *tdesc = transport_info->description;
4948 return true;
4949}
4950
Steve Anton75737c02017-11-06 10:37:17 -08004951cricket::IceConfig PeerConnection::ParseIceConfig(
4952 const PeerConnectionInterface::RTCConfiguration& config) const {
4953 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004954 switch (config.continual_gathering_policy) {
4955 case PeerConnectionInterface::GATHER_ONCE:
4956 gathering_policy = cricket::GATHER_ONCE;
4957 break;
4958 case PeerConnectionInterface::GATHER_CONTINUALLY:
4959 gathering_policy = cricket::GATHER_CONTINUALLY;
4960 break;
4961 default:
4962 RTC_NOTREACHED();
4963 gathering_policy = cricket::GATHER_ONCE;
4964 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004965
Steve Anton75737c02017-11-06 10:37:17 -08004966 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004967 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4968 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004969 ice_config.prioritize_most_likely_candidate_pairs =
4970 config.prioritize_most_likely_ice_candidate_pairs;
4971 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004972 RTCConfigurationToIceConfigOptionalInt(
4973 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004974 ice_config.continual_gathering_policy = gathering_policy;
4975 ice_config.presume_writable_when_fully_relayed =
4976 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004977 ice_config.ice_check_interval_strong_connectivity =
4978 config.ice_check_interval_strong_connectivity;
4979 ice_config.ice_check_interval_weak_connectivity =
4980 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004981 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004982 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004983 ice_config.regather_all_networks_interval_range =
4984 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004985 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004986 return ice_config;
4987}
4988
Steve Anton75737c02017-11-06 10:37:17 -08004989bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4990 std::string* track_id) {
4991 if (!local_description()) {
4992 return false;
4993 }
4994 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4995 track_id);
4996}
4997
4998bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4999 std::string* track_id) {
5000 if (!remote_description()) {
5001 return false;
5002 }
5003 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5004 track_id);
5005}
5006
5007bool PeerConnection::SendData(const cricket::SendDataParams& params,
5008 const rtc::CopyOnWriteBuffer& payload,
5009 cricket::SendDataResult* result) {
5010 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005011 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005012 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005013 return false;
5014 }
5015 return rtp_data_channel_
5016 ? rtp_data_channel_->SendData(params, payload, result)
5017 : network_thread()->Invoke<bool>(
5018 RTC_FROM_HERE,
5019 Bind(&cricket::SctpTransportInternal::SendData,
5020 sctp_transport_.get(), params, payload, result));
5021}
5022
5023bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5024 if (!rtp_data_channel_ && !sctp_transport_) {
5025 // Don't log an error here, because DataChannels are expected to call
5026 // ConnectDataChannel in this state. It's the only way to initially tell
5027 // whether or not the underlying transport is ready.
5028 return false;
5029 }
5030 if (rtp_data_channel_) {
5031 rtp_data_channel_->SignalReadyToSendData.connect(
5032 webrtc_data_channel, &DataChannel::OnChannelReady);
5033 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5034 &DataChannel::OnDataReceived);
5035 } else {
5036 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5037 &DataChannel::OnChannelReady);
5038 SignalSctpDataReceived.connect(webrtc_data_channel,
5039 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005040 SignalSctpClosingProcedureStartedRemotely.connect(
5041 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5042 SignalSctpClosingProcedureComplete.connect(
5043 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005044 }
5045 return true;
5046}
5047
5048void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5049 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005050 RTC_LOG(LS_ERROR)
5051 << "DisconnectDataChannel called when rtp_data_channel_ and "
5052 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005053 return;
5054 }
5055 if (rtp_data_channel_) {
5056 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5057 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5058 } else {
5059 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5060 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005061 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5062 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005063 }
5064}
5065
5066void PeerConnection::AddSctpDataStream(int sid) {
5067 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005068 RTC_LOG(LS_ERROR)
5069 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005070 return;
5071 }
5072 network_thread()->Invoke<void>(
5073 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5074 sctp_transport_.get(), sid));
5075}
5076
5077void PeerConnection::RemoveSctpDataStream(int sid) {
5078 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005079 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005080 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005081 return;
5082 }
5083 network_thread()->Invoke<void>(
5084 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5085 sctp_transport_.get(), sid));
5086}
5087
5088bool PeerConnection::ReadyToSendData() const {
5089 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5090 sctp_ready_to_send_data_;
5091}
5092
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005093absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005094 if (sctp_mid_ && transport_controller_) {
5095 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5096 if (dtls_transport) {
5097 return dtls_transport->transport_name();
5098 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005099 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005100 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005101 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005102}
5103
Qingsi Wang72a43a12018-02-20 16:03:18 -08005104cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5105 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005106 network_thread()->Invoke<void>(
5107 RTC_FROM_HERE,
5108 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5109 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005110 return candidate_states_list;
5111}
5112
Steve Anton5dfde182018-02-06 10:34:40 -08005113std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5114 const {
5115 std::map<std::string, std::string> transport_names_by_mid;
5116 for (auto transceiver : transceivers_) {
5117 cricket::BaseChannel* channel = transceiver->internal()->channel();
5118 if (channel) {
5119 transport_names_by_mid[channel->content_name()] =
5120 channel->transport_name();
5121 }
Steve Anton75737c02017-11-06 10:37:17 -08005122 }
Steve Anton5dfde182018-02-06 10:34:40 -08005123 if (rtp_data_channel_) {
5124 transport_names_by_mid[rtp_data_channel_->content_name()] =
5125 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005126 }
5127 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005128 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005129 RTC_DCHECK(transport_name);
5130 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005131 }
Steve Anton5dfde182018-02-06 10:34:40 -08005132 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005133}
5134
Steve Anton5dfde182018-02-06 10:34:40 -08005135std::map<std::string, cricket::TransportStats>
5136PeerConnection::GetTransportStatsByNames(
5137 const std::set<std::string>& transport_names) {
5138 if (!network_thread()->IsCurrent()) {
5139 return network_thread()
5140 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5141 RTC_FROM_HERE,
5142 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005143 }
Steve Anton5dfde182018-02-06 10:34:40 -08005144 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5145 for (const std::string& transport_name : transport_names) {
5146 cricket::TransportStats transport_stats;
5147 bool success =
5148 transport_controller_->GetStats(transport_name, &transport_stats);
5149 if (success) {
5150 transport_stats_by_name[transport_name] = std::move(transport_stats);
5151 } else {
5152 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5153 << transport_name;
5154 }
5155 }
5156 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005157}
5158
5159bool PeerConnection::GetLocalCertificate(
5160 const std::string& transport_name,
5161 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005162 if (!certificate) {
5163 return false;
5164 }
5165 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5166 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005167}
5168
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005169std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005170 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005171 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005172}
5173
5174cricket::DataChannelType PeerConnection::data_channel_type() const {
5175 return data_channel_type_;
5176}
5177
5178bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5179 return pending_ice_restarts_.find(content_name) !=
5180 pending_ice_restarts_.end();
5181}
5182
Steve Anton75737c02017-11-06 10:37:17 -08005183bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5184 return transport_controller_->NeedsIceRestart(content_name);
5185}
5186
5187void PeerConnection::OnCertificateReady(
5188 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5189 transport_controller_->SetLocalCertificate(certificate);
5190}
5191
5192void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005193 SetSessionError(SessionError::kTransport,
5194 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005195}
5196
5197void PeerConnection::OnTransportControllerConnectionState(
5198 cricket::IceConnectionState state) {
5199 switch (state) {
5200 case cricket::kIceConnectionConnecting:
5201 // If the current state is Connected or Completed, then there were
5202 // writable channels but now there are not, so the next state must
5203 // be Disconnected.
5204 // kIceConnectionConnecting is currently used as the default,
5205 // un-connected state by the TransportController, so its only use is
5206 // detecting disconnections.
5207 if (ice_connection_state_ ==
5208 PeerConnectionInterface::kIceConnectionConnected ||
5209 ice_connection_state_ ==
5210 PeerConnectionInterface::kIceConnectionCompleted) {
5211 SetIceConnectionState(
5212 PeerConnectionInterface::kIceConnectionDisconnected);
5213 }
5214 break;
5215 case cricket::kIceConnectionFailed:
5216 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5217 break;
5218 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005219 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005220 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005221 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005222 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005223 break;
5224 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005225 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005226 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005227 if (ice_connection_state_ !=
5228 PeerConnectionInterface::kIceConnectionConnected) {
5229 // If jumping directly from "checking" to "connected",
5230 // signal "connected" first.
5231 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5232 }
5233 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005234 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005235 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005236 break;
5237 default:
5238 RTC_NOTREACHED();
5239 }
5240}
5241
5242void PeerConnection::OnTransportControllerCandidatesGathered(
5243 const std::string& transport_name,
5244 const cricket::Candidates& candidates) {
5245 RTC_DCHECK(signaling_thread()->IsCurrent());
5246 int sdp_mline_index;
5247 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005248 RTC_LOG(LS_ERROR)
5249 << "OnTransportControllerCandidatesGathered: content name "
5250 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005251 return;
5252 }
5253
5254 for (cricket::Candidates::const_iterator citer = candidates.begin();
5255 citer != candidates.end(); ++citer) {
5256 // Use transport_name as the candidate media id.
5257 std::unique_ptr<JsepIceCandidate> candidate(
5258 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5259 if (local_description()) {
5260 mutable_local_description()->AddCandidate(candidate.get());
5261 }
5262 OnIceCandidate(std::move(candidate));
5263 }
5264}
5265
5266void PeerConnection::OnTransportControllerCandidatesRemoved(
5267 const std::vector<cricket::Candidate>& candidates) {
5268 RTC_DCHECK(signaling_thread()->IsCurrent());
5269 // Sanity check.
5270 for (const cricket::Candidate& candidate : candidates) {
5271 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005272 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005273 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005274 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005275 return;
5276 }
5277 }
5278
5279 if (local_description()) {
5280 mutable_local_description()->RemoveCandidates(candidates);
5281 }
5282 OnIceCandidatesRemoved(candidates);
5283}
5284
5285void PeerConnection::OnTransportControllerDtlsHandshakeError(
5286 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005287 RTC_HISTOGRAM_ENUMERATION(
5288 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5289 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005290}
5291
Steve Antoned10bd92017-12-05 10:52:59 -08005292void PeerConnection::EnableSending() {
5293 for (auto transceiver : transceivers_) {
5294 cricket::BaseChannel* channel = transceiver->internal()->channel();
5295 if (channel && !channel->enabled()) {
5296 channel->Enable(true);
5297 }
Steve Anton75737c02017-11-06 10:37:17 -08005298 }
5299
Steve Anton4171afb2017-11-20 10:20:22 -08005300 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005301 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005302 }
Steve Anton75737c02017-11-06 10:37:17 -08005303}
5304
5305// Returns the media index for a local ice candidate given the content name.
5306bool PeerConnection::GetLocalCandidateMediaIndex(
5307 const std::string& content_name,
5308 int* sdp_mline_index) {
5309 if (!local_description() || !sdp_mline_index) {
5310 return false;
5311 }
5312
5313 bool content_found = false;
5314 const ContentInfos& contents = local_description()->description()->contents();
5315 for (size_t index = 0; index < contents.size(); ++index) {
5316 if (contents[index].name == content_name) {
5317 *sdp_mline_index = static_cast<int>(index);
5318 content_found = true;
5319 break;
5320 }
5321 }
5322 return content_found;
5323}
5324
5325bool PeerConnection::UseCandidatesInSessionDescription(
5326 const SessionDescriptionInterface* remote_desc) {
5327 if (!remote_desc) {
5328 return true;
5329 }
5330 bool ret = true;
5331
5332 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5333 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5334 for (size_t n = 0; n < candidates->count(); ++n) {
5335 const IceCandidateInterface* candidate = candidates->at(n);
5336 bool valid = false;
5337 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5338 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005339 RTC_LOG(LS_INFO)
5340 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005341 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005342 }
5343 continue;
5344 }
5345 ret = UseCandidate(candidate);
5346 if (!ret) {
5347 break;
5348 }
5349 }
5350 }
5351 return ret;
5352}
5353
5354bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5355 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5356 size_t remote_content_size =
5357 remote_description()->description()->contents().size();
5358 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005359 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005360 return false;
5361 }
5362
5363 cricket::ContentInfo content =
5364 remote_description()->description()->contents()[mediacontent_index];
5365 std::vector<cricket::Candidate> candidates;
5366 candidates.push_back(candidate->candidate());
5367 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005368 RTCError error =
5369 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005370 if (error.ok()) {
5371 // Candidates successfully submitted for checking.
5372 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5373 ice_connection_state_ ==
5374 PeerConnectionInterface::kIceConnectionDisconnected) {
5375 // If state is New, then the session has just gotten its first remote ICE
5376 // candidates, so go to Checking.
5377 // If state is Disconnected, the session is re-using old candidates or
5378 // receiving additional ones, so go to Checking.
5379 // If state is Connected, stay Connected.
5380 // TODO(bemasc): If state is Connected, and the new candidates are for a
5381 // newly added transport, then the state actually _should_ move to
5382 // checking. Add a way to distinguish that case.
5383 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5384 }
5385 // TODO(bemasc): If state is Completed, go back to Connected.
5386 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005387 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005388 }
5389 return true;
5390}
5391
5392void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005393 // Destroy video channel first since it may have a pointer to the
5394 // voice channel.
5395 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005396 if (!video_info || video_info->rejected) {
5397 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005398 }
5399
Steve Anton6fec8802017-12-04 10:37:29 -08005400 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5401 if (!audio_info || audio_info->rejected) {
5402 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005403 }
5404
5405 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5406 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005407 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005408 }
5409}
5410
Steve Antondcc3c022017-12-22 16:02:54 -08005411RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5412 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005413 const cricket::ContentGroup* bundle_group = nullptr;
5414 if (configuration_.bundle_policy ==
5415 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005416 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005417 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005418 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5419 "max-bundle configured but session description "
5420 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005421 }
5422 }
Steve Antondcc3c022017-12-22 16:02:54 -08005423 return std::move(bundle_group);
5424}
5425
5426RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005427 // Creating the media channels. Transports should already have been created
5428 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005429 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005430 if (voice && !voice->rejected &&
5431 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005432 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005433 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005434 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5435 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005436 }
5437 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5438 }
5439
Steve Antondcc3c022017-12-22 16:02:54 -08005440 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005441 if (video && !video->rejected &&
5442 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005443 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005444 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005445 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5446 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005447 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005448 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005449 }
5450
Steve Antondcc3c022017-12-22 16:02:54 -08005451 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005452 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5453 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005454 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005455 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5456 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005457 }
5458 }
5459
Steve Anton8a006912017-12-04 15:25:56 -08005460 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005461}
5462
Steve Anton4171afb2017-11-20 10:20:22 -08005463// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005464cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005465 const std::string& mid) {
5466 RtpTransportInternal* rtp_transport =
5467 transport_controller_->GetRtpTransport(mid);
5468 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005469 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005470 call_.get(), configuration_.media_config, rtp_transport,
5471 signaling_thread(), mid, SrtpRequired(),
5472 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005473 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005474 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005475 }
Steve Anton75737c02017-11-06 10:37:17 -08005476 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5477 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005478 voice_channel->SignalSentPacket.connect(this,
5479 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005480 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005481
Steve Antoneda6ccd2017-12-04 10:21:55 -08005482 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005483}
5484
Steve Anton4171afb2017-11-20 10:20:22 -08005485// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005486cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005487 const std::string& mid) {
5488 RtpTransportInternal* rtp_transport =
5489 transport_controller_->GetRtpTransport(mid);
5490 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005491 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005492 call_.get(), configuration_.media_config, rtp_transport,
5493 signaling_thread(), mid, SrtpRequired(),
5494 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005495 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005496 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005497 }
Steve Anton75737c02017-11-06 10:37:17 -08005498 video_channel->SignalDtlsSrtpSetupFailure.connect(
5499 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005500 video_channel->SignalSentPacket.connect(this,
5501 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005502 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005503
Steve Antoneda6ccd2017-12-04 10:21:55 -08005504 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005505}
5506
Zhi Huange830e682018-03-30 10:48:35 -07005507bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005508 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5509 if (sctp) {
5510 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005511 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005512 << "Trying to create SCTP transport, but didn't compile with "
5513 "SCTP support (HAVE_SCTP)";
5514 return false;
5515 }
5516 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005517 RTC_FROM_HERE,
5518 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005519 return false;
5520 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005521 for (const auto& channel : sctp_data_channels_) {
5522 channel->OnTransportChannelCreated();
5523 }
Steve Anton75737c02017-11-06 10:37:17 -08005524 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005525 RtpTransportInternal* rtp_transport =
5526 transport_controller_->GetRtpTransport(mid);
5527 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005528 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005529 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5530 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005531 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005532 return false;
5533 }
Steve Anton75737c02017-11-06 10:37:17 -08005534 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5535 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5536 rtp_data_channel_->SignalSentPacket.connect(
5537 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005538 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005539 }
5540
Steve Anton75737c02017-11-06 10:37:17 -08005541 return true;
5542}
5543
5544Call::Stats PeerConnection::GetCallStats() {
5545 if (!worker_thread()->IsCurrent()) {
5546 return worker_thread()->Invoke<Call::Stats>(
5547 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5548 }
5549 if (call_) {
5550 return call_->GetStats();
5551 } else {
5552 return Call::Stats();
5553 }
5554}
5555
Zhi Huange830e682018-03-30 10:48:35 -07005556bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005557 RTC_DCHECK(network_thread()->IsCurrent());
5558 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005559 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005560 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005561 RTC_DCHECK(dtls_transport);
5562 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005563 RTC_DCHECK(sctp_transport_);
5564 sctp_invoker_.reset(new rtc::AsyncInvoker());
5565 sctp_transport_->SignalReadyToSendData.connect(
5566 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5567 sctp_transport_->SignalDataReceived.connect(
5568 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005569 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5570 // another thread. Would be nice if there was a helper class similar to
5571 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5572 // code.
5573 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5574 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5575 sctp_transport_->SignalClosingProcedureComplete.connect(
5576 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005577 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005578 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005579 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005580}
5581
5582void PeerConnection::DestroySctpTransport_n() {
5583 RTC_DCHECK(network_thread()->IsCurrent());
5584 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005585 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005586 sctp_invoker_.reset(nullptr);
5587 sctp_ready_to_send_data_ = false;
5588}
5589
5590void PeerConnection::OnSctpTransportReadyToSendData_n() {
5591 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5592 RTC_DCHECK(network_thread()->IsCurrent());
5593 // Note: Cannot use rtc::Bind here because it will grab a reference to
5594 // PeerConnection and potentially cause PeerConnection to live longer than
5595 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5596 // be destroyed before PeerConnection is destroyed, and at that point all
5597 // pending tasks will be cleared.
5598 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5599 OnSctpTransportReadyToSendData_s(true);
5600 });
5601}
5602
5603void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5604 RTC_DCHECK(signaling_thread()->IsCurrent());
5605 sctp_ready_to_send_data_ = ready;
5606 SignalSctpReadyToSendData(ready);
5607}
5608
5609void PeerConnection::OnSctpTransportDataReceived_n(
5610 const cricket::ReceiveDataParams& params,
5611 const rtc::CopyOnWriteBuffer& payload) {
5612 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5613 RTC_DCHECK(network_thread()->IsCurrent());
5614 // Note: Cannot use rtc::Bind here because it will grab a reference to
5615 // PeerConnection and potentially cause PeerConnection to live longer than
5616 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5617 // be destroyed before PeerConnection is destroyed, and at that point all
5618 // pending tasks will be cleared.
5619 sctp_invoker_->AsyncInvoke<void>(
5620 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5621 OnSctpTransportDataReceived_s(params, payload);
5622 });
5623}
5624
5625void PeerConnection::OnSctpTransportDataReceived_s(
5626 const cricket::ReceiveDataParams& params,
5627 const rtc::CopyOnWriteBuffer& payload) {
5628 RTC_DCHECK(signaling_thread()->IsCurrent());
5629 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5630 // Received OPEN message; parse and signal that a new data channel should
5631 // be created.
5632 std::string label;
5633 InternalDataChannelInit config;
5634 config.id = params.ssrc;
5635 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005636 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5637 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005638 return;
5639 }
5640 config.open_handshake_role = InternalDataChannelInit::kAcker;
5641 OnDataChannelOpenMessage(label, config);
5642 } else {
5643 // Otherwise just forward the signal.
5644 SignalSctpDataReceived(params, payload);
5645 }
5646}
5647
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005648void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005649 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5650 RTC_DCHECK(network_thread()->IsCurrent());
5651 sctp_invoker_->AsyncInvoke<void>(
5652 RTC_FROM_HERE, signaling_thread(),
5653 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005654 &SignalSctpClosingProcedureStartedRemotely, sid));
5655}
5656
5657void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5658 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5659 RTC_DCHECK(network_thread()->IsCurrent());
5660 sctp_invoker_->AsyncInvoke<void>(
5661 RTC_FROM_HERE, signaling_thread(),
5662 rtc::Bind(&sigslot::signal1<int>::operator(),
5663 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005664}
5665
5666// Returns false if bundle is enabled and rtcp_mux is disabled.
5667bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5668 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5669 if (!bundle_enabled)
5670 return true;
5671
5672 const cricket::ContentGroup* bundle_group =
5673 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5674 RTC_DCHECK(bundle_group != NULL);
5675
5676 const cricket::ContentInfos& contents = desc->contents();
5677 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5678 citer != contents.end(); ++citer) {
5679 const cricket::ContentInfo* content = (&*citer);
5680 RTC_DCHECK(content != NULL);
5681 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005682 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005683 if (!HasRtcpMuxEnabled(content))
5684 return false;
5685 }
5686 }
5687 // RTCP-MUX is enabled in all the contents.
5688 return true;
5689}
5690
5691bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005692 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005693}
5694
Steve Anton8a006912017-12-04 15:25:56 -08005695RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005696 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005697 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005698 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005699 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005700 }
5701
5702 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005703 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005704 }
5705
Steve Anton3828c062017-12-06 10:34:51 -08005706 SdpType type = sdesc->GetType();
5707 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5708 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005709 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005710 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005711 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005712 }
5713
5714 // Verify crypto settings.
5715 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005716 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5717 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005718 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005719 if (!crypto_error.ok()) {
5720 return crypto_error;
5721 }
Steve Anton75737c02017-11-06 10:37:17 -08005722 }
5723
5724 // Verify ice-ufrag and ice-pwd.
5725 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005726 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5727 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005728 }
5729
5730 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005731 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5732 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005733 }
5734
5735 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5736 // m-lines that do not rtcp-mux enabled.
5737
5738 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005739 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005740 // With an answer we want to compare the new answer session description with
5741 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005742 const cricket::SessionDescription* offer_desc =
5743 (source == cricket::CS_LOCAL) ? remote_description()->description()
5744 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005745 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5746 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5747 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005748 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5749 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005750 }
5751 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005752 // The re-offers should respect the order of m= sections in current
5753 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005754 // With a re-offer, either the current local or current remote descriptions
5755 // could be the most up to date, so we would like to check against both of
5756 // them if they exist. It could be the case that one of them has a 0 port
5757 // for a media section, but the other does not. This is important to check
5758 // against in the case that we are recycling an m= section.
5759 const cricket::SessionDescription* current_desc = nullptr;
5760 const cricket::SessionDescription* secondary_current_desc = nullptr;
5761 if (local_description()) {
5762 current_desc = local_description()->description();
5763 if (remote_description()) {
5764 secondary_current_desc = remote_description()->description();
5765 }
5766 } else if (remote_description()) {
5767 current_desc = remote_description()->description();
5768 }
Steve Anton75737c02017-11-06 10:37:17 -08005769 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005770 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5771 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005772 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5773 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005774 }
5775 }
5776
Steve Antonba42e992018-04-09 14:10:01 -07005777 if (IsUnifiedPlan()) {
5778 // Ensure that each audio and video media section has at most one
5779 // "StreamParams". This will return an error if receiving a session
5780 // description from a "Plan B" endpoint which adds multiple tracks of the
5781 // same type. With Unified Plan, there can only be at most one track per
5782 // media section.
5783 for (const ContentInfo& content : sdesc->description()->contents()) {
5784 const MediaContentDescription& desc = *content.description;
5785 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5786 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5787 desc.streams().size() > 1u) {
5788 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5789 "Media section has more than one track specified "
5790 "with a=ssrc lines which is not supported with "
5791 "Unified Plan.");
5792 }
5793 }
5794 }
5795
Steve Anton8a006912017-12-04 15:25:56 -08005796 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005797}
5798
Steve Anton3828c062017-12-06 10:34:51 -08005799bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005800 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005801 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005802 return (state == PeerConnectionInterface::kStable) ||
5803 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005804 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005805 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005806 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5807 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5808 }
5809}
5810
Steve Anton3828c062017-12-06 10:34:51 -08005811bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005812 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005813 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005814 return (state == PeerConnectionInterface::kStable) ||
5815 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005816 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005817 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005818 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5819 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5820 }
5821}
5822
Steve Antonf8470812017-12-04 10:46:21 -08005823const char* PeerConnection::SessionErrorToString(SessionError error) const {
5824 switch (error) {
5825 case SessionError::kNone:
5826 return "ERROR_NONE";
5827 case SessionError::kContent:
5828 return "ERROR_CONTENT";
5829 case SessionError::kTransport:
5830 return "ERROR_TRANSPORT";
5831 }
5832 RTC_NOTREACHED();
5833 return "";
5834}
5835
Steve Anton75737c02017-11-06 10:37:17 -08005836std::string PeerConnection::GetSessionErrorMsg() {
5837 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005838 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5839 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005840 return desc.str();
5841}
5842
Steve Anton8e20f172018-03-06 10:55:04 -08005843void PeerConnection::ReportSdpFormatReceived(
5844 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005845 int num_audio_mlines = 0;
5846 int num_video_mlines = 0;
5847 int num_audio_tracks = 0;
5848 int num_video_tracks = 0;
5849 for (const ContentInfo& content : remote_offer.description()->contents()) {
5850 cricket::MediaType media_type = content.media_description()->type();
5851 int num_tracks = std::max(
5852 1, static_cast<int>(content.media_description()->streams().size()));
5853 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5854 num_audio_mlines += 1;
5855 num_audio_tracks += num_tracks;
5856 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5857 num_video_mlines += 1;
5858 num_video_tracks += num_tracks;
5859 }
5860 }
5861 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5862 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5863 format = kSdpFormatReceivedComplexUnifiedPlan;
5864 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5865 format = kSdpFormatReceivedComplexPlanB;
5866 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5867 format = kSdpFormatReceivedSimple;
5868 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005869 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5870 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005871}
5872
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005873void PeerConnection::NoteUsageEvent(UsageEvent event) {
5874 RTC_DCHECK_RUN_ON(signaling_thread());
5875 usage_event_accumulator_ |= static_cast<int>(event);
5876}
5877
5878void PeerConnection::ReportUsagePattern() const {
5879 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005880 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5881 usage_event_accumulator_,
5882 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005883 const int bad_bits =
5884 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5885 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5886 const int good_bits =
5887 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5888 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5889 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5890 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5891 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005892 // If called after close(), we can't report, because observer may have
5893 // been deallocated, and therefore pointer is null. Write to log instead.
5894 if (observer_) {
5895 Observer()->OnInterestingUsage(usage_event_accumulator_);
5896 } else {
5897 RTC_LOG(LS_INFO) << "Interesting usage signature "
5898 << usage_event_accumulator_
5899 << " observed after observer shutdown";
5900 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005901 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005902}
5903
Steve Anton0ffaaa22018-02-23 10:31:30 -08005904void PeerConnection::ReportNegotiatedSdpSemantics(
5905 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005906 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005907 switch (answer.description()->msid_signaling()) {
5908 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005909 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005910 break;
5911 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005912 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005913 break;
5914 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005915 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005916 break;
5917 case cricket::kMsidSignalingMediaSection |
5918 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005919 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005920 break;
5921 default:
5922 RTC_NOTREACHED();
5923 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005924 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5925 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005926}
5927
Steve Anton75737c02017-11-06 10:37:17 -08005928// We need to check the local/remote description for the Transport instead of
5929// the session, because a new Transport added during renegotiation may have
5930// them unset while the session has them set from the previous negotiation.
5931// Not doing so may trigger the auto generation of transport description and
5932// mess up DTLS identity information, ICE credential, etc.
5933bool PeerConnection::ReadyToUseRemoteCandidate(
5934 const IceCandidateInterface* candidate,
5935 const SessionDescriptionInterface* remote_desc,
5936 bool* valid) {
5937 *valid = true;
5938
5939 const SessionDescriptionInterface* current_remote_desc =
5940 remote_desc ? remote_desc : remote_description();
5941
5942 if (!current_remote_desc) {
5943 return false;
5944 }
5945
5946 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5947 size_t remote_content_size =
5948 current_remote_desc->description()->contents().size();
5949 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005950 RTC_LOG(LS_ERROR)
5951 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5952 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005953
5954 *valid = false;
5955 return false;
5956 }
5957
5958 cricket::ContentInfo content =
5959 current_remote_desc->description()->contents()[mediacontent_index];
5960
5961 const std::string transport_name = GetTransportName(content.name);
5962 if (transport_name.empty()) {
5963 return false;
5964 }
Zhi Huange830e682018-03-30 10:48:35 -07005965 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005966}
5967
5968bool PeerConnection::SrtpRequired() const {
5969 return dtls_enabled_ ||
5970 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5971}
5972
5973void PeerConnection::OnTransportControllerGatheringState(
5974 cricket::IceGatheringState state) {
5975 RTC_DCHECK(signaling_thread()->IsCurrent());
5976 if (state == cricket::kIceGatheringGathering) {
5977 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5978 } else if (state == cricket::kIceGatheringComplete) {
5979 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5980 }
5981}
5982
5983void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005984 std::map<std::string, std::set<cricket::MediaType>>
5985 media_types_by_transport_name;
5986 for (auto transceiver : transceivers_) {
5987 if (transceiver->internal()->channel()) {
5988 const std::string& transport_name =
5989 transceiver->internal()->channel()->transport_name();
5990 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005991 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005992 }
Steve Anton75737c02017-11-06 10:37:17 -08005993 }
5994 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005995 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5996 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005997 }
Zhi Huange830e682018-03-30 10:48:35 -07005998
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005999 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006000 if (transport_name) {
6001 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006002 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006003 }
Zhi Huange830e682018-03-30 10:48:35 -07006004
Steve Antonc7b964c2018-02-01 14:39:45 -08006005 for (const auto& entry : media_types_by_transport_name) {
6006 const std::string& transport_name = entry.first;
6007 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006008 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006009 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006010 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006011 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006012 }
6013 }
6014}
6015// Walk through the ConnectionInfos to gather best connection usage
6016// for IPv4 and IPv6.
6017void PeerConnection::ReportBestConnectionState(
6018 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006019 for (const cricket::TransportChannelStats& channel_stats :
6020 stats.channel_stats) {
6021 for (const cricket::ConnectionInfo& connection_info :
6022 channel_stats.connection_infos) {
6023 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006024 continue;
6025 }
6026
Steve Antonc7b964c2018-02-01 14:39:45 -08006027 const cricket::Candidate& local = connection_info.local_candidate;
6028 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006029
6030 // Increment the counter for IceCandidatePairType.
6031 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6032 (local.type() == RELAY_PORT_TYPE &&
6033 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006034 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6035 GetIceCandidatePairCounter(local, remote),
6036 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006037 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006038 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6039 GetIceCandidatePairCounter(local, remote),
6040 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006041 } else {
6042 RTC_CHECK(0);
6043 }
Steve Anton75737c02017-11-06 10:37:17 -08006044
6045 // Increment the counter for IP type.
6046 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006047 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6048 kBestConnections_IPv4,
6049 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006050 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006051 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6052 kBestConnections_IPv6,
6053 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006054 } else {
6055 RTC_CHECK(0);
6056 }
6057
6058 return;
6059 }
6060 }
6061}
6062
6063void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006064 const cricket::TransportStats& stats,
6065 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006066 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6067 return;
6068 }
6069
6070 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6071 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6072 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6073 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6074 return;
6075 }
6076
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006077 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6078 for (cricket::MediaType media_type : media_types) {
6079 switch (media_type) {
6080 case cricket::MEDIA_TYPE_AUDIO:
6081 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6082 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6083 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6084 break;
6085 case cricket::MEDIA_TYPE_VIDEO:
6086 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6087 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6088 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6089 break;
6090 case cricket::MEDIA_TYPE_DATA:
6091 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6092 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6093 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6094 break;
6095 default:
6096 RTC_NOTREACHED();
6097 continue;
6098 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006099 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006100 }
6101
6102 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6103 for (cricket::MediaType media_type : media_types) {
6104 switch (media_type) {
6105 case cricket::MEDIA_TYPE_AUDIO:
6106 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6107 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6108 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6109 break;
6110 case cricket::MEDIA_TYPE_VIDEO:
6111 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6112 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6113 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6114 break;
6115 case cricket::MEDIA_TYPE_DATA:
6116 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6117 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6118 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6119 break;
6120 default:
6121 RTC_NOTREACHED();
6122 continue;
6123 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006124 }
Steve Anton75737c02017-11-06 10:37:17 -08006125 }
6126}
6127
6128void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6129 RTC_DCHECK(worker_thread()->IsCurrent());
6130 RTC_DCHECK(call_);
6131 call_->OnSentPacket(sent_packet);
6132}
6133
6134const std::string PeerConnection::GetTransportName(
6135 const std::string& content_name) {
6136 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006137 if (channel) {
6138 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006139 }
Steve Anton6fec8802017-12-04 10:37:29 -08006140 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006141 RTC_DCHECK(sctp_mid_);
6142 if (content_name == *sctp_mid_) {
6143 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006144 }
6145 }
6146 // Return an empty string if failed to retrieve the transport name.
6147 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006148}
6149
Steve Anton6fec8802017-12-04 10:37:29 -08006150void PeerConnection::DestroyTransceiverChannel(
6151 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6152 transceiver) {
6153 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006154
Steve Anton6fec8802017-12-04 10:37:29 -08006155 cricket::BaseChannel* channel = transceiver->internal()->channel();
6156 if (channel) {
6157 transceiver->internal()->SetChannel(nullptr);
6158 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006159 }
6160}
6161
6162void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006163 if (rtp_data_channel_) {
6164 OnDataChannelDestroyed();
6165 DestroyBaseChannel(rtp_data_channel_);
6166 rtp_data_channel_ = nullptr;
6167 }
6168
6169 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6170 // grab a reference to this PeerConnection. If this is called from the
6171 // PeerConnection destructor, the RefCountedObject vtable will have already
6172 // been destroyed (since it is a subclass of PeerConnection) and using
6173 // rtc::Bind will cause "Pure virtual function called" error to appear.
6174
6175 if (sctp_transport_) {
6176 OnDataChannelDestroyed();
6177 network_thread()->Invoke<void>(RTC_FROM_HERE,
6178 [this] { DestroySctpTransport_n(); });
6179 }
6180}
6181
6182void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6183 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006184 switch (channel->media_type()) {
6185 case cricket::MEDIA_TYPE_AUDIO:
6186 channel_manager()->DestroyVoiceChannel(
6187 static_cast<cricket::VoiceChannel*>(channel));
6188 break;
6189 case cricket::MEDIA_TYPE_VIDEO:
6190 channel_manager()->DestroyVideoChannel(
6191 static_cast<cricket::VideoChannel*>(channel));
6192 break;
6193 case cricket::MEDIA_TYPE_DATA:
6194 channel_manager()->DestroyRtpDataChannel(
6195 static_cast<cricket::RtpDataChannel*>(channel));
6196 break;
6197 default:
6198 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6199 break;
6200 }
Zhi Huange830e682018-03-30 10:48:35 -07006201}
Steve Anton6fec8802017-12-04 10:37:29 -08006202
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006203bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006204 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006205 RtpTransportInternal* rtp_transport,
6206 cricket::DtlsTransportInternal* dtls_transport) {
6207 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006208 auto base_channel = GetChannel(mid);
6209 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006210 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006211 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006212 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006213 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006214 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006215 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006216}
6217
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006218PeerConnectionObserver* PeerConnection::Observer() const {
6219 // In earlier production code, the pointer was not cleared on close,
6220 // which might have led to undefined behavior if the observer was not
6221 // deallocated, or strange crashes if it was.
6222 // We use CHECK in order to catch such behavior if it exists.
6223 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6224 RTC_CHECK(observer_);
6225 return observer_;
6226}
6227
Harald Alvestrand89061872018-01-02 14:08:34 +01006228void PeerConnection::ClearStatsCache() {
6229 if (stats_collector_) {
6230 stats_collector_->ClearCachedStatsReport();
6231 }
6232}
6233
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006234void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006235 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6236 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006237}
6238
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006239} // namespace webrtc