blob: 22cd60a4deeedcb590ecd8da5e4a3337a9a2337c [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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "pc/peer_connection.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
Steve Anton64b626b2019-01-28 17:25:26 -080020#include "absl/algorithm/container.h"
Karl Wiberg918f50c2018-07-05 11:40:33 +020021#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010022#include "absl/strings/match.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "api/jsep_ice_candidate.h"
24#include "api/jsep_session_description.h"
25#include "api/media_stream_proxy.h"
26#include "api/media_stream_track_proxy.h"
27#include "api/uma_metrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "call/call.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "logging/rtc_event_log/ice_logger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020030#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "logging/rtc_event_log/rtc_event_log.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "media/sctp/sctp_transport.h"
33#include "pc/audio_track.h"
Steve Anton75737c02017-11-06 10:37:17 -080034#include "pc/channel.h"
Steve Anton10542f22019-01-11 09:11:00 -080035#include "pc/channel_manager.h"
36#include "pc/dtmf_sender.h"
37#include "pc/media_stream.h"
38#include "pc/media_stream_observer.h"
39#include "pc/remote_audio_source.h"
40#include "pc/rtp_media_utils.h"
41#include "pc/rtp_receiver.h"
42#include "pc/rtp_sender.h"
43#include "pc/sctp_utils.h"
44#include "pc/sdp_utils.h"
45#include "pc/stream_collection.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "pc/video_capturer_track_source.h"
47#include "pc/video_track.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/bind.h"
49#include "rtc_base/checks.h"
50#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010051#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080052#include "rtc_base/string_encode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020053#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/trace_event.h"
55#include "system_wrappers/include/clock.h"
56#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070057#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
Steve Anton75737c02017-11-06 10:37:17 -080059using cricket::ContentInfo;
60using cricket::ContentInfos;
61using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080063using cricket::RidDescription;
64using cricket::RidDirection;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080065using cricket::SessionDescription;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080066using cricket::SimulcastDescription;
67using cricket::SimulcastLayer;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080068using cricket::SimulcastLayerList;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -080069using cricket::StreamParams;
Steve Anton75737c02017-11-06 10:37:17 -080070using cricket::TransportInfo;
71
72using cricket::LOCAL_PORT_TYPE;
73using cricket::STUN_PORT_TYPE;
74using cricket::RELAY_PORT_TYPE;
75using cricket::PRFLX_PORT_TYPE;
76
Steve Antonba818672017-11-06 10:21:57 -080077namespace webrtc {
78
Steve Anton75737c02017-11-06 10:37:17 -080079// Error messages
80const char kBundleWithoutRtcpMux[] =
81 "rtcp-mux must be enabled when BUNDLE "
82 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080083const char kInvalidCandidates[] = "Description contains invalid candidates.";
84const char kInvalidSdp[] = "Invalid session description.";
85const char kMlineMismatchInAnswer[] =
86 "The order of m-lines in answer doesn't match order in offer. Rejecting "
87 "answer.";
88const char kMlineMismatchInSubsequentOffer[] =
89 "The order of m-lines in subsequent offer doesn't match order from "
90 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080091const char kSdpWithoutDtlsFingerprint[] =
92 "Called with SDP without DTLS fingerprint.";
93const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
94const char kSdpWithoutIceUfragPwd[] =
95 "Called with SDP without ice-ufrag and ice-pwd.";
96const char kSessionError[] = "Session error code: ";
97const char kSessionErrorDesc[] = "Session error description: ";
98const char kDtlsSrtpSetupFailureRtp[] =
99 "Couldn't set up DTLS-SRTP on RTP channel.";
100const char kDtlsSrtpSetupFailureRtcp[] =
101 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102
Steve Anton75737c02017-11-06 10:37:17 -0800103namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104
Seth Hampson845e8782018-03-02 11:34:10 -0800105static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800106static const char kDefaultAudioSenderId[] = "defaulta0";
107static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700108
zhihuang8f65cdf2016-05-06 18:40:30 -0700109// The length of RTCP CNAMEs.
110static const int kRtcpCnameLength = 16;
111
Steve Antonad182762018-09-05 20:22:40 +0000112enum {
113 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
114 MSG_SET_SESSIONDESCRIPTION_FAILED,
115 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
116 MSG_GETSTATS,
117 MSG_FREE_DATACHANNELS,
118 MSG_REPORT_USAGE_PATTERN,
119};
120
Harald Alvestrand19793842018-06-25 12:03:50 +0200121static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
122
Steve Antonad182762018-09-05 20:22:40 +0000123struct SetSessionDescriptionMsg : public rtc::MessageData {
124 explicit SetSessionDescriptionMsg(
125 webrtc::SetSessionDescriptionObserver* observer)
126 : observer(observer) {}
127
128 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
129 RTCError error;
130};
131
132struct CreateSessionDescriptionMsg : public rtc::MessageData {
133 explicit CreateSessionDescriptionMsg(
134 webrtc::CreateSessionDescriptionObserver* observer)
135 : observer(observer) {}
136
137 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
138 RTCError error;
139};
140
141struct GetStatsMsg : public rtc::MessageData {
142 GetStatsMsg(webrtc::StatsObserver* observer,
143 webrtc::MediaStreamTrackInterface* track)
144 : observer(observer), track(track) {}
145 rtc::scoped_refptr<webrtc::StatsObserver> observer;
146 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
147};
148
deadbeefab9b2d12015-10-14 11:33:11 -0700149// Check if we can send |new_stream| on a PeerConnection.
150bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
151 webrtc::MediaStreamInterface* new_stream) {
152 if (!new_stream || !current_streams) {
153 return false;
154 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700155 if (current_streams->find(new_stream->id()) != nullptr) {
156 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100157 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700158 return false;
159 }
160 return true;
161}
162
deadbeef5e97fb52015-10-15 12:49:08 -0700163// If the direction is "recvonly" or "inactive", treat the description
164// as containing no streams.
165// See: https://code.google.com/p/webrtc/issues/detail?id=5054
166std::vector<cricket::StreamParams> GetActiveStreams(
167 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800168 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700169 ? desc->streams()
170 : std::vector<cricket::StreamParams>();
171}
172
deadbeefab9b2d12015-10-14 11:33:11 -0700173bool IsValidOfferToReceiveMedia(int value) {
174 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
175 return (value >= Options::kUndefined) &&
176 (value <= Options::kMaxOfferToReceiveMedia);
177}
178
zhihuang1c378ed2017-08-17 14:10:50 -0700179// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800180void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700181 const std::vector<rtc::scoped_refptr<
182 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700183 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200184 cricket::MediaDescriptionOptions* video_media_description_options,
185 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700186 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700187 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
188 if (audio_media_description_options) {
189 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700190 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 } else {
193 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
194 if (video_media_description_options) {
195 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800196 sender->id(), sender->internal()->stream_ids(), {},
197 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700198 }
199 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700200 }
zhihuang1c378ed2017-08-17 14:10:50 -0700201}
olka3c747662017-08-17 06:50:32 -0700202
zhihuang1c378ed2017-08-17 14:10:50 -0700203// Add options to |session_options| from |rtp_data_channels|.
204void AddRtpDataChannelOptions(
205 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
206 rtp_data_channels,
207 cricket::MediaDescriptionOptions* data_media_description_options) {
208 if (!data_media_description_options) {
209 return;
210 }
deadbeefab9b2d12015-10-14 11:33:11 -0700211 // Check for data channels.
212 for (const auto& kv : rtp_data_channels) {
213 const DataChannel* channel = kv.second;
214 if (channel->state() == DataChannel::kConnecting ||
215 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700216 // Legacy RTP data channels are signaled with the track/stream ID set to
217 // the data channel's label.
218 data_media_description_options->AddRtpDataChannel(channel->label(),
219 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700220 }
221 }
222}
223
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700224uint32_t ConvertIceTransportTypeToCandidateFilter(
225 PeerConnectionInterface::IceTransportsType type) {
226 switch (type) {
227 case PeerConnectionInterface::kNone:
228 return cricket::CF_NONE;
229 case PeerConnectionInterface::kRelay:
230 return cricket::CF_RELAY;
231 case PeerConnectionInterface::kNoHost:
232 return (cricket::CF_ALL & ~cricket::CF_HOST);
233 case PeerConnectionInterface::kAll:
234 return cricket::CF_ALL;
235 default:
nissec80e7412017-01-11 05:56:46 -0800236 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700237 }
238 return cricket::CF_NONE;
239}
240
deadbeef293e9262017-01-11 12:28:30 -0800241// Helper to set an error and return from a method.
242bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
243 if (error) {
244 error->set_type(type);
245 }
246 return type == webrtc::RTCErrorType::NONE;
247}
248
Steve Anton038834f2017-07-14 15:59:59 -0700249bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700250 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700251 if (error_out) {
252 *error_out = std::move(error);
253 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700254 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700255}
256
Steve Antonba818672017-11-06 10:21:57 -0800257std::string GetSignalingStateString(
258 PeerConnectionInterface::SignalingState state) {
259 switch (state) {
260 case PeerConnectionInterface::kStable:
261 return "kStable";
262 case PeerConnectionInterface::kHaveLocalOffer:
263 return "kHaveLocalOffer";
264 case PeerConnectionInterface::kHaveLocalPrAnswer:
265 return "kHavePrAnswer";
266 case PeerConnectionInterface::kHaveRemoteOffer:
267 return "kHaveRemoteOffer";
268 case PeerConnectionInterface::kHaveRemotePrAnswer:
269 return "kHaveRemotePrAnswer";
270 case PeerConnectionInterface::kClosed:
271 return "kClosed";
272 }
273 RTC_NOTREACHED();
274 return "";
275}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700276
Steve Anton75737c02017-11-06 10:37:17 -0800277IceCandidatePairType GetIceCandidatePairCounter(
278 const cricket::Candidate& local,
279 const cricket::Candidate& remote) {
280 const auto& l = local.type();
281 const auto& r = remote.type();
282 const auto& host = LOCAL_PORT_TYPE;
283 const auto& srflx = STUN_PORT_TYPE;
284 const auto& relay = RELAY_PORT_TYPE;
285 const auto& prflx = PRFLX_PORT_TYPE;
286 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800287 bool local_hostname =
288 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
289 bool remote_hostname = !remote.address().hostname().empty() &&
290 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800291 bool local_private = IPIsPrivate(local.address().ipaddr());
292 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800293 if (local_hostname) {
294 if (remote_hostname) {
295 return kIceCandidatePairHostNameHostName;
296 } else if (remote_private) {
297 return kIceCandidatePairHostNameHostPrivate;
298 } else {
299 return kIceCandidatePairHostNameHostPublic;
300 }
301 } else if (local_private) {
302 if (remote_hostname) {
303 return kIceCandidatePairHostPrivateHostName;
304 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800305 return kIceCandidatePairHostPrivateHostPrivate;
306 } else {
307 return kIceCandidatePairHostPrivateHostPublic;
308 }
309 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800310 if (remote_hostname) {
311 return kIceCandidatePairHostPublicHostName;
312 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800313 return kIceCandidatePairHostPublicHostPrivate;
314 } else {
315 return kIceCandidatePairHostPublicHostPublic;
316 }
317 }
318 }
319 if (l == host && r == srflx)
320 return kIceCandidatePairHostSrflx;
321 if (l == host && r == relay)
322 return kIceCandidatePairHostRelay;
323 if (l == host && r == prflx)
324 return kIceCandidatePairHostPrflx;
325 if (l == srflx && r == host)
326 return kIceCandidatePairSrflxHost;
327 if (l == srflx && r == srflx)
328 return kIceCandidatePairSrflxSrflx;
329 if (l == srflx && r == relay)
330 return kIceCandidatePairSrflxRelay;
331 if (l == srflx && r == prflx)
332 return kIceCandidatePairSrflxPrflx;
333 if (l == relay && r == host)
334 return kIceCandidatePairRelayHost;
335 if (l == relay && r == srflx)
336 return kIceCandidatePairRelaySrflx;
337 if (l == relay && r == relay)
338 return kIceCandidatePairRelayRelay;
339 if (l == relay && r == prflx)
340 return kIceCandidatePairRelayPrflx;
341 if (l == prflx && r == host)
342 return kIceCandidatePairPrflxHost;
343 if (l == prflx && r == srflx)
344 return kIceCandidatePairPrflxSrflx;
345 if (l == prflx && r == relay)
346 return kIceCandidatePairPrflxRelay;
347 return kIceCandidatePairMax;
348}
349
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800350// Logic to decide if an m= section can be recycled. This means that the new
351// m= section is not rejected, but the old local or remote m= section is
352// rejected. |old_content_one| and |old_content_two| refer to the m= section
353// of the old remote and old local descriptions in no particular order.
354// We need to check both the old local and remote because either
355// could be the most current from the latest negotation.
356bool IsMediaSectionBeingRecycled(SdpType type,
357 const ContentInfo& content,
358 const ContentInfo* old_content_one,
359 const ContentInfo* old_content_two) {
360 return type == SdpType::kOffer && !content.rejected &&
361 ((old_content_one && old_content_one->rejected) ||
362 (old_content_two && old_content_two->rejected));
363}
364
Steve Anton75737c02017-11-06 10:37:17 -0800365// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366// |current_desc|. The number of m= sections in |new_desc| should be no
367// less than |current_desc|. In the case of checking an answer's
368// |new_desc|, the |current_desc| is the last offer that was set as the
369// local or remote. In the case of checking an offer's |new_desc| we
370// check against the local and remote descriptions stored from the last
371// negotiation, because either of these could be the most up to date for
372// possible rejected m sections. These are the |current_desc| and
373// |secondary_current_desc|.
374bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
375 const SessionDescription* secondary_current_desc,
376 const SessionDescription& new_desc,
377 const SdpType type) {
378 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800379 return false;
380 }
381
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800382 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
383 const cricket::ContentInfo* secondary_content_info = nullptr;
384 if (secondary_current_desc &&
385 i < secondary_current_desc->contents().size()) {
386 secondary_content_info = &secondary_current_desc->contents()[i];
387 }
388 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
389 &current_desc.contents()[i],
390 secondary_content_info)) {
391 // For new offer descriptions, if the media section can be recycled, it's
392 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800393 continue;
394 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800395 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800396 return false;
397 }
398 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800399 new_desc.contents()[i].media_description();
400 const MediaContentDescription* current_desc_mdesc =
401 current_desc.contents()[i].media_description();
402 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800403 return false;
404 }
405 }
406 return true;
407}
408
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800409bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
410 const SessionDescription& desc2) {
411 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800412}
413
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700414void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
415 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200416 // Array of structs needed to map {KeyExchangeProtocolType,
417 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
418 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
419 static constexpr struct {
420 KeyExchangeProtocolType protocol_type;
421 cricket::MediaType media_type;
422 KeyExchangeProtocolMedia protocol_media;
423 } kEnumCounterKeyProtocolMediaMap[] = {
424 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
425 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
426 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
427 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
428 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
429 kEnumCounterKeyProtocolMediaTypeDtlsData},
430 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
431 kEnumCounterKeyProtocolMediaTypeSdesAudio},
432 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
433 kEnumCounterKeyProtocolMediaTypeSdesVideo},
434 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
435 kEnumCounterKeyProtocolMediaTypeSdesData},
436 };
437
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
439 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100440
Mirko Bonadeiab499822018-09-11 10:43:20 +0200441 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
442 if (i.protocol_type == protocol_type && i.media_type == media_type) {
443 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
444 i.protocol_media,
445 kEnumCounterKeyProtocolMediaTypeMax);
446 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100447 }
448}
449
Harald Alvestrand76829d72018-07-18 23:24:36 +0200450void NoteAddIceCandidateResult(int result) {
451 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
452 kAddIceCandidateMax);
453}
454
Steve Anton75737c02017-11-06 10:37:17 -0800455// Checks that each non-rejected content has SDES crypto keys or a DTLS
456// fingerprint, unless it's in a BUNDLE group, in which case only the
457// BUNDLE-tag section (first media section/description in the BUNDLE group)
458// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
459// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
460// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700461RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800462 const cricket::ContentGroup* bundle =
463 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800464 for (const cricket::ContentInfo& content_info : desc->contents()) {
465 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800466 continue;
467 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100468 // Note what media is used with each crypto protocol, for all sections.
469 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
470 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700471 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800472 const std::string& mid = content_info.name;
473 if (bundle && bundle->HasContentName(mid) &&
474 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800475 // This isn't the first media section in the BUNDLE group, so it's not
476 // required to have crypto attributes, since only the crypto attributes
477 // from the first section actually get used.
478 continue;
479 }
480
481 // If the content isn't rejected or bundled into another m= section, crypto
482 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800483 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800484 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800485 if (!media || !tinfo) {
486 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800487 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800488 }
489 if (dtls_enabled) {
490 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100491 RTC_LOG(LS_WARNING)
492 << "Session description must have DTLS fingerprint if "
493 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800494 return RTCError(RTCErrorType::INVALID_PARAMETER,
495 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800496 }
497 } else {
498 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100499 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800500 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800501 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800502 }
503 }
504 }
Steve Anton8a006912017-12-04 15:25:56 -0800505 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800506}
507
508// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
509// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
510// media section/description in the BUNDLE group) needs a ufrag and pwd.
511bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
512 const cricket::ContentGroup* bundle =
513 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800514 for (const cricket::ContentInfo& content_info : desc->contents()) {
515 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800516 continue;
517 }
Steve Anton8a006912017-12-04 15:25:56 -0800518 const std::string& mid = content_info.name;
519 if (bundle && bundle->HasContentName(mid) &&
520 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800521 // This isn't the first media section in the BUNDLE group, so it's not
522 // required to have ufrag/password, since only the ufrag/password from
523 // the first section actually get used.
524 continue;
525 }
526
527 // If the content isn't rejected or bundled into another m= section,
528 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800529 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (!tinfo) {
531 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100532 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800533 return false;
534 }
535 if (tinfo->description.ice_ufrag.empty() ||
536 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100537 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800538 return false;
539 }
540 }
541 return true;
542}
543
Steve Anton75737c02017-11-06 10:37:17 -0800544// Get the SCTP port out of a SessionDescription.
545// Return -1 if not found.
546int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800547 const cricket::DataContentDescription* data_desc =
548 GetFirstDataContentDescription(session_description);
549 RTC_DCHECK(data_desc);
550 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800551 return -1;
552 }
Steve Anton75737c02017-11-06 10:37:17 -0800553 std::string value;
554 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
555 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800556 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800557 if (!codec.Matches(match_pattern)) {
558 continue;
559 }
560 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
561 return rtc::FromString<int>(value);
562 }
563 }
564 return -1;
565}
566
Steve Anton75737c02017-11-06 10:37:17 -0800567// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
568bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
569 const SessionDescriptionInterface* new_desc,
570 const std::string& content_name) {
571 if (!old_desc) {
572 return false;
573 }
574 const SessionDescription* new_sd = new_desc->description();
575 const SessionDescription* old_sd = old_desc->description();
576 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
577 if (!cinfo || cinfo->rejected) {
578 return false;
579 }
580 // If the content isn't rejected, check if ufrag and password has changed.
581 const cricket::TransportDescription* new_transport_desc =
582 new_sd->GetTransportDescriptionByName(content_name);
583 const cricket::TransportDescription* old_transport_desc =
584 old_sd->GetTransportDescriptionByName(content_name);
585 if (!new_transport_desc || !old_transport_desc) {
586 // No transport description exists. This is not an ICE restart.
587 return false;
588 }
589 if (cricket::IceCredentialsChanged(
590 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
591 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100592 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
593 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800594 return true;
595 }
596 return false;
597}
598
Steve Anton80dd7b52018-02-16 17:08:42 -0800599// Generates a string error message for SetLocalDescription/SetRemoteDescription
600// from an RTCError.
601std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
602 SdpType type,
603 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200604 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800605 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
606 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200607 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800608}
609
Seth Hampson5b4f0752018-04-02 16:31:36 -0700610std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
611 std::string output = "streams=[";
612 const char* separator = "";
613 for (const auto& stream_id : stream_ids) {
614 output.append(separator).append(stream_id);
615 separator = ", ";
616 }
617 output.append("]");
618 return output;
619}
620
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200621absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700622 int rtc_configuration_parameter) {
623 if (rtc_configuration_parameter ==
624 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 }
627 return rtc_configuration_parameter;
628}
629
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800630cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
631 switch (type) {
632 case DataMessageType::kText:
633 return cricket::DMT_TEXT;
634 case DataMessageType::kBinary:
635 return cricket::DMT_BINARY;
636 case DataMessageType::kControl:
637 return cricket::DMT_CONTROL;
638 default:
639 return cricket::DMT_NONE;
640 }
641 return cricket::DMT_NONE;
642}
643
644DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
645 switch (type) {
646 case cricket::DMT_TEXT:
647 return DataMessageType::kText;
648 case cricket::DMT_BINARY:
649 return DataMessageType::kBinary;
650 case cricket::DMT_CONTROL:
651 return DataMessageType::kControl;
652 case cricket::DMT_NONE:
653 default:
654 RTC_NOTREACHED();
655 }
656 return DataMessageType::kControl;
657}
658
Steve Anton75737c02017-11-06 10:37:17 -0800659} // namespace
660
Henrik Boström31638672017-11-23 17:48:32 +0100661// Upon completion, posts a task to execute the callback of the
662// SetSessionDescriptionObserver asynchronously on the same thread. At this
663// point, the state of the peer connection might no longer reflect the effects
664// of the SetRemoteDescription operation, as the peer connection could have been
665// modified during the post.
666// TODO(hbos): Remove this class once we remove the version of
667// PeerConnectionInterface::SetRemoteDescription() that takes a
668// SetSessionDescriptionObserver as an argument.
669class PeerConnection::SetRemoteDescriptionObserverAdapter
670 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
671 public:
672 SetRemoteDescriptionObserverAdapter(
673 rtc::scoped_refptr<PeerConnection> pc,
674 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
675 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
676
677 // SetRemoteDescriptionObserverInterface implementation.
678 void OnSetRemoteDescriptionComplete(RTCError error) override {
679 if (error.ok())
680 pc_->PostSetSessionDescriptionSuccess(wrapper_);
681 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100682 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100683 }
684
685 private:
686 rtc::scoped_refptr<PeerConnection> pc_;
687 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
688};
689
deadbeef293e9262017-01-11 12:28:30 -0800690bool PeerConnectionInterface::RTCConfiguration::operator==(
691 const PeerConnectionInterface::RTCConfiguration& o) const {
692 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700693 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800694 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000695 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700696 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800697 BundlePolicy bundle_policy;
698 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700699 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
700 int ice_candidate_pool_size;
701 bool disable_ipv6;
702 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700703 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100704 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700705 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200706 absl::optional<int> screencast_min_bitrate;
707 absl::optional<bool> combined_audio_video_bwe;
708 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800709 TcpCandidatePolicy tcp_candidate_policy;
710 CandidateNetworkPolicy candidate_network_policy;
711 int audio_jitter_buffer_max_packets;
712 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100713 int audio_jitter_buffer_min_delay_ms;
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100714 bool audio_jitter_buffer_enable_rtx_handling;
deadbeef293e9262017-01-11 12:28:30 -0800715 int ice_connection_receiving_timeout;
716 int ice_backup_candidate_pair_ping_interval;
717 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800718 bool prioritize_most_likely_ice_candidate_pairs;
719 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800720 bool prune_turn_ports;
721 bool presume_writable_when_fully_relayed;
722 bool enable_ice_renomination;
723 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200724 absl::optional<int> ice_check_interval_strong_connectivity;
725 absl::optional<int> ice_check_interval_weak_connectivity;
726 absl::optional<int> ice_check_min_interval;
727 absl::optional<int> ice_unwritable_timeout;
728 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800729 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200730 absl::optional<int> stun_candidate_keepalive_interval;
731 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200732 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800733 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200734 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700735 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700736 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700737 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700738 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100739 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800740 };
741 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
742 "Did you add something to RTCConfiguration and forget to "
743 "update operator==?");
744 return type == o.type && servers == o.servers &&
745 bundle_policy == o.bundle_policy &&
746 rtcp_mux_policy == o.rtcp_mux_policy &&
747 tcp_candidate_policy == o.tcp_candidate_policy &&
748 candidate_network_policy == o.candidate_network_policy &&
749 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
750 audio_jitter_buffer_fast_accelerate ==
751 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100752 audio_jitter_buffer_min_delay_ms ==
753 o.audio_jitter_buffer_min_delay_ms &&
Jakob Ivarsson53eae872019-01-10 15:58:36 +0100754 audio_jitter_buffer_enable_rtx_handling ==
755 o.audio_jitter_buffer_enable_rtx_handling &&
deadbeef293e9262017-01-11 12:28:30 -0800756 ice_connection_receiving_timeout ==
757 o.ice_connection_receiving_timeout &&
758 ice_backup_candidate_pair_ping_interval ==
759 o.ice_backup_candidate_pair_ping_interval &&
760 continual_gathering_policy == o.continual_gathering_policy &&
761 certificates == o.certificates &&
762 prioritize_most_likely_ice_candidate_pairs ==
763 o.prioritize_most_likely_ice_candidate_pairs &&
764 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800765 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700766 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100767 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800768 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800769 screencast_min_bitrate == o.screencast_min_bitrate &&
770 combined_audio_video_bwe == o.combined_audio_video_bwe &&
771 enable_dtls_srtp == o.enable_dtls_srtp &&
772 ice_candidate_pool_size == o.ice_candidate_pool_size &&
773 prune_turn_ports == o.prune_turn_ports &&
774 presume_writable_when_fully_relayed ==
775 o.presume_writable_when_fully_relayed &&
776 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800777 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800778 ice_check_interval_strong_connectivity ==
779 o.ice_check_interval_strong_connectivity &&
780 ice_check_interval_weak_connectivity ==
781 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700782 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700783 ice_unwritable_timeout == o.ice_unwritable_timeout &&
784 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800785 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800786 stun_candidate_keepalive_interval ==
787 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200788 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800789 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800790 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700791 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700792 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700793 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700794 use_media_transport_for_data_channels ==
795 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100796 crypto_options == o.crypto_options &&
797 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800798}
799
800bool PeerConnectionInterface::RTCConfiguration::operator!=(
801 const PeerConnectionInterface::RTCConfiguration& o) const {
802 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800803}
804
zhihuang8f65cdf2016-05-06 18:40:30 -0700805// Generate a RTCP CNAME when a PeerConnection is created.
806std::string GenerateRtcpCname() {
807 std::string cname;
808 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100809 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800810 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700811 }
812 return cname;
813}
814
zhihuang1c378ed2017-08-17 14:10:50 -0700815bool ValidateOfferAnswerOptions(
816 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
817 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
818 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700819}
820
zhihuang1c378ed2017-08-17 14:10:50 -0700821// From |rtc_options|, fill parts of |session_options| shared by all generated
822// m= sections (in other words, nothing that involves a map/array).
823void ExtractSharedMediaSessionOptions(
824 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
825 cricket::MediaSessionOptions* session_options) {
826 session_options->vad_enabled = rtc_options.voice_activity_detection;
827 session_options->bundle_enabled = rtc_options.use_rtp_mux;
828}
zhihuanga77e6bb2017-08-14 18:17:48 -0700829
zhihuang38ede132017-06-15 12:52:32 -0700830PeerConnection::PeerConnection(PeerConnectionFactory* factory,
831 std::unique_ptr<RtcEventLog> event_log,
832 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700834 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700835 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700836 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700837 remote_streams_(StreamCollection::Create()),
838 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839
840PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100841 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800842 RTC_DCHECK_RUN_ON(signaling_thread());
843
Steve Anton8af21862017-12-15 11:20:13 -0800844 // Need to stop transceivers before destroying the stats collector because
845 // AudioRtpSender has a reference to the StatsCollector it will update when
846 // stopping.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100847 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -0800848 transceiver->Stop();
849 }
Steve Anton4171afb2017-11-20 10:20:22 -0800850
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700851 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800852 if (stats_collector_) {
853 stats_collector_->WaitForPendingRequest();
854 stats_collector_ = nullptr;
855 }
Steve Anton75737c02017-11-06 10:37:17 -0800856
Steve Anton8af21862017-12-15 11:20:13 -0800857 // Don't destroy BaseChannels until after stats has been cleaned up so that
858 // the last stats request can still read from the channels.
859 DestroyAllChannels();
860
Mirko Bonadei675513b2017-11-09 11:09:25 +0100861 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800862
863 webrtc_session_desc_factory_.reset();
864 sctp_invoker_.reset();
865 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800866 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800867 transport_controller_.reset();
868
deadbeef91dd5672016-05-18 16:55:30 -0700869 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700870 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700871 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700872 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700873 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700874 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800875 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700876 event_log_.reset();
877 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000878}
879
Steve Anton8af21862017-12-15 11:20:13 -0800880void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800881 // Destroy video channels first since they may have a pointer to a voice
882 // channel.
Mirko Bonadei739baf02019-01-27 17:29:42 +0100883 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800884 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800885 DestroyTransceiverChannel(transceiver);
886 }
887 }
Mirko Bonadei739baf02019-01-27 17:29:42 +0100888 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800889 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800890 DestroyTransceiverChannel(transceiver);
891 }
892 }
893 DestroyDataChannel();
894}
895
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000897 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700898 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100899 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700900
901 RTCError config_error = ValidateConfiguration(configuration);
902 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100903 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700904 return false;
905 }
906
Benjamin Wrightcab58882018-05-02 15:12:47 -0700907 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100908 RTC_LOG(LS_ERROR)
909 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100910 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800911 return false;
912 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200913
Benjamin Wrightcab58882018-05-02 15:12:47 -0700914 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800915 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100916 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100917 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800918 return false;
919 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700920
Benjamin Wrightcab58882018-05-02 15:12:47 -0700921 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700922 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700923 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700924 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800925
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200926 cricket::ServerAddresses stun_servers;
927 std::vector<cricket::RelayServerConfig> turn_servers;
928
929 RTCErrorType parse_error =
930 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
931 if (parse_error != RTCErrorType::NONE) {
932 return false;
933 }
934
deadbeef91dd5672016-05-18 16:55:30 -0700935 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700936 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700937 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200938 RTC_FROM_HERE,
939 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
940 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941 return false;
942 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200943 // If initialization was successful, note if STUN or TURN servers
944 // were supplied.
945 if (!stun_servers.empty()) {
946 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
947 }
948 if (!turn_servers.empty()) {
949 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
950 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700952 // Send information about IPv4/IPv6 status.
953 PeerConnectionAddressFamilyCounter address_family;
954 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
955 address_family = kPeerConnection_IPv6;
956 } else {
957 address_family = kPeerConnection_IPv4;
958 }
959 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
960 kPeerConnectionAddressFamilyCounter_Max);
961
Zhi Huange830e682018-03-30 10:48:35 -0700962 const PeerConnectionFactoryInterface::Options& options = factory_->options();
963
Steve Anton75737c02017-11-06 10:37:17 -0800964 // RFC 3264: The numeric value of the session id and version in the
965 // o line MUST be representable with a "64 bit signed integer".
966 // Due to this constraint session id |session_id_| is max limited to
967 // LLONG_MAX.
968 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700969 JsepTransportController::Config config;
970 config.redetermine_role_on_ice_restart =
971 configuration.redetermine_role_on_ice_restart;
972 config.ssl_max_version = factory_->options().ssl_max_version;
973 config.disable_encryption = options.disable_encryption;
974 config.bundle_policy = configuration.bundle_policy;
975 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700976 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
977 // stub.
978 config.crypto_options = configuration.crypto_options.has_value()
979 ? *configuration.crypto_options
980 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700981 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700982 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700983#if defined(ENABLE_EXTERNAL_AUTH)
984 config.enable_external_auth = true;
985#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700986 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700987
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700988 if (configuration.use_media_transport ||
989 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700990 if (!factory_->media_transport_factory()) {
991 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700992 << "PeerConnecton is initialized with use_media_transport = true or "
993 << "use_media_transport_for_data_channels = true "
994 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700995 return false;
996 }
997
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -0800998 config.use_media_transport_for_media = configuration.use_media_transport;
999 config.use_media_transport_for_data_channels =
1000 configuration.use_media_transport_for_data_channels;
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001001 config.media_transport_factory = factory_->media_transport_factory();
1002 }
1003
Zhi Huange830e682018-03-30 10:48:35 -07001004 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001005 signaling_thread(), network_thread(), port_allocator_.get(),
1006 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001007 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001008 this, &PeerConnection::OnTransportControllerConnectionState);
1009 transport_controller_->SignalStandardizedIceConnectionState.connect(
1010 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001011 transport_controller_->SignalConnectionState.connect(
1012 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001013 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001014 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001015 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001016 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001017 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001018 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1019 transport_controller_->SignalDtlsHandshakeError.connect(
1020 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1021
1022 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001023
deadbeefab9b2d12015-10-14 11:33:11 -07001024 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001025 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026
Steve Antonba818672017-11-06 10:21:57 -08001027 configuration_ = configuration;
1028
Steve Anton75737c02017-11-06 10:37:17 -08001029 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1030 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1031 if (!configuration.certificates.empty()) {
1032 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1033 // just picking the first one. The decision should be made based on the DTLS
1034 // handshake. The DTLS negotiations need to know about all certificates.
1035 certificate = configuration.certificates[0];
1036 }
1037
Steve Antond25da372017-11-06 14:50:29 -08001038 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001039
1040 if (options.disable_encryption) {
1041 dtls_enabled_ = false;
1042 } else {
1043 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001044 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001045 // |configuration| can override the default |dtls_enabled_| value.
1046 if (configuration.enable_dtls_srtp) {
1047 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1048 }
1049 }
1050
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001051 if (configuration.use_media_transport_for_data_channels) {
1052 if (configuration.enable_rtp_data_channel) {
1053 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1054 "use_media_transport_for_data_channels are "
1055 "incompatible and cannot both be set to true";
1056 return false;
1057 }
1058 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1059 } else if (configuration.enable_rtp_data_channel) {
1060 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1061 // set. It takes precendence over the disable_sctp_data_channels
1062 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001063 data_channel_type_ = cricket::DCT_RTP;
1064 } else {
1065 // DTLS has to be enabled to use SCTP.
1066 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1067 data_channel_type_ = cricket::DCT_SCTP;
1068 }
1069 }
1070
1071 video_options_.screencast_min_bitrate_kbps =
1072 configuration.screencast_min_bitrate;
1073 audio_options_.combined_audio_video_bwe =
1074 configuration.combined_audio_video_bwe;
1075
1076 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001077 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001078
1079 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001080 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001081
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001082 audio_options_.audio_jitter_buffer_min_delay_ms =
1083 configuration.audio_jitter_buffer_min_delay_ms;
1084
Jakob Ivarsson53eae872019-01-10 15:58:36 +01001085 audio_options_.audio_jitter_buffer_enable_rtx_handling =
1086 configuration.audio_jitter_buffer_enable_rtx_handling;
1087
Steve Anton75737c02017-11-06 10:37:17 -08001088 // Whether the certificate generator/certificate is null or not determines
1089 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1090 // the right instructions by clearing the variables if needed.
1091 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001092 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001093 certificate = nullptr;
1094 } else if (certificate) {
1095 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001096 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001097 }
1098
1099 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1100 signaling_thread(), channel_manager(), this, session_id(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08001101 std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
Steve Anton75737c02017-11-06 10:37:17 -08001102 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1103 this, &PeerConnection::OnCertificateReady);
1104
1105 if (options.disable_encryption) {
1106 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1107 }
1108
1109 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001110 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001111 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112
Steve Anton4171afb2017-11-20 10:20:22 -08001113 // Add default audio/video transceivers for Plan B SDP.
1114 if (!IsUnifiedPlan()) {
1115 transceivers_.push_back(
1116 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1117 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1118 transceivers_.push_back(
1119 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1120 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1121 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001122 int delay_ms =
1123 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001124 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1125 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126 return true;
1127}
1128
Steve Anton038834f2017-07-14 15:59:59 -07001129RTCError PeerConnection::ValidateConfiguration(
1130 const RTCConfiguration& config) const {
1131 if (config.ice_regather_interval_range &&
1132 config.continual_gathering_policy == GATHER_ONCE) {
1133 return RTCError(RTCErrorType::INVALID_PARAMETER,
1134 "ice_regather_interval_range specified but continual "
1135 "gathering policy is GATHER_ONCE");
1136 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001137 auto result =
1138 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1139 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001140}
1141
Yves Gerey665174f2018-06-19 15:03:05 +02001142rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001143 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1144 "Plan SdpSemantics. Please use GetSenders "
1145 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001146 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147}
1148
Yves Gerey665174f2018-06-19 15:03:05 +02001149rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001150 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1151 "Plan SdpSemantics. Please use GetReceivers "
1152 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001153 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154}
1155
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001156bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001157 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1158 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001159 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001160 if (IsClosed()) {
1161 return false;
1162 }
deadbeefab9b2d12015-10-14 11:33:11 -07001163 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001164 return false;
1165 }
deadbeefab9b2d12015-10-14 11:33:11 -07001166
1167 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001168 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1169 observer->SignalAudioTrackAdded.connect(this,
1170 &PeerConnection::OnAudioTrackAdded);
1171 observer->SignalAudioTrackRemoved.connect(
1172 this, &PeerConnection::OnAudioTrackRemoved);
1173 observer->SignalVideoTrackAdded.connect(this,
1174 &PeerConnection::OnVideoTrackAdded);
1175 observer->SignalVideoTrackRemoved.connect(
1176 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001177 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001178
deadbeefab9b2d12015-10-14 11:33:11 -07001179 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001180 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001181 }
1182 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001183 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001184 }
1185
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001186 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001187 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 return true;
1189}
1190
1191void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001192 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1193 "Plan SdpSemantics. Please use RemoveTrack "
1194 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001195 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001196 if (!IsClosed()) {
1197 for (const auto& track : local_stream->GetAudioTracks()) {
1198 RemoveAudioTrack(track.get(), local_stream);
1199 }
1200 for (const auto& track : local_stream->GetVideoTracks()) {
1201 RemoveVideoTrack(track.get(), local_stream);
1202 }
deadbeefab9b2d12015-10-14 11:33:11 -07001203 }
deadbeefab9b2d12015-10-14 11:33:11 -07001204 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001205 stream_observers_.erase(
1206 std::remove_if(
1207 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001208 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001209 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001210 }),
1211 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001212
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001213 if (IsClosed()) {
1214 return;
1215 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001216 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217}
1218
Steve Anton2d6c76a2018-01-05 17:10:52 -08001219RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001220 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001221 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001222 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001223 if (!track) {
1224 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1225 }
1226 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1227 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1228 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1229 "Track has invalid kind: " + track->kind());
1230 }
Steve Antonf9381f02017-12-14 10:23:57 -08001231 if (IsClosed()) {
1232 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1233 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001234 }
Steve Anton4171afb2017-11-20 10:20:22 -08001235 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001236 LOG_AND_RETURN_ERROR(
1237 RTCErrorType::INVALID_PARAMETER,
1238 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001239 }
Steve Antonf9381f02017-12-14 10:23:57 -08001240 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001241 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1242 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001243 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001244 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001245 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001246 }
1247 return sender_or_error;
1248}
deadbeefe1f9d832016-01-14 15:35:42 -08001249
Steve Antonf9381f02017-12-14 10:23:57 -08001250RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1251PeerConnection::AddTrackPlanB(
1252 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001253 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001254 if (stream_ids.size() > 1u) {
1255 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1256 "AddTrack with more than one stream is not "
1257 "supported with Plan B semantics.");
1258 }
1259 std::vector<std::string> adjusted_stream_ids = stream_ids;
1260 if (adjusted_stream_ids.empty()) {
1261 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1262 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001263 cricket::MediaType media_type =
1264 (track->kind() == MediaStreamTrackInterface::kAudioKind
1265 ? cricket::MEDIA_TYPE_AUDIO
1266 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001267 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001268 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001269 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001270 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001271 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001272 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001273 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001274 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001275 if (sender_info) {
1276 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001277 }
Steve Antonf9381f02017-12-14 10:23:57 -08001278 } else {
1279 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001280 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001281 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001282 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001283 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001284 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001285 if (sender_info) {
1286 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001287 }
deadbeefe1f9d832016-01-14 15:35:42 -08001288 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001289 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001290}
deadbeefe1f9d832016-01-14 15:35:42 -08001291
Steve Antonf9381f02017-12-14 10:23:57 -08001292RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1293PeerConnection::AddTrackUnifiedPlan(
1294 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001295 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001296 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1297 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001298 RTC_LOG(LS_INFO) << "Reusing an existing "
1299 << cricket::MediaTypeToString(transceiver->media_type())
1300 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001301 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001302 transceiver->internal()->set_direction(
1303 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001304 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001305 transceiver->internal()->set_direction(
1306 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001307 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001308 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001309 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001310 } else {
1311 cricket::MediaType media_type =
1312 (track->kind() == MediaStreamTrackInterface::kAudioKind
1313 ? cricket::MEDIA_TYPE_AUDIO
1314 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001315 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1316 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001317 std::string sender_id = track->id();
1318 // Avoid creating a sender with an existing ID by generating a random ID.
1319 // This can happen if this is the second time AddTrack has created a sender
1320 // for this track.
1321 if (FindSenderById(sender_id)) {
1322 sender_id = rtc::CreateRandomUuid();
1323 }
Florent Castelli892acf02018-10-01 22:47:20 +02001324 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001325 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1326 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001327 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001328 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001329 }
Steve Antonf9381f02017-12-14 10:23:57 -08001330 return transceiver->sender();
1331}
1332
1333rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1334PeerConnection::FindFirstTransceiverForAddedTrack(
1335 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1336 RTC_DCHECK(track);
1337 for (auto transceiver : transceivers_) {
1338 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001339 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001340 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001341 !transceiver->internal()->has_ever_been_used_to_send() &&
1342 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001343 return transceiver;
1344 }
1345 }
1346 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001347}
1348
1349bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1350 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001351 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001352}
1353
Steve Anton24db5732018-07-23 10:27:33 -07001354RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001355 rtc::scoped_refptr<RtpSenderInterface> sender) {
1356 if (!sender) {
1357 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1358 }
deadbeefe1f9d832016-01-14 15:35:42 -08001359 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001360 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1361 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001362 }
Steve Antonf9381f02017-12-14 10:23:57 -08001363 if (IsUnifiedPlan()) {
1364 auto transceiver = FindTransceiverBySender(sender);
1365 if (!transceiver || !sender->track()) {
1366 return RTCError::OK();
1367 }
1368 sender->SetTrack(nullptr);
1369 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001370 transceiver->internal()->set_direction(
1371 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001372 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001373 transceiver->internal()->set_direction(
1374 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001375 }
Steve Anton4171afb2017-11-20 10:20:22 -08001376 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001377 bool removed;
1378 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1379 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1380 } else {
1381 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1382 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1383 }
1384 if (!removed) {
1385 LOG_AND_RETURN_ERROR(
1386 RTCErrorType::INVALID_PARAMETER,
1387 "Couldn't find sender " + sender->id() + " to remove.");
1388 }
Steve Anton4171afb2017-11-20 10:20:22 -08001389 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001390 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001391 return RTCError::OK();
1392}
1393
1394rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1395PeerConnection::FindTransceiverBySender(
1396 rtc::scoped_refptr<RtpSenderInterface> sender) {
1397 for (auto transceiver : transceivers_) {
1398 if (transceiver->sender() == sender) {
1399 return transceiver;
1400 }
1401 }
1402 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001403}
1404
Steve Anton9158ef62017-11-27 13:01:52 -08001405RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1406PeerConnection::AddTransceiver(
1407 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1408 return AddTransceiver(track, RtpTransceiverInit());
1409}
1410
1411RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1412PeerConnection::AddTransceiver(
1413 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1414 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001415 RTC_CHECK(IsUnifiedPlan())
1416 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001417 if (!track) {
1418 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1419 }
1420 cricket::MediaType media_type;
1421 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1422 media_type = cricket::MEDIA_TYPE_AUDIO;
1423 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1424 media_type = cricket::MEDIA_TYPE_VIDEO;
1425 } else {
1426 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1427 "Track kind is not audio or video");
1428 }
1429 return AddTransceiver(media_type, track, init);
1430}
1431
1432RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1433PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1434 return AddTransceiver(media_type, RtpTransceiverInit());
1435}
1436
1437RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1438PeerConnection::AddTransceiver(cricket::MediaType media_type,
1439 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001440 RTC_CHECK(IsUnifiedPlan())
1441 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001442 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1443 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1444 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1445 "media type is not audio or video");
1446 }
1447 return AddTransceiver(media_type, nullptr, init);
1448}
1449
1450RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1451PeerConnection::AddTransceiver(
1452 cricket::MediaType media_type,
1453 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001454 const RtpTransceiverInit& init,
1455 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001456 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1457 media_type == cricket::MEDIA_TYPE_VIDEO));
1458 if (track) {
1459 RTC_DCHECK_EQ(media_type,
1460 (track->kind() == MediaStreamTrackInterface::kAudioKind
1461 ? cricket::MEDIA_TYPE_AUDIO
1462 : cricket::MEDIA_TYPE_VIDEO));
1463 }
1464
1465 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001466 if (init.send_encodings.size() > 1) {
1467 LOG_AND_RETURN_ERROR(
1468 RTCErrorType::UNSUPPORTED_PARAMETER,
1469 "Attempted to create an encoder with more than 1 encoding parameter.");
1470 }
1471
1472 for (const auto& encoding : init.send_encodings) {
1473 if (encoding.ssrc.has_value()) {
1474 LOG_AND_RETURN_ERROR(
1475 RTCErrorType::UNSUPPORTED_PARAMETER,
1476 "Attempted to set an unimplemented parameter of RtpParameters.");
1477 }
1478 }
1479
1480 RtpParameters parameters;
1481 parameters.encodings = init.send_encodings;
1482 if (UnimplementedRtpParameterHasValue(parameters)) {
1483 LOG_AND_RETURN_ERROR(
1484 RTCErrorType::UNSUPPORTED_PARAMETER,
1485 "Attempted to set an unimplemented parameter of RtpParameters.");
1486 }
Steve Anton9158ef62017-11-27 13:01:52 -08001487
Steve Anton3d954a62018-04-02 11:27:23 -07001488 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1489 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001490 // Set the sender ID equal to the track ID if the track is specified unless
1491 // that sender ID is already in use.
1492 std::string sender_id =
1493 (track && !FindSenderById(track->id()) ? track->id()
1494 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001495 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1496 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001497 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1498 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1499 transceiver->internal()->set_direction(init.direction);
1500
Steve Anton22da89f2018-01-25 13:58:07 -08001501 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001502 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001503 }
Steve Antonf9381f02017-12-14 10:23:57 -08001504
1505 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1506}
1507
Steve Anton02ee47c2018-01-10 16:26:06 -08001508rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1509PeerConnection::CreateSender(
1510 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001511 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001512 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001513 const std::vector<std::string>& stream_ids,
1514 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001515 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001516 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1517 RTC_DCHECK(!track ||
1518 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1519 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1520 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001521 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001522 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001523 } else {
1524 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1525 RTC_DCHECK(!track ||
1526 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1527 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001528 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001529 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001530 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001531 bool set_track_succeeded = sender->SetTrack(track);
1532 RTC_DCHECK(set_track_succeeded);
1533 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001534 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001535 return sender;
1536}
1537
1538rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1539PeerConnection::CreateReceiver(cricket::MediaType media_type,
1540 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001541 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1542 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001543 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001544 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001545 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1546 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001547 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001548 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001549 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001550 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001551 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1552 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001553 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001554 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001555 return receiver;
1556}
1557
1558rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1559PeerConnection::CreateAndAddTransceiver(
1560 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1561 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1562 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001563 // Ensure that the new sender does not have an ID that is already in use by
1564 // another sender.
1565 // Allow receiver IDs to conflict since those come from remote SDP (which
1566 // could be invalid, but should not cause a crash).
1567 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001568 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1569 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001570 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001571 transceiver->internal()->SignalNegotiationNeeded.connect(
1572 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001573 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001574}
1575
Steve Anton52d86772018-02-20 15:48:12 -08001576void PeerConnection::OnNegotiationNeeded() {
1577 RTC_DCHECK_RUN_ON(signaling_thread());
1578 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001579 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001580}
1581
deadbeeffac06552015-11-25 11:26:01 -08001582rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001583 const std::string& kind,
1584 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001585 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1586 "Plan SdpSemantics. Please use AddTransceiver "
1587 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001588 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001589 if (IsClosed()) {
1590 return nullptr;
1591 }
Steve Anton4171afb2017-11-20 10:20:22 -08001592
Seth Hampson5b4f0752018-04-02 16:31:36 -07001593 // Internally we need to have one stream with Plan B semantics, so we
1594 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001595 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001596 if (stream_id.empty()) {
1597 stream_ids.push_back(rtc::CreateRandomUuid());
1598 RTC_LOG(LS_INFO)
1599 << "No stream_id specified for sender. Generated stream ID: "
1600 << stream_ids[0];
1601 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001602 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001603 }
1604
Steve Anton4171afb2017-11-20 10:20:22 -08001605 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001606 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001607 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001608 auto* audio_sender = new AudioRtpSender(
1609 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001610 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001611 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001612 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001613 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001614 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001615 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001616 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001617 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001618 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001619 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001620 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001621 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001622 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001623 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001624 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001625 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001626
deadbeefe1f9d832016-01-14 15:35:42 -08001627 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001628}
1629
deadbeef70ab1a12015-09-28 16:53:55 -07001630std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1631 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001632 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001633 for (const auto& sender : GetSendersInternal()) {
Steve Anton4171afb2017-11-20 10:20:22 -08001634 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001635 }
1636 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001637}
1638
Steve Anton4171afb2017-11-20 10:20:22 -08001639std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1640PeerConnection::GetSendersInternal() const {
1641 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1642 all_senders;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001643 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001644 auto senders = transceiver->internal()->senders();
1645 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1646 }
1647 return all_senders;
1648}
1649
deadbeef70ab1a12015-09-28 16:53:55 -07001650std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1651PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001652 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001653 for (const auto& receiver : GetReceiversInternal()) {
1654 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001655 }
1656 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001657}
1658
Steve Anton4171afb2017-11-20 10:20:22 -08001659std::vector<
1660 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1661PeerConnection::GetReceiversInternal() const {
1662 std::vector<
1663 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1664 all_receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001665 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08001666 auto receivers = transceiver->internal()->receivers();
1667 all_receivers.insert(all_receivers.end(), receivers.begin(),
1668 receivers.end());
1669 }
1670 return all_receivers;
1671}
1672
Steve Anton9158ef62017-11-27 13:01:52 -08001673std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1674PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001675 RTC_CHECK(IsUnifiedPlan())
1676 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001677 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001678 for (const auto& transceiver : transceivers_) {
Steve Anton9158ef62017-11-27 13:01:52 -08001679 all_transceivers.push_back(transceiver);
1680 }
1681 return all_transceivers;
1682}
1683
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001684bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001685 MediaStreamTrackInterface* track,
1686 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001687 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001688 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001689 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001690 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001691 return false;
1692 }
1693
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001694 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001695 // The StatsCollector is used to tell if a track is valid because it may
1696 // remember tracks that the PeerConnection previously removed.
1697 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001698 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1699 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001700 return false;
1701 }
Steve Antonad182762018-09-05 20:22:40 +00001702 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1703 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704 return true;
1705}
1706
hbos74e1a4f2016-09-15 23:33:01 -07001707void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001708 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001709 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001710 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001711 stats_collector_->GetStatsReport(callback);
1712}
1713
Henrik Boström1df1bf82018-03-20 13:24:20 +01001714void PeerConnection::GetStats(
1715 rtc::scoped_refptr<RtpSenderInterface> selector,
1716 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1717 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1718 RTC_DCHECK(callback);
1719 RTC_DCHECK(stats_collector_);
1720 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1721 if (selector) {
1722 for (const auto& proxy_transceiver : transceivers_) {
1723 for (const auto& proxy_sender :
1724 proxy_transceiver->internal()->senders()) {
1725 if (proxy_sender == selector) {
1726 internal_sender = proxy_sender->internal();
1727 break;
1728 }
1729 }
1730 if (internal_sender)
1731 break;
1732 }
1733 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001734 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001735 // belong to the PeerConnection (in Plan B, senders can be removed from the
1736 // PeerConnection). This means that "all the stats objects representing the
1737 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1738 // produces an empty stats report.
1739 stats_collector_->GetStatsReport(internal_sender, callback);
1740}
1741
1742void PeerConnection::GetStats(
1743 rtc::scoped_refptr<RtpReceiverInterface> selector,
1744 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1745 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1746 RTC_DCHECK(callback);
1747 RTC_DCHECK(stats_collector_);
1748 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1749 if (selector) {
1750 for (const auto& proxy_transceiver : transceivers_) {
1751 for (const auto& proxy_receiver :
1752 proxy_transceiver->internal()->receivers()) {
1753 if (proxy_receiver == selector) {
1754 internal_receiver = proxy_receiver->internal();
1755 break;
1756 }
1757 }
1758 if (internal_receiver)
1759 break;
1760 }
1761 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001762 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001763 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1764 // the PeerConnection). This means that "all the stats objects representing
1765 // the selector" is an empty set. Invoking GetStatsReport() with a null
1766 // selector produces an empty stats report.
1767 stats_collector_->GetStatsReport(internal_receiver, callback);
1768}
1769
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001770PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1771 return signaling_state_;
1772}
1773
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774PeerConnectionInterface::IceConnectionState
1775PeerConnection::ice_connection_state() {
1776 return ice_connection_state_;
1777}
1778
Alex Loiko9289eda2018-11-23 16:18:59 +00001779PeerConnectionInterface::IceConnectionState
1780PeerConnection::standardized_ice_connection_state() {
1781 return standardized_ice_connection_state_;
1782}
1783
Jonas Olsson635474e2018-10-18 15:58:17 +02001784PeerConnectionInterface::PeerConnectionState
1785PeerConnection::peer_connection_state() {
1786 return connection_state_;
1787}
1788
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789PeerConnectionInterface::IceGatheringState
1790PeerConnection::ice_gathering_state() {
1791 return ice_gathering_state_;
1792}
1793
Yves Gerey665174f2018-06-19 15:03:05 +02001794rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001795 const std::string& label,
1796 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001797 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001798
deadbeefab9b2d12015-10-14 11:33:11 -07001799 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001800
kwibergd1fe2812016-04-27 06:47:29 -07001801 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001802 if (config) {
1803 internal_config.reset(new InternalDataChannelInit(*config));
1804 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001805 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001806 InternalCreateDataChannel(label, internal_config.get()));
1807 if (!channel.get()) {
1808 return nullptr;
1809 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001810
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001811 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1812 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001813 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001814 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001815 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001816 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001817 return DataChannelProxy::Create(signaling_thread(), channel.get());
1818}
1819
1820void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001821 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001822 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001823
nisse7ce109a2017-01-31 00:57:56 -08001824 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001825 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001826 return;
1827 }
deadbeefab9b2d12015-10-14 11:33:11 -07001828
Steve Anton8d3444d2017-10-20 15:30:51 -07001829 if (IsClosed()) {
1830 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001831 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001832 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001833 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001834 return;
1835 }
1836
zhihuang1c378ed2017-08-17 14:10:50 -07001837 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001838 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001839 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001840 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001841 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001842 return;
1843 }
1844
Steve Anton22da89f2018-01-25 13:58:07 -08001845 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1846 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1847 if (IsUnifiedPlan()) {
1848 RTCError error = HandleLegacyOfferOptions(options);
1849 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001850 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001851 return;
1852 }
1853 }
1854
zhihuang1c378ed2017-08-17 14:10:50 -07001855 cricket::MediaSessionOptions session_options;
1856 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001857 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858}
1859
Steve Anton22da89f2018-01-25 13:58:07 -08001860RTCError PeerConnection::HandleLegacyOfferOptions(
1861 const RTCOfferAnswerOptions& options) {
1862 RTC_DCHECK(IsUnifiedPlan());
1863
1864 if (options.offer_to_receive_audio == 0) {
1865 RemoveRecvDirectionFromReceivingTransceiversOfType(
1866 cricket::MEDIA_TYPE_AUDIO);
1867 } else if (options.offer_to_receive_audio == 1) {
1868 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1869 } else if (options.offer_to_receive_audio > 1) {
1870 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1871 "offer_to_receive_audio > 1 is not supported.");
1872 }
1873
1874 if (options.offer_to_receive_video == 0) {
1875 RemoveRecvDirectionFromReceivingTransceiversOfType(
1876 cricket::MEDIA_TYPE_VIDEO);
1877 } else if (options.offer_to_receive_video == 1) {
1878 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1879 } else if (options.offer_to_receive_video > 1) {
1880 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1881 "offer_to_receive_video > 1 is not supported.");
1882 }
1883
1884 return RTCError::OK();
1885}
1886
1887void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1888 cricket::MediaType media_type) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01001889 for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001890 RtpTransceiverDirection new_direction =
1891 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1892 if (new_direction != transceiver->direction()) {
1893 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1894 << " transceiver (MID="
1895 << transceiver->mid().value_or("<not set>") << ") from "
1896 << RtpTransceiverDirectionToString(
1897 transceiver->direction())
1898 << " to "
1899 << RtpTransceiverDirectionToString(new_direction)
1900 << " since CreateOffer specified offer_to_receive=0";
1901 transceiver->internal()->set_direction(new_direction);
1902 }
Steve Anton22da89f2018-01-25 13:58:07 -08001903 }
1904}
1905
1906void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1907 cricket::MediaType media_type) {
1908 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001909 RTC_LOG(LS_INFO)
1910 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1911 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001912 RtpTransceiverInit init;
1913 init.direction = RtpTransceiverDirection::kRecvOnly;
1914 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1915 }
1916}
1917
1918std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1919PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1920 std::vector<
1921 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1922 receiving_transceivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +01001923 for (const auto& transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001924 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001925 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1926 receiving_transceivers.push_back(transceiver);
1927 }
1928 }
1929 return receiving_transceivers;
1930}
1931
htaa2a49d92016-03-04 02:51:39 -08001932void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1933 const RTCOfferAnswerOptions& options) {
1934 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001935 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001936 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001937 return;
1938 }
1939
Steve Antondffead82018-02-06 10:31:29 -08001940 if (!(signaling_state_ == kHaveRemoteOffer ||
1941 signaling_state_ == kHaveLocalPrAnswer)) {
1942 std::string error =
1943 "PeerConnection cannot create an answer in a state other than "
1944 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001946 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001947 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001948 return;
1949 }
1950
Steve Antondffead82018-02-06 10:31:29 -08001951 // The remote description should be set if we're in the right state.
1952 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001953
Steve Anton22da89f2018-01-25 13:58:07 -08001954 if (IsUnifiedPlan()) {
1955 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1956 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1957 "supported with Unified Plan semantics. Use the "
1958 "RtpTransceiver API instead.";
1959 }
1960 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1961 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1962 "supported with Unified Plan semantics. Use the "
1963 "RtpTransceiver API instead.";
1964 }
1965 }
1966
htaa2a49d92016-03-04 02:51:39 -08001967 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001968 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001969
Steve Antond25da372017-11-06 14:50:29 -08001970 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001971}
1972
1973void PeerConnection::SetLocalDescription(
1974 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001975 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001976 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001977
Steve Anton80dd7b52018-02-16 17:08:42 -08001978 // The SetLocalDescription contract is that we take ownership of the session
1979 // description regardless of the outcome, so wrap it in a unique_ptr right
1980 // away. Ideally, SetLocalDescription's signature will be changed to take the
1981 // description as a unique_ptr argument to formalize this agreement.
1982 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1983
nisse7ce109a2017-01-31 00:57:56 -08001984 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001985 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986 return;
1987 }
Steve Anton8a006912017-12-04 15:25:56 -08001988
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001989 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001990 PostSetSessionDescriptionFailure(
1991 observer,
1992 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 return;
1994 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001995
Steve Anton80dd7b52018-02-16 17:08:42 -08001996 // If a session error has occurred the PeerConnection is in a possibly
1997 // inconsistent state so fail right away.
1998 if (session_error() != SessionError::kNone) {
1999 std::string error_message = GetSessionErrorMsg();
2000 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002001 PostSetSessionDescriptionFailure(
2002 observer,
2003 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002004 return;
2005 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002006
Steve Anton80dd7b52018-02-16 17:08:42 -08002007 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2008 if (!error.ok()) {
2009 std::string error_message = GetSetDescriptionErrorMessage(
2010 cricket::CS_LOCAL, desc->GetType(), error);
2011 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002012 PostSetSessionDescriptionFailure(
2013 observer,
2014 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002015 return;
2016 }
2017
2018 // Grab the description type before moving ownership to ApplyLocalDescription,
2019 // which may destroy it before returning.
2020 const SdpType type = desc->GetType();
2021
2022 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002023 // |desc| may be destroyed at this point.
2024
2025 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002026 // If ApplyLocalDescription fails, the PeerConnection could be in an
2027 // inconsistent state, so act conservatively here and set the session error
2028 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2029 SetSessionError(SessionError::kContent, error.message());
2030 std::string error_message =
2031 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2032 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002033 PostSetSessionDescriptionFailure(
2034 observer,
2035 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002036 return;
2037 }
Steve Anton8a006912017-12-04 15:25:56 -08002038 RTC_DCHECK(local_description());
2039
2040 PostSetSessionDescriptionSuccess(observer);
2041
Steve Antonad182762018-09-05 20:22:40 +00002042 // MaybeStartGathering needs to be called after posting
2043 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2044 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002045 transport_controller_->MaybeStartGathering();
2046
Steve Antona3a92c22017-12-07 10:27:41 -08002047 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002048 // TODO(deadbeef): We already had to hop to the network thread for
2049 // MaybeStartGathering...
2050 network_thread()->Invoke<void>(
2051 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2052 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002053 // Make UMA notes about what was agreed to.
2054 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002055 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002056 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002057}
2058
2059RTCError PeerConnection::ApplyLocalDescription(
2060 std::unique_ptr<SessionDescriptionInterface> desc) {
2061 RTC_DCHECK_RUN_ON(signaling_thread());
2062 RTC_DCHECK(desc);
2063
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002064 // Update stats here so that we have the most recent stats for tracks and
2065 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002066 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002067
Steve Antondcc3c022017-12-22 16:02:54 -08002068 // Take a reference to the old local description since it's used below to
2069 // compare against the new local description. When setting the new local
2070 // description, grab ownership of the replaced session description in case it
2071 // is the same as |old_local_description|, to keep it alive for the duration
2072 // of the method.
2073 const SessionDescriptionInterface* old_local_description =
2074 local_description();
2075 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002076 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002077 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002078 replaced_local_description = pending_local_description_
2079 ? std::move(pending_local_description_)
2080 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002081 current_local_description_ = std::move(desc);
2082 pending_local_description_ = nullptr;
2083 current_remote_description_ = std::move(pending_remote_description_);
2084 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002085 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002086 pending_local_description_ = std::move(desc);
2087 }
2088 // The session description to apply now must be accessed by
2089 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002090 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002091
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002092 if (!is_caller_) {
2093 if (remote_description()) {
2094 // Remote description was applied first, so this PC is the callee.
2095 is_caller_ = false;
2096 } else {
2097 // Local description is applied first, so this PC is the caller.
2098 is_caller_ = true;
2099 }
2100 }
2101
Zhi Huange830e682018-03-30 10:48:35 -07002102 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2103 if (!error.ok()) {
2104 return error;
2105 }
2106
Steve Antondcc3c022017-12-22 16:02:54 -08002107 if (IsUnifiedPlan()) {
2108 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002109 cricket::CS_LOCAL, *local_description(), old_local_description,
2110 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002111 if (!error.ok()) {
2112 return error;
2113 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002114 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2115 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002116 for (const auto& transceiver : transceivers_) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002117 // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
2118 // Note that code paths that don't set MID won't be able to use
2119 // information about DTLS transports.
2120 if (transceiver->mid()) {
2121 auto dtls_transport =
2122 LookupDtlsTransportByMidInternal(*transceiver->mid());
2123 transceiver->internal()->sender_internal()->set_transport(
2124 dtls_transport);
2125 transceiver->internal()->receiver_internal()->set_transport(
2126 dtls_transport);
2127 }
2128
Steve Antondcc3c022017-12-22 16:02:54 -08002129 const ContentInfo* content =
2130 FindMediaSectionForTransceiver(transceiver, local_description());
2131 if (!content) {
2132 continue;
2133 }
2134 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002135 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2136 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002137 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002138 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2139 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2140 // "recvonly", process the removal of a remote track for the media
2141 // description, given transceiver, removeList, and muteTracks.
2142 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2143 (transceiver->internal()->fired_direction() &&
2144 RtpTransceiverDirectionHasRecv(
2145 *transceiver->internal()->fired_direction()))) {
2146 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2147 &removed_streams);
2148 }
2149 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2150 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002151 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002152 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002153 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002154 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002155 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002156 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002157 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002158 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002159 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002160 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002161 }
2162 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002163 // Media channels will be created only when offer is set. These may use new
2164 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002165 if (type == SdpType::kOffer) {
2166 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2167 // description is applied. Restore back to old description.
2168 RTCError error = CreateChannels(*local_description()->description());
2169 if (!error.ok()) {
2170 return error;
2171 }
2172 }
Steve Antondcc3c022017-12-22 16:02:54 -08002173 // Remove unused channels if MediaContentDescription is rejected.
2174 RemoveUnusedChannels(local_description()->description());
2175 }
Steve Anton8a006912017-12-04 15:25:56 -08002176
Zhi Huange830e682018-03-30 10:48:35 -07002177 error = UpdateSessionState(type, cricket::CS_LOCAL,
2178 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002179 if (!error.ok()) {
2180 return error;
2181 }
Steve Antondcc3c022017-12-22 16:02:54 -08002182
Steve Anton8a006912017-12-04 15:25:56 -08002183 if (remote_description()) {
2184 // Now that we have a local description, we can push down remote candidates.
2185 UseCandidatesInSessionDescription(remote_description());
2186 }
2187
2188 pending_ice_restarts_.clear();
2189 if (session_error() != SessionError::kNone) {
2190 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2191 }
2192
deadbeefab9b2d12015-10-14 11:33:11 -07002193 // If setting the description decided our SSL role, allocate any necessary
2194 // SCTP sids.
2195 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002196 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002197 AllocateSctpSids(role);
2198 }
2199
Steve Antond3679212018-01-17 17:41:02 -08002200 if (IsUnifiedPlan()) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01002201 for (const auto& transceiver : transceivers_) {
Steve Antond3679212018-01-17 17:41:02 -08002202 const ContentInfo* content =
2203 FindMediaSectionForTransceiver(transceiver, local_description());
2204 if (!content) {
2205 continue;
2206 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002207 cricket::ChannelInterface* channel = transceiver->internal()->channel();
2208 if (content->rejected || !channel || channel->local_streams().empty()) {
Steve Anton60b6c1d2018-06-13 11:32:27 -07002209 // 0 is a special value meaning "this sender has no associated send
2210 // stream". Need to call this so the sender won't attempt to configure
2211 // a no longer existing stream and run into DCHECKs in the lower
2212 // layers.
2213 transceiver->internal()->sender_internal()->SetSsrc(0);
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002214 } else {
2215 // Get the StreamParams from the channel which could generate SSRCs.
2216 const std::vector<StreamParams>& streams = channel->local_streams();
2217 transceiver->internal()->sender_internal()->set_stream_ids(
2218 streams[0].stream_ids());
2219 transceiver->internal()->sender_internal()->SetSsrc(
2220 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002221 }
2222 }
2223 } else {
2224 // Plan B semantics.
2225
Steve Antondcc3c022017-12-22 16:02:54 -08002226 // Update state and SSRC of local MediaStreams and DataChannels based on the
2227 // local session description.
2228 const cricket::ContentInfo* audio_content =
2229 GetFirstAudioContent(local_description()->description());
2230 if (audio_content) {
2231 if (audio_content->rejected) {
2232 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2233 } else {
2234 const cricket::AudioContentDescription* audio_desc =
2235 audio_content->media_description()->as_audio();
2236 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2237 }
deadbeeffaac4972015-11-12 15:33:07 -08002238 }
deadbeefab9b2d12015-10-14 11:33:11 -07002239
Steve Antondcc3c022017-12-22 16:02:54 -08002240 const cricket::ContentInfo* video_content =
2241 GetFirstVideoContent(local_description()->description());
2242 if (video_content) {
2243 if (video_content->rejected) {
2244 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2245 } else {
2246 const cricket::VideoContentDescription* video_desc =
2247 video_content->media_description()->as_video();
2248 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2249 }
deadbeeffaac4972015-11-12 15:33:07 -08002250 }
deadbeefab9b2d12015-10-14 11:33:11 -07002251 }
2252
2253 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002254 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002255 if (data_content) {
2256 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002257 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002258 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002259 cricket::kMediaProtocolRtpPrefix)) {
2260 UpdateLocalRtpDataChannels(data_desc->streams());
2261 }
2262 }
2263
Steve Anton8a006912017-12-04 15:25:56 -08002264 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002265}
2266
Steve Anton06817cd2018-12-18 15:55:30 -08002267// The SDP parser used to populate these values by default for the 'content
2268// name' if an a=mid line was absent.
2269static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2270 switch (media_type) {
2271 case cricket::MEDIA_TYPE_AUDIO:
2272 return cricket::CN_AUDIO;
2273 case cricket::MEDIA_TYPE_VIDEO:
2274 return cricket::CN_VIDEO;
2275 case cricket::MEDIA_TYPE_DATA:
2276 return cricket::CN_DATA;
2277 }
2278 RTC_NOTREACHED();
2279 return "";
2280}
2281
2282void PeerConnection::FillInMissingRemoteMids(
2283 cricket::SessionDescription* remote_description) {
2284 RTC_DCHECK(remote_description);
2285 const cricket::ContentInfos& local_contents =
2286 (local_description() ? local_description()->description()->contents()
2287 : cricket::ContentInfos());
Steve Anton06817cd2018-12-18 15:55:30 -08002288 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2289 cricket::ContentInfo& content = remote_description->contents()[i];
2290 if (!content.name.empty()) {
2291 continue;
2292 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002293 std::string new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002294 absl::string_view source_explanation;
2295 if (IsUnifiedPlan()) {
2296 if (i < local_contents.size()) {
2297 new_mid = local_contents[i].name;
2298 source_explanation = "from the matching local media section";
2299 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002300 new_mid = mid_generator_();
Steve Anton06817cd2018-12-18 15:55:30 -08002301 source_explanation = "generated just now";
2302 }
2303 } else {
Amit Hilbuchae3df542019-01-07 12:13:08 -08002304 new_mid = std::string(
2305 GetDefaultMidForPlanB(content.media_description()->type()));
Steve Anton06817cd2018-12-18 15:55:30 -08002306 source_explanation = "to match pre-existing behavior";
2307 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08002308 content.name = new_mid;
Steve Anton06817cd2018-12-18 15:55:30 -08002309 remote_description->transport_infos()[i].content_name =
2310 std::string(new_mid);
2311 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2312 << " is missing an a=mid line. Filling in the value '"
2313 << new_mid << "' " << source_explanation << ".";
2314 }
2315}
2316
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002317void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002318 SetSessionDescriptionObserver* observer,
2319 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002320 SetRemoteDescription(
2321 std::unique_ptr<SessionDescriptionInterface>(desc),
2322 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2323 new SetRemoteDescriptionObserverAdapter(this, observer)));
2324}
2325
2326void PeerConnection::SetRemoteDescription(
2327 std::unique_ptr<SessionDescriptionInterface> desc,
2328 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002329 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002330
nisse7ce109a2017-01-31 00:57:56 -08002331 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002332 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002333 return;
2334 }
Steve Anton8a006912017-12-04 15:25:56 -08002335
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002336 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002337 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002338 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002339 return;
2340 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002341
Steve Anton80dd7b52018-02-16 17:08:42 -08002342 // If a session error has occurred the PeerConnection is in a possibly
2343 // inconsistent state so fail right away.
2344 if (session_error() != SessionError::kNone) {
2345 std::string error_message = GetSessionErrorMsg();
2346 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2347 observer->OnSetRemoteDescriptionComplete(
2348 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2349 return;
2350 }
Steve Anton71439a62018-02-15 11:53:06 -08002351
Steve Antonba42e992018-04-09 14:10:01 -07002352 if (desc->GetType() == SdpType::kOffer) {
2353 // Report to UMA the format of the received offer.
2354 ReportSdpFormatReceived(*desc);
2355 }
2356
Steve Anton06817cd2018-12-18 15:55:30 -08002357 // Handle remote descriptions missing a=mid lines for interop with legacy end
2358 // points.
2359 FillInMissingRemoteMids(desc->description());
2360
Steve Anton80dd7b52018-02-16 17:08:42 -08002361 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002362 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002363 std::string error_message = GetSetDescriptionErrorMessage(
2364 cricket::CS_REMOTE, desc->GetType(), error);
2365 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002366 observer->OnSetRemoteDescriptionComplete(
2367 RTCError(error.type(), std::move(error_message)));
2368 return;
2369 }
Steve Anton71439a62018-02-15 11:53:06 -08002370
Steve Anton80dd7b52018-02-16 17:08:42 -08002371 // Grab the description type before moving ownership to
2372 // ApplyRemoteDescription, which may destroy it before returning.
2373 const SdpType type = desc->GetType();
2374
2375 error = ApplyRemoteDescription(std::move(desc));
2376 // |desc| may be destroyed at this point.
2377
2378 if (!error.ok()) {
2379 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2380 // inconsistent state, so act conservatively here and set the session error
2381 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2382 SetSessionError(SessionError::kContent, error.message());
2383 std::string error_message =
2384 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2385 RTC_LOG(LS_ERROR) << error_message;
2386 observer->OnSetRemoteDescriptionComplete(
2387 RTCError(error.type(), std::move(error_message)));
2388 return;
2389 }
2390 RTC_DCHECK(remote_description());
2391
2392 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002393 // TODO(deadbeef): We already had to hop to the network thread for
2394 // MaybeStartGathering...
2395 network_thread()->Invoke<void>(
2396 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2397 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002398 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002399 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002400 }
2401
2402 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002403 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002404}
2405
2406RTCError PeerConnection::ApplyRemoteDescription(
2407 std::unique_ptr<SessionDescriptionInterface> desc) {
2408 RTC_DCHECK_RUN_ON(signaling_thread());
2409 RTC_DCHECK(desc);
2410
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 // Update stats here so that we have the most recent stats for tracks and
2412 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002413 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002414
Steve Antondcc3c022017-12-22 16:02:54 -08002415 // Take a reference to the old remote description since it's used below to
2416 // compare against the new remote description. When setting the new remote
2417 // description, grab ownership of the replaced session description in case it
2418 // is the same as |old_remote_description|, to keep it alive for the duration
2419 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002420 const SessionDescriptionInterface* old_remote_description =
2421 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002422 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002423 SdpType type = desc->GetType();
2424 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002425 replaced_remote_description = pending_remote_description_
2426 ? std::move(pending_remote_description_)
2427 : std::move(current_remote_description_);
2428 current_remote_description_ = std::move(desc);
2429 pending_remote_description_ = nullptr;
2430 current_local_description_ = std::move(pending_local_description_);
2431 } else {
2432 replaced_remote_description = std::move(pending_remote_description_);
2433 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434 }
Steve Anton8a006912017-12-04 15:25:56 -08002435 // The session description to apply now must be accessed by
2436 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002437 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002438
Zhi Huange830e682018-03-30 10:48:35 -07002439 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2440 if (!error.ok()) {
2441 return error;
2442 }
Steve Anton8a006912017-12-04 15:25:56 -08002443 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002444 if (IsUnifiedPlan()) {
2445 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002446 cricket::CS_REMOTE, *remote_description(), local_description(),
2447 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002448 if (!error.ok()) {
2449 return error;
2450 }
Steve Antondcc3c022017-12-22 16:02:54 -08002451 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002452 // Media channels will be created only when offer is set. These may use new
2453 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002454 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002455 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002456 // description is applied. Restore back to old description.
2457 RTCError error = CreateChannels(*remote_description()->description());
2458 if (!error.ok()) {
2459 return error;
2460 }
2461 }
Steve Antondcc3c022017-12-22 16:02:54 -08002462 // Remove unused channels if MediaContentDescription is rejected.
2463 RemoveUnusedChannels(remote_description()->description());
2464 }
Steve Anton8a006912017-12-04 15:25:56 -08002465
Zhi Huange830e682018-03-30 10:48:35 -07002466 // NOTE: Candidates allocation will be initiated only when
2467 // SetLocalDescription is called.
2468 error = UpdateSessionState(type, cricket::CS_REMOTE,
2469 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002470 if (!error.ok()) {
2471 return error;
2472 }
2473
2474 if (local_description() &&
2475 !UseCandidatesInSessionDescription(remote_description())) {
2476 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2477 }
2478
2479 if (old_remote_description) {
2480 for (const cricket::ContentInfo& content :
2481 old_remote_description->description()->contents()) {
2482 // Check if this new SessionDescription contains new ICE ufrag and
2483 // password that indicates the remote peer requests an ICE restart.
2484 // TODO(deadbeef): When we start storing both the current and pending
2485 // remote description, this should reset pending_ice_restarts and compare
2486 // against the current description.
2487 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2488 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002489 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002490 pending_ice_restarts_.insert(content.name);
2491 }
2492 } else {
2493 // We retain all received candidates only if ICE is not restarted.
2494 // When ICE is restarted, all previous candidates belong to an old
2495 // generation and should not be kept.
2496 // TODO(deadbeef): This goes against the W3C spec which says the remote
2497 // description should only contain candidates from the last set remote
2498 // description plus any candidates added since then. We should remove
2499 // this once we're sure it won't break anything.
2500 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2501 old_remote_description, content.name, mutable_remote_description());
2502 }
2503 }
2504 }
2505
2506 if (session_error() != SessionError::kNone) {
2507 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2508 }
2509
2510 // Set the the ICE connection state to connecting since the connection may
2511 // become writable with peer reflexive candidates before any remote candidate
2512 // is signaled.
2513 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2514 // is to have a new signal the indicates a change in checking state from the
2515 // transport and expose a new checking() member from transport that can be
2516 // read to determine the current checking state. The existing SignalConnecting
2517 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002518 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002519 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002520 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2521 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2522 }
2523
deadbeefab9b2d12015-10-14 11:33:11 -07002524 // If setting the description decided our SSL role, allocate any necessary
2525 // SCTP sids.
2526 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002527 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002528 AllocateSctpSids(role);
2529 }
2530
Steve Antondcc3c022017-12-22 16:02:54 -08002531 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002532 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002533 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002534 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002535 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002536 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Mirko Bonadei739baf02019-01-27 17:29:42 +01002537 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08002538 const ContentInfo* content =
2539 FindMediaSectionForTransceiver(transceiver, remote_description());
2540 if (!content) {
2541 continue;
2542 }
2543 const MediaContentDescription* media_desc = content->media_description();
2544 RtpTransceiverDirection local_direction =
2545 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002546 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2547 // RTCSessionDescription: Set the associated remote streams given
2548 // transceiver.[[Receiver]], msids, addList, and removeList".
2549 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2550 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2551 std::vector<std::string> stream_ids;
2552 if (!media_desc->streams().empty()) {
2553 // The remote description has signaled the stream IDs.
2554 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002555 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002556 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2557 << " (" << GetStreamIdsString(stream_ids) << ").";
2558 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2559 stream_ids, &added_streams,
2560 &removed_streams);
2561 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2562 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2563 // and transceiver's current direction is neither sendrecv nor recvonly,
2564 // process the addition of a remote track for the media description.
2565 if (!transceiver->fired_direction() ||
2566 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2567 RTC_LOG(LS_INFO)
2568 << "Processing the addition of a remote track for MID="
2569 << content->name << ".";
2570 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002571 }
Steve Antondcc3c022017-12-22 16:02:54 -08002572 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002573 // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
Steve Anton0f5400a2018-07-17 14:25:36 -07002574 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2575 // removal of a remote track for the media description, given transceiver,
2576 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002577 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002578 (transceiver->fired_direction() &&
2579 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2580 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2581 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002582 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002583 // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
Steve Anton0f5400a2018-07-17 14:25:36 -07002584 transceiver->internal()->set_fired_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002585 // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
Steve Anton0f5400a2018-07-17 14:25:36 -07002586 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002587 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002588 // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
Steve Anton0f5400a2018-07-17 14:25:36 -07002589 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002590 transceiver->internal()->set_current_direction(local_direction);
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002591 // 2.2.8.1.11.[3-6]: Set the transport internal slots.
2592 if (transceiver->mid()) {
2593 auto dtls_transport =
2594 LookupDtlsTransportByMidInternal(*transceiver->mid());
2595 transceiver->internal()->sender_internal()->set_transport(
2596 dtls_transport);
2597 transceiver->internal()->receiver_internal()->set_transport(
2598 dtls_transport);
2599 }
Steve Antondcc3c022017-12-22 16:02:54 -08002600 }
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01002601 // 2.2.8.1.12: If the media description is rejected, and transceiver is
Steve Anton0f5400a2018-07-17 14:25:36 -07002602 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002603 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002604 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2605 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002606 transceiver->Stop();
2607 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002608 if (!content->rejected &&
2609 RtpTransceiverDirectionHasRecv(local_direction)) {
2610 // Set ssrc to 0 in the case of an unsignalled ssrc.
2611 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002612 if (!media_desc->streams().empty() &&
2613 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002614 ssrc = media_desc->streams()[0].first_ssrc();
2615 }
2616 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002617 }
Steve Antondcc3c022017-12-22 16:02:54 -08002618 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002619 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002620 auto observer = Observer();
Mirko Bonadei739baf02019-01-27 17:29:42 +01002621 for (const auto& transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002622 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002623 observer->OnTrack(transceiver);
2624 observer->OnAddTrack(transceiver->receiver(),
2625 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002626 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002627 for (const auto& stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002628 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002629 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002630 for (const auto& transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002631 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002632 }
Mirko Bonadei739baf02019-01-27 17:29:42 +01002633 for (const auto& stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002634 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002635 }
Steve Antondcc3c022017-12-22 16:02:54 -08002636 }
2637
Henrik Boströmfdb92012017-11-09 19:55:44 +01002638 const cricket::ContentInfo* audio_content =
2639 GetFirstAudioContent(remote_description()->description());
2640 const cricket::ContentInfo* video_content =
2641 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002642 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002643 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002644 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002645 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002646 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002647 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002648
2649 // Check if the descriptions include streams, just in case the peer supports
2650 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002651 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002652 (audio_desc && !audio_desc->streams().empty()) ||
2653 (video_desc && !video_desc->streams().empty())) {
2654 remote_peer_supports_msid_ = true;
2655 }
deadbeefab9b2d12015-10-14 11:33:11 -07002656
2657 // We wait to signal new streams until we finish processing the description,
2658 // since only at that point will new streams have all their tracks.
2659 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2660
Steve Antondcc3c022017-12-22 16:02:54 -08002661 if (!IsUnifiedPlan()) {
2662 // TODO(steveanton): When removing RTP senders/receivers in response to a
2663 // rejected media section, there is some cleanup logic that expects the
2664 // voice/ video channel to still be set. But in this method the voice/video
2665 // channel would have been destroyed by the SetRemoteDescription caller
2666 // above so the cleanup that relies on them fails to run. The RemoveSenders
2667 // calls should be moved to right before the DestroyChannel calls to fix
2668 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002669
Steve Antondcc3c022017-12-22 16:02:54 -08002670 // Find all audio rtp streams and create corresponding remote AudioTracks
2671 // and MediaStreams.
2672 if (audio_content) {
2673 if (audio_content->rejected) {
2674 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2675 } else {
2676 bool default_audio_track_needed =
2677 !remote_peer_supports_msid_ &&
2678 RtpTransceiverDirectionHasSend(audio_desc->direction());
2679 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2680 default_audio_track_needed, audio_desc->type(),
2681 new_streams);
2682 }
deadbeeffaac4972015-11-12 15:33:07 -08002683 }
deadbeefab9b2d12015-10-14 11:33:11 -07002684
Steve Antondcc3c022017-12-22 16:02:54 -08002685 // Find all video rtp streams and create corresponding remote VideoTracks
2686 // and MediaStreams.
2687 if (video_content) {
2688 if (video_content->rejected) {
2689 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2690 } else {
2691 bool default_video_track_needed =
2692 !remote_peer_supports_msid_ &&
2693 RtpTransceiverDirectionHasSend(video_desc->direction());
2694 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2695 default_video_track_needed, video_desc->type(),
2696 new_streams);
2697 }
deadbeeffaac4972015-11-12 15:33:07 -08002698 }
deadbeefab9b2d12015-10-14 11:33:11 -07002699
Steve Antondcc3c022017-12-22 16:02:54 -08002700 // Update the DataChannels with the information from the remote peer.
2701 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002702 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002703 cricket::kMediaProtocolRtpPrefix)) {
2704 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2705 }
deadbeefab9b2d12015-10-14 11:33:11 -07002706 }
deadbeefab9b2d12015-10-14 11:33:11 -07002707
Steve Antondcc3c022017-12-22 16:02:54 -08002708 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002709 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002710 for (size_t i = 0; i < new_streams->count(); ++i) {
2711 MediaStreamInterface* new_stream = new_streams->at(i);
2712 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002713 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002714 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2715 }
deadbeefab9b2d12015-10-14 11:33:11 -07002716
Steve Antondcc3c022017-12-22 16:02:54 -08002717 UpdateEndedRemoteMediaStreams();
2718 }
deadbeefab9b2d12015-10-14 11:33:11 -07002719
Steve Anton8a006912017-12-04 15:25:56 -08002720 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002721}
2722
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002723void PeerConnection::SetAssociatedRemoteStreams(
2724 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2725 const std::vector<std::string>& stream_ids,
2726 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2727 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2728 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2729 for (const std::string& stream_id : stream_ids) {
2730 rtc::scoped_refptr<MediaStreamInterface> stream =
2731 remote_streams_->find(stream_id);
2732 if (!stream) {
2733 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2734 MediaStream::Create(stream_id));
2735 remote_streams_->AddStream(stream);
2736 added_streams->push_back(stream);
2737 }
2738 media_streams.push_back(stream);
2739 }
2740 // Special case: "a=msid" missing, use random stream ID.
2741 if (media_streams.empty() &&
2742 !(remote_description()->description()->msid_signaling() &
2743 cricket::kMsidSignalingMediaSection)) {
2744 if (!missing_msid_default_stream_) {
2745 missing_msid_default_stream_ = MediaStreamProxy::Create(
2746 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2747 added_streams->push_back(missing_msid_default_stream_);
2748 }
2749 media_streams.push_back(missing_msid_default_stream_);
2750 }
2751 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2752 receiver->streams();
2753 // SetStreams() will add/remove the receiver's track to/from the streams. This
2754 // differs from the spec - the spec uses an "addList" and "removeList" to
2755 // update the stream-track relationships in a later step. We do this earlier,
2756 // changing the order of things, but the end-result is the same.
2757 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2758 // instead. https://crbug.com/webrtc/9480
2759 receiver->SetStreams(media_streams);
2760 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2761}
2762
Steve Anton0f5400a2018-07-17 14:25:36 -07002763void PeerConnection::ProcessRemovalOfRemoteTrack(
2764 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2765 transceiver,
2766 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2767 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2768 RTC_DCHECK(transceiver->mid());
2769 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2770 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002771 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002772 transceiver->internal()->receiver_internal()->streams();
2773 // This will remove the remote track from the streams.
2774 transceiver->internal()->receiver_internal()->set_stream_ids({});
2775 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002776 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2777}
2778
2779void PeerConnection::RemoveRemoteStreamsIfEmpty(
2780 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2781 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2782 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2783 // streams, see if the stream was removed by checking if this was the last
2784 // receiver with that stream ID.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002785 for (const auto& remote_stream : remote_streams) {
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002786 if (remote_stream->GetAudioTracks().empty() &&
2787 remote_stream->GetVideoTracks().empty()) {
2788 remote_streams_->RemoveStream(remote_stream);
2789 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002790 }
2791 }
2792}
2793
Steve Antondcc3c022017-12-22 16:02:54 -08002794RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2795 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002796 const SessionDescriptionInterface& new_session,
2797 const SessionDescriptionInterface* old_local_description,
2798 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002799 RTC_DCHECK(IsUnifiedPlan());
2800
Steve Anton7464fca2018-01-19 11:10:37 -08002801 const cricket::ContentGroup* bundle_group = nullptr;
2802 if (new_session.GetType() == SdpType::kOffer) {
2803 auto bundle_group_or_error =
2804 GetEarlyBundleGroup(*new_session.description());
2805 if (!bundle_group_or_error.ok()) {
2806 return bundle_group_or_error.MoveError();
2807 }
2808 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002809 }
Steve Antondcc3c022017-12-22 16:02:54 -08002810
Steve Antondcc3c022017-12-22 16:02:54 -08002811 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002812 for (size_t i = 0; i < new_contents.size(); ++i) {
2813 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002814 cricket::MediaType media_type = new_content.media_description()->type();
Amit Hilbuchae3df542019-01-07 12:13:08 -08002815 mid_generator_.AddKnownId(new_content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002816 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2817 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002818 const cricket::ContentInfo* old_local_content = nullptr;
2819 if (old_local_description &&
2820 i < old_local_description->description()->contents().size()) {
2821 old_local_content =
2822 &old_local_description->description()->contents()[i];
2823 }
2824 const cricket::ContentInfo* old_remote_content = nullptr;
2825 if (old_remote_description &&
2826 i < old_remote_description->description()->contents().size()) {
2827 old_remote_content =
2828 &old_remote_description->description()->contents()[i];
2829 }
Steve Antondcc3c022017-12-22 16:02:54 -08002830 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002831 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2832 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002833 if (!transceiver_or_error.ok()) {
2834 return transceiver_or_error.MoveError();
2835 }
2836 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002837 RTCError error =
2838 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2839 if (!error.ok()) {
2840 return error;
2841 }
2842 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002843 if (GetDataMid() && new_content.name != *GetDataMid()) {
2844 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002845 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2846 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002847 continue;
2848 }
2849 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2850 if (!error.ok()) {
2851 return error;
2852 }
Steve Antondcc3c022017-12-22 16:02:54 -08002853 } else {
2854 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2855 "Unknown section type.");
2856 }
2857 }
2858
2859 return RTCError::OK();
2860}
2861
2862RTCError PeerConnection::UpdateTransceiverChannel(
2863 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2864 transceiver,
2865 const cricket::ContentInfo& content,
2866 const cricket::ContentGroup* bundle_group) {
2867 RTC_DCHECK(IsUnifiedPlan());
2868 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002869 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002870 if (content.rejected) {
2871 if (channel) {
2872 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002873 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002874 }
2875 } else {
2876 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002877 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002878 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002879 } else {
Steve Anton69470252018-02-09 11:43:08 -08002880 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002881 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002882 }
2883 if (!channel) {
2884 LOG_AND_RETURN_ERROR(
2885 RTCErrorType::INTERNAL_ERROR,
2886 "Failed to create channel for mid=" + content.name);
2887 }
2888 transceiver->internal()->SetChannel(channel);
2889 }
2890 }
2891 return RTCError::OK();
2892}
2893
Steve Antonfa2260d2017-12-28 16:38:23 -08002894RTCError PeerConnection::UpdateDataChannel(
2895 cricket::ContentSource source,
2896 const cricket::ContentInfo& content,
2897 const cricket::ContentGroup* bundle_group) {
2898 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002899 // If data channels are disabled, ignore this media section. CreateAnswer
2900 // will take care of rejecting it.
2901 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002902 }
2903 if (content.rejected) {
2904 DestroyDataChannel();
2905 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002906 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002907 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002908 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2909 "Failed to create data channel.");
2910 }
2911 }
2912 if (source == cricket::CS_REMOTE) {
2913 const MediaContentDescription* data_desc = content.media_description();
2914 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2915 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2916 }
2917 }
2918 }
2919 return RTCError::OK();
2920}
2921
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08002922// This method will extract any send encodings that were sent by the remote
2923// connection. This is currently only relevant for Simulcast scenario (where
2924// the number of layers may be communicated by the server).
2925static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
2926 const MediaContentDescription& desc) {
2927 if (!desc.HasSimulcast()) {
2928 return {};
2929 }
2930 std::vector<RtpEncodingParameters> result;
2931 const SimulcastDescription& simulcast = desc.simulcast_description();
2932
2933 // This is a remote description, the parameters we are after should appear
2934 // as receive streams.
2935 for (const auto& alternatives : simulcast.receive_layers()) {
2936 RTC_DCHECK(!alternatives.empty());
2937 // There is currently no way to specify or choose from alternatives.
2938 // We will always use the first alternative, which is the most preferred.
2939 const SimulcastLayer& layer = alternatives[0];
2940 RtpEncodingParameters parameters;
2941 parameters.rid = layer.rid;
2942 parameters.active = !layer.is_paused;
2943 result.push_back(parameters);
2944 }
2945
2946 return result;
2947}
2948
2949static RTCError UpdateSimulcastLayerStatusInSender(
2950 const std::vector<SimulcastLayer>& layers,
2951 RtpSenderInterface* sender) {
2952 RTC_DCHECK(sender);
2953 RtpParameters parameters = sender->GetParameters();
2954
2955 // The simulcast envelope cannot be changed, only the status of the streams.
2956 // So we will iterate over the send encodings rather than the layers.
2957 for (RtpEncodingParameters& encoding : parameters.encodings) {
2958 auto iter = std::find_if(layers.begin(), layers.end(),
2959 [&encoding](const SimulcastLayer& layer) {
2960 return layer.rid == encoding.rid;
2961 });
2962 // A layer that cannot be found may have been removed by the remote party.
2963 encoding.active = iter != layers.end() && !iter->is_paused;
2964 }
2965
2966 return sender->SetParameters(parameters);
2967}
2968
2969static RTCError DisableSimulcastInSender(RtpSenderInterface* sender) {
2970 RTC_DCHECK(sender);
2971 RtpParameters parameters = sender->GetParameters();
2972 if (parameters.encodings.empty()) {
2973 return RTCError::OK();
2974 }
2975
2976 bool first_layer_status = parameters.encodings[0].active;
2977 for (RtpEncodingParameters& encoding : parameters.encodings) {
2978 // TODO(bugs.webrtc.org/10251): Active does not really disable the layer.
2979 // The user might enable it at a later point in time even though it was
2980 // rejected.
2981 encoding.active = false;
2982 }
2983 parameters.encodings[0].active = first_layer_status;
2984
2985 return sender->SetParameters(parameters);
2986}
2987
Steve Antondcc3c022017-12-22 16:02:54 -08002988RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2989PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002990 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002991 size_t mline_index,
2992 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002993 const ContentInfo* old_local_content,
2994 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002995 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002996 // If this is an offer then the m= section might be recycled. If the m=
2997 // section is being recycled (defined as: rejected in the current local or
2998 // remote description and not rejected in new description), dissociate the
2999 // currently associated RtpTransceiver by setting its mid property to null,
3000 // and discard the mapping between the transceiver and its m= section index.
3001 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
3002 old_remote_content)) {
3003 // We want to dissociate the transceiver that has the rejected mid.
3004 const std::string& old_mid =
3005 (old_local_content && old_local_content->rejected)
3006 ? old_local_content->name
3007 : old_remote_content->name;
3008 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08003009 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003010 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
3011 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003012 old_transceiver->internal()->set_mid(absl::nullopt);
3013 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08003014 }
3015 }
3016 const MediaContentDescription* media_desc = content.media_description();
3017 auto transceiver = GetAssociatedTransceiver(content.name);
3018 if (source == cricket::CS_LOCAL) {
3019 // Find the RtpTransceiver that corresponds to this m= section, using the
3020 // mapping between transceivers and m= section indices established when
3021 // creating the offer.
3022 if (!transceiver) {
3023 transceiver = GetTransceiverByMLineIndex(mline_index);
3024 }
3025 if (!transceiver) {
3026 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3027 "Unknown transceiver");
3028 }
3029 } else {
3030 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
3031 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
3032 // of the same type...
3033 if (!transceiver &&
3034 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
3035 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
3036 }
3037 // If no RtpTransceiver was found in the previous step, create one with a
3038 // recvonly direction.
3039 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07003040 RTC_LOG(LS_INFO) << "Adding "
3041 << cricket::MediaTypeToString(media_desc->type())
3042 << " transceiver for MID=" << content.name
3043 << " at i=" << mline_index
3044 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07003045 std::string sender_id = rtc::CreateRandomUuid();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003046 std::vector<RtpEncodingParameters> send_encodings =
3047 GetSendEncodingsFromRemoteDescription(*media_desc);
3048 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
3049 send_encodings);
Steve Anton5f94aa22018-02-01 10:58:30 -08003050 std::string receiver_id;
3051 if (!media_desc->streams().empty()) {
3052 receiver_id = media_desc->streams()[0].id;
3053 } else {
3054 receiver_id = rtc::CreateRandomUuid();
3055 }
3056 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08003057 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08003058 transceiver->internal()->set_direction(
3059 RtpTransceiverDirection::kRecvOnly);
3060 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003061
3062 // Check if the offer indicated simulcast but the answer rejected it.
3063 // This can happen when simulcast is not supported on the remote party.
3064 // This check can be simplified to comparing the number of send encodings,
3065 // but that might break legacy implementation in which simulcast is not
3066 // signaled in the remote description.
3067 if (old_local_content && old_local_content->media_description() &&
3068 old_local_content->media_description()->HasSimulcast() &&
3069 !media_desc->HasSimulcast()) {
3070 RTCError error =
3071 DisableSimulcastInSender(transceiver->internal()->sender());
3072 if (!error.ok()) {
3073 RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
3074 return std::move(error);
3075 }
3076 }
Steve Antondcc3c022017-12-22 16:02:54 -08003077 }
3078 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08003079 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003080 LOG_AND_RETURN_ERROR(
3081 RTCErrorType::INVALID_PARAMETER,
3082 "Transceiver type does not match media description type.");
3083 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08003084 if (media_desc->HasSimulcast()) {
3085 std::vector<SimulcastLayer> layers =
3086 source == cricket::CS_LOCAL
3087 ? media_desc->simulcast_description().send_layers().GetAllLayers()
3088 : media_desc->simulcast_description()
3089 .receive_layers()
3090 .GetAllLayers();
3091 RTCError error = UpdateSimulcastLayerStatusInSender(
3092 layers, transceiver->internal()->sender());
3093 if (!error.ok()) {
3094 RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
3095 return std::move(error);
3096 }
3097 }
Steve Antondcc3c022017-12-22 16:02:54 -08003098 // Associate the found or created RtpTransceiver with the m= section by
3099 // setting the value of the RtpTransceiver's mid property to the MID of the m=
3100 // section, and establish a mapping between the transceiver and the index of
3101 // the m= section.
3102 transceiver->internal()->set_mid(content.name);
3103 transceiver->internal()->set_mline_index(mline_index);
3104 return std::move(transceiver);
3105}
3106
3107rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3108PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
3109 RTC_DCHECK(IsUnifiedPlan());
3110 for (auto transceiver : transceivers_) {
3111 if (transceiver->mid() == mid) {
3112 return transceiver;
3113 }
3114 }
3115 return nullptr;
3116}
3117
3118rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3119PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3120 RTC_DCHECK(IsUnifiedPlan());
3121 for (auto transceiver : transceivers_) {
3122 if (transceiver->internal()->mline_index() == mline_index) {
3123 return transceiver;
3124 }
3125 }
3126 return nullptr;
3127}
3128
3129rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3130PeerConnection::FindAvailableTransceiverToReceive(
3131 cricket::MediaType media_type) const {
3132 RTC_DCHECK(IsUnifiedPlan());
3133 // From JSEP section 5.10 (Applying a Remote Description):
3134 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3135 // the same type that were added to the PeerConnection by addTrack and are not
3136 // associated with any m= section and are not stopped, find the first such
3137 // RtpTransceiver.
3138 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003139 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003140 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3141 !transceiver->stopped()) {
3142 return transceiver;
3143 }
3144 }
3145 return nullptr;
3146}
3147
Steve Antoned10bd92017-12-05 10:52:59 -08003148const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3149 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3150 transceiver,
3151 const SessionDescriptionInterface* sdesc) const {
3152 RTC_DCHECK(transceiver);
3153 RTC_DCHECK(sdesc);
3154 if (IsUnifiedPlan()) {
3155 if (!transceiver->internal()->mid()) {
3156 // This transceiver is not associated with a media section yet.
3157 return nullptr;
3158 }
3159 return sdesc->description()->GetContentByName(
3160 *transceiver->internal()->mid());
3161 } else {
3162 // Plan B only allows at most one audio and one video section, so use the
3163 // first media section of that type.
3164 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003165 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003166 }
3167}
3168
deadbeef46c73892016-11-16 19:42:04 -08003169PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3170 return configuration_;
3171}
3172
deadbeef293e9262017-01-11 12:28:30 -08003173bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3174 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003175 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003176 if (IsClosed()) {
3177 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3178 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3179 }
3180
Qingsi Wanga2d60672018-04-11 16:57:45 -07003181 // According to JSEP, after setLocalDescription, changing the candidate pool
3182 // size is not allowed, and changing the set of ICE servers will not result
3183 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003184 if (local_description() && configuration.ice_candidate_pool_size !=
3185 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003186 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3187 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003188 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003189 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003190
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003191 if (local_description() &&
3192 configuration.use_media_transport != configuration_.use_media_transport) {
3193 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3194 "SetLocalDescription.";
3195 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3196 }
3197
3198 if (remote_description() &&
3199 configuration.use_media_transport != configuration_.use_media_transport) {
3200 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3201 "SetRemoteDescription.";
3202 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3203 }
3204
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003205 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003206 configuration.use_media_transport_for_data_channels !=
3207 configuration_.use_media_transport_for_data_channels) {
3208 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3209 "after calling SetLocalDescription.";
3210 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3211 }
3212
3213 if (remote_description() &&
3214 configuration.use_media_transport_for_data_channels !=
3215 configuration_.use_media_transport_for_data_channels) {
3216 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3217 "after calling SetRemoteDescription.";
3218 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3219 }
3220
3221 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003222 configuration.crypto_options != configuration_.crypto_options) {
3223 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3224 "SetLocalDescription.";
3225 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3226 }
3227
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003228 if (configuration.use_media_transport_for_data_channels ||
3229 configuration.use_media_transport) {
3230 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3231 << "Media transport requires MaxBundle policy.";
3232 }
3233
deadbeef293e9262017-01-11 12:28:30 -08003234 // The simplest (and most future-compatible) way to tell if the config was
3235 // modified in an invalid way is to copy each property we do support
3236 // modifying, then use operator==. There are far more properties we don't
3237 // support modifying than those we do, and more could be added.
3238 RTCConfiguration modified_config = configuration_;
3239 modified_config.servers = configuration.servers;
3240 modified_config.type = configuration.type;
3241 modified_config.ice_candidate_pool_size =
3242 configuration.ice_candidate_pool_size;
3243 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003244 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003245 modified_config.ice_check_interval_strong_connectivity =
3246 configuration.ice_check_interval_strong_connectivity;
3247 modified_config.ice_check_interval_weak_connectivity =
3248 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003249 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3250 modified_config.ice_unwritable_min_checks =
3251 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003252 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003253 modified_config.stun_candidate_keepalive_interval =
3254 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003255 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003256 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003257 modified_config.active_reset_srtp_params =
3258 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003259 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003260 modified_config.use_media_transport_for_data_channels =
3261 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003262 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003263 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003264 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3265 }
3266
Steve Anton038834f2017-07-14 15:59:59 -07003267 // Validate the modified configuration.
3268 RTCError validate_error = ValidateConfiguration(modified_config);
3269 if (!validate_error.ok()) {
3270 return SafeSetError(std::move(validate_error), error);
3271 }
3272
deadbeef293e9262017-01-11 12:28:30 -08003273 // Note that this isn't possible through chromium, since it's an unsigned
3274 // short in WebIDL.
3275 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003276 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003277 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3278 }
3279
3280 // Parse ICE servers before hopping to network thread.
3281 cricket::ServerAddresses stun_servers;
3282 std::vector<cricket::RelayServerConfig> turn_servers;
3283 RTCErrorType parse_error =
3284 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3285 if (parse_error != RTCErrorType::NONE) {
3286 return SafeSetError(parse_error, error);
3287 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003288 // Note if STUN or TURN servers were supplied.
3289 if (!stun_servers.empty()) {
3290 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3291 }
3292 if (!turn_servers.empty()) {
3293 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3294 }
deadbeef293e9262017-01-11 12:28:30 -08003295
3296 // In theory this shouldn't fail.
3297 if (!network_thread()->Invoke<bool>(
3298 RTC_FROM_HERE,
3299 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3300 stun_servers, turn_servers, modified_config.type,
3301 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003302 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003303 modified_config.turn_customizer,
3304 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003305 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003306 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3307 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003308
deadbeefd1a38b52016-12-10 13:15:33 -08003309 // As described in JSEP, calling setConfiguration with new ICE servers or
3310 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3311 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003312 if (modified_config.servers != configuration_.servers ||
3313 modified_config.type != configuration_.type ||
3314 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003315 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003316 }
skvladd1f5fda2017-02-03 16:54:05 -08003317
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003318 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003319 transport_controller_->SetMediaTransportSettings(
3320 modified_config.use_media_transport,
3321 modified_config.use_media_transport_for_data_channels);
skvladd1f5fda2017-02-03 16:54:05 -08003322
Zhi Huangb57e1692018-06-12 11:41:11 -07003323 if (configuration_.active_reset_srtp_params !=
3324 modified_config.active_reset_srtp_params) {
3325 transport_controller_->SetActiveResetSrtpParams(
3326 modified_config.active_reset_srtp_params);
3327 }
3328
deadbeef293e9262017-01-11 12:28:30 -08003329 configuration_ = modified_config;
3330 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003331}
3332
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003333bool PeerConnection::AddIceCandidate(
3334 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003335 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003336 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003337 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003338 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003339 return false;
3340 }
Steve Antond25da372017-11-06 14:50:29 -08003341
3342 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003343 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003344 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003345 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003346 return false;
3347 }
3348
3349 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003350 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003351 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003352 return false;
3353 }
3354
3355 bool valid = false;
3356 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3357 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003358 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003359 return false;
3360 }
3361
3362 // Add this candidate to the remote session description.
3363 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003364 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003365 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003366 return false;
3367 }
3368
3369 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003370 bool result = UseCandidate(ice_candidate);
3371 if (result) {
3372 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3373 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3374 } else {
3375 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3376 }
3377 return result;
Steve Antond25da372017-11-06 14:50:29 -08003378 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003379 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003380 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003381 return true;
3382 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003383}
3384
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003385bool PeerConnection::RemoveIceCandidates(
3386 const std::vector<cricket::Candidate>& candidates) {
3387 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003388 if (IsClosed()) {
3389 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3390 return false;
3391 }
3392
Steve Antond25da372017-11-06 14:50:29 -08003393 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003394 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3395 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003396 return false;
3397 }
3398
3399 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003400 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003401 return false;
3402 }
3403
3404 size_t number_removed =
3405 mutable_remote_description()->RemoveCandidates(candidates);
3406 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003407 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003408 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003409 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003410 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003411 }
3412
3413 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003414 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3415 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003416 RTC_LOG(LS_ERROR)
3417 << "RemoveIceCandidates: Error when removing remote candidates: "
3418 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003419 }
3420 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003421}
3422
Niels Möller0c4f7be2018-05-07 14:01:37 +02003423RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003424 if (!worker_thread()->IsCurrent()) {
3425 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003426 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003427 }
3428
Niels Möller0c4f7be2018-05-07 14:01:37 +02003429 const bool has_min = bitrate.min_bitrate_bps.has_value();
3430 const bool has_start = bitrate.start_bitrate_bps.has_value();
3431 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003432 if (has_min && *bitrate.min_bitrate_bps < 0) {
3433 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3434 "min_bitrate_bps <= 0");
3435 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003436 if (has_start) {
3437 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003438 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003439 "start_bitrate_bps < min_bitrate_bps");
3440 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003441 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3442 "curent_bitrate_bps < 0");
3443 }
3444 }
3445 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003446 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003447 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003448 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003449 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3450 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3451 "max_bitrate_bps < min_bitrate_bps");
3452 } else if (*bitrate.max_bitrate_bps < 0) {
3453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3454 "max_bitrate_bps < 0");
3455 }
3456 }
3457
zstein4b979802017-06-02 14:37:37 -07003458 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003459 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003460
3461 return RTCError::OK();
3462}
3463
Alex Narest78609d52017-10-20 10:37:47 +02003464void PeerConnection::SetBitrateAllocationStrategy(
3465 std::unique_ptr<rtc::BitrateAllocationStrategy>
3466 bitrate_allocation_strategy) {
3467 rtc::Thread* worker_thread = factory_->worker_thread();
3468 if (!worker_thread->IsCurrent()) {
3469 rtc::BitrateAllocationStrategy* strategy_raw =
3470 bitrate_allocation_strategy.release();
3471 auto functor = [this, strategy_raw]() {
3472 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003473 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003474 };
3475 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3476 return;
3477 }
3478 RTC_DCHECK(call_.get());
3479 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3480}
3481
henrika5f6bf242017-11-01 11:06:56 +01003482void PeerConnection::SetAudioPlayout(bool playout) {
3483 if (!worker_thread()->IsCurrent()) {
3484 worker_thread()->Invoke<void>(
3485 RTC_FROM_HERE,
3486 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3487 return;
3488 }
3489 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003490 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003491 audio_state->SetPlayout(playout);
3492}
3493
3494void PeerConnection::SetAudioRecording(bool recording) {
3495 if (!worker_thread()->IsCurrent()) {
3496 worker_thread()->Invoke<void>(
3497 RTC_FROM_HERE,
3498 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3499 return;
3500 }
3501 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003502 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003503 audio_state->SetRecording(recording);
3504}
3505
Steve Anton8c0f7a72017-10-03 10:03:10 -07003506std::unique_ptr<rtc::SSLCertificate>
3507PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003508 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3509 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003510 return nullptr;
3511 }
Steve Antonf25303e2018-10-16 15:23:31 -07003512 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003513}
3514
Zhi Huang70b820f2018-01-27 14:16:15 -08003515std::unique_ptr<rtc::SSLCertChain>
3516PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003517 auto audio_transceiver = GetFirstAudioTransceiver();
3518 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003519 return nullptr;
3520 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003521 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003522 audio_transceiver->internal()->channel()->transport_name());
3523}
3524
3525rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3526PeerConnection::GetFirstAudioTransceiver() const {
3527 for (auto transceiver : transceivers_) {
3528 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3529 return transceiver;
3530 }
3531 }
3532 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003533}
3534
ivoc14d5dbe2016-07-04 07:06:55 -07003535bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3536 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003537 // TODO(eladalon): It would be better to not allow negative values into PC.
3538 const size_t max_size = (max_size_bytes < 0)
3539 ? RtcEventLog::kUnlimitedOutput
3540 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003541 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3542 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3543 output_period_ms = 5000;
3544 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003545 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003546 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003547 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003548}
3549
Bjorn Tereliusde939432017-11-20 17:38:14 +01003550bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3551 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003552 // TODO(eladalon): In C++14, this can be done with a lambda.
3553 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003554 bool operator()() {
3555 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3556 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003557 PeerConnection* const pc;
3558 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003559 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003560 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003561 return worker_thread()->Invoke<bool>(
3562 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003563}
3564
3565void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003566 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003567 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3568}
3569
Harald Alvestrandad88c882018-11-28 16:47:46 +01003570rtc::scoped_refptr<DtlsTransportInterface>
3571PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3572 return transport_controller_->LookupDtlsTransportByMid(mid);
3573}
3574
Harald Alvestrand4a7b3ac2019-01-17 10:39:40 +01003575rtc::scoped_refptr<DtlsTransport>
3576PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
3577 return transport_controller_->LookupDtlsTransportByMid(mid);
3578}
3579
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003580const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003581 return pending_local_description_ ? pending_local_description_.get()
3582 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003583}
3584
3585const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003586 return pending_remote_description_ ? pending_remote_description_.get()
3587 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003588}
3589
deadbeeffe4a8a42016-12-20 17:56:17 -08003590const SessionDescriptionInterface* PeerConnection::current_local_description()
3591 const {
Steve Anton75737c02017-11-06 10:37:17 -08003592 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003593}
3594
3595const SessionDescriptionInterface* PeerConnection::current_remote_description()
3596 const {
Steve Anton75737c02017-11-06 10:37:17 -08003597 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003598}
3599
3600const SessionDescriptionInterface* PeerConnection::pending_local_description()
3601 const {
Steve Anton75737c02017-11-06 10:37:17 -08003602 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003603}
3604
3605const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3606 const {
Steve Anton75737c02017-11-06 10:37:17 -08003607 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003608}
3609
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003610void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003611 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003612 // Update stats here so that we have the most recent stats for tracks and
3613 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003614 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003615
Steve Anton75737c02017-11-06 10:37:17 -08003616 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003617 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003618
Mirko Bonadei739baf02019-01-27 17:29:42 +01003619 for (const auto& transceiver : transceivers_) {
Steve Anton8af21862017-12-15 11:20:13 -08003620 transceiver->Stop();
3621 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003622
3623 // Ensure that all asynchronous stats requests are completed before destroying
3624 // the transport controller below.
3625 if (stats_collector_) {
3626 stats_collector_->WaitForPendingRequest();
3627 }
3628
3629 // Don't destroy BaseChannels until after stats has been cleaned up so that
3630 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003631 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003632
Qingsi Wang93a84392018-01-30 17:13:09 -08003633 // The event log is used in the transport controller, which must be outlived
3634 // by the former. CreateOffer by the peer connection is implemented
3635 // asynchronously and if the peer connection is closed without resetting the
3636 // WebRTC session description factory, the session description factory would
3637 // call the transport controller.
3638 webrtc_session_desc_factory_.reset();
3639 transport_controller_.reset();
3640
deadbeef42a42632017-03-10 15:18:00 -08003641 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003642 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3643 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003644
Steve Anton978b8762017-09-29 12:15:02 -07003645 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003646 call_.reset();
3647 // The event log must outlive call (and any other object that uses it).
3648 event_log_.reset();
3649 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003650 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003651 // The .h file says that observer can be discarded after close() returns.
3652 // Make sure this is true.
3653 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003654}
3655
Steve Antonad182762018-09-05 20:22:40 +00003656void PeerConnection::OnMessage(rtc::Message* msg) {
3657 switch (msg->message_id) {
3658 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3659 SetSessionDescriptionMsg* param =
3660 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3661 param->observer->OnSuccess();
3662 delete param;
3663 break;
3664 }
3665 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3666 SetSessionDescriptionMsg* param =
3667 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3668 param->observer->OnFailure(std::move(param->error));
3669 delete param;
3670 break;
3671 }
3672 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3673 CreateSessionDescriptionMsg* param =
3674 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3675 param->observer->OnFailure(std::move(param->error));
3676 delete param;
3677 break;
3678 }
3679 case MSG_GETSTATS: {
3680 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3681 StatsReports reports;
3682 stats_->GetStats(param->track, &reports);
3683 param->observer->OnComplete(reports);
3684 delete param;
3685 break;
3686 }
3687 case MSG_FREE_DATACHANNELS: {
3688 sctp_data_channels_to_free_.clear();
3689 break;
3690 }
3691 case MSG_REPORT_USAGE_PATTERN: {
3692 ReportUsagePattern();
3693 break;
3694 }
3695 default:
3696 RTC_NOTREACHED() << "Not implemented";
3697 break;
3698 }
3699}
3700
Steve Antonafb0bb72018-02-20 11:35:37 -08003701cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3702 RTC_DCHECK(!IsUnifiedPlan());
3703 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3704 GetAudioTransceiver()->internal()->channel());
3705 if (voice_channel) {
3706 return voice_channel->media_channel();
3707 } else {
3708 return nullptr;
3709 }
3710}
3711
3712cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3713 RTC_DCHECK(!IsUnifiedPlan());
3714 auto* video_channel = static_cast<cricket::VideoChannel*>(
3715 GetVideoTransceiver()->internal()->channel());
3716 if (video_channel) {
3717 return video_channel->media_channel();
3718 } else {
3719 return nullptr;
3720 }
3721}
3722
Steve Anton4171afb2017-11-20 10:20:22 -08003723void PeerConnection::CreateAudioReceiver(
3724 MediaStreamInterface* stream,
3725 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003726 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3727 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003728 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3729 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003730 auto* audio_receiver = new AudioRtpReceiver(
3731 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003732 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003733 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3734 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3735 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003736 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003737 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003738 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003739}
3740
Steve Anton4171afb2017-11-20 10:20:22 -08003741void PeerConnection::CreateVideoReceiver(
3742 MediaStreamInterface* stream,
3743 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003744 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3745 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003746 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3747 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003748 auto* video_receiver = new VideoRtpReceiver(
3749 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003750 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003751 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3752 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3753 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003754 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003755 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003756 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003757}
3758
deadbeef70ab1a12015-09-28 16:53:55 -07003759// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3760// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003761rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003762 const RtpSenderInfo& remote_sender_info) {
3763 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3764 if (!receiver) {
3765 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3766 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003767 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003768 }
Steve Anton4171afb2017-11-20 10:20:22 -08003769 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3770 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3771 } else {
3772 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3773 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003774 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003775}
3776
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003777void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3778 MediaStreamInterface* stream) {
3779 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003780 RTC_DCHECK(track);
3781 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003782 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003783 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003784 // We already have a sender for this track, so just change the stream_id
3785 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003786 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003787 return;
3788 }
3789
3790 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003791 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003792 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003793 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003794 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003795 // If the sender has already been configured in SDP, we call SetSsrc,
3796 // which will connect the sender to the underlying transport. This can
3797 // occur if a local session description that contains the ID of the sender
3798 // is set before AddStream is called. It can also occur if the local
3799 // session description is not changed and RemoveStream is called, and
3800 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003801 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003802 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003803 if (sender_info) {
3804 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003805 }
3806}
3807
3808// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3809// indefinitely, when we have unified plan SDP.
3810void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3811 MediaStreamInterface* stream) {
3812 RTC_DCHECK(!IsClosed());
3813 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003814 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003815 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3816 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003817 return;
3818 }
Steve Anton4171afb2017-11-20 10:20:22 -08003819 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003820}
3821
3822void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3823 MediaStreamInterface* stream) {
3824 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003825 RTC_DCHECK(track);
3826 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003827 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003828 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003829 // We already have a sender for this track, so just change the stream_id
3830 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003831 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003832 return;
3833 }
3834
3835 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003836 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003837 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003838 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003839 GetVideoTransceiver()->internal()->AddSender(new_sender);
3840 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003841 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003842 if (sender_info) {
3843 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003844 }
3845}
3846
3847void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3848 MediaStreamInterface* stream) {
3849 RTC_DCHECK(!IsClosed());
3850 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003851 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003852 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3853 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003854 return;
3855 }
Steve Anton4171afb2017-11-20 10:20:22 -08003856 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003857}
3858
Steve Antonba818672017-11-06 10:21:57 -08003859void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003860 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003861 if (ice_connection_state_ == new_state) {
3862 return;
3863 }
3864
deadbeefcbecd352015-09-23 11:50:27 -07003865 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003866 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003867 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003868 return;
3869 }
Steve Antonba818672017-11-06 10:21:57 -08003870
Mirko Bonadei675513b2017-11-09 11:09:25 +01003871 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3872 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003873 RTC_DCHECK(ice_connection_state_ !=
3874 PeerConnectionInterface::kIceConnectionClosed);
3875
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003876 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003877 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003878}
3879
Alex Loiko9289eda2018-11-23 16:18:59 +00003880void PeerConnection::SetStandardizedIceConnectionState(
3881 PeerConnectionInterface::IceConnectionState new_state) {
3882 RTC_DCHECK(signaling_thread()->IsCurrent());
3883 if (standardized_ice_connection_state_ == new_state)
3884 return;
3885 if (IsClosed())
3886 return;
3887 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003888 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003889}
3890
Jonas Olsson635474e2018-10-18 15:58:17 +02003891void PeerConnection::SetConnectionState(
3892 PeerConnectionInterface::PeerConnectionState new_state) {
3893 RTC_DCHECK(signaling_thread()->IsCurrent());
3894 if (connection_state_ == new_state)
3895 return;
3896 if (IsClosed())
3897 return;
3898 connection_state_ = new_state;
3899 Observer()->OnConnectionChange(new_state);
3900}
3901
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003902void PeerConnection::OnIceGatheringChange(
3903 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003904 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003905 if (IsClosed()) {
3906 return;
3907 }
3908 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003909 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003910}
3911
jbauch81bf7b02017-03-25 08:31:12 -07003912void PeerConnection::OnIceCandidate(
3913 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003914 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003915 if (IsClosed()) {
3916 return;
3917 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003918 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003919 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3920 candidate->candidate().address().IsPrivateIP()) {
3921 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3922 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003923 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003924}
3925
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003926void PeerConnection::OnIceCandidatesRemoved(
3927 const std::vector<cricket::Candidate>& candidates) {
3928 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003929 if (IsClosed()) {
3930 return;
3931 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003932 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003933}
3934
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003935void PeerConnection::ChangeSignalingState(
3936 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003937 RTC_DCHECK(signaling_thread()->IsCurrent());
3938 if (signaling_state_ == signaling_state) {
3939 return;
3940 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003941 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3942 << GetSignalingStateString(signaling_state_)
3943 << " New state: "
3944 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003945 signaling_state_ = signaling_state;
3946 if (signaling_state == kClosed) {
3947 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003948 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003949 standardized_ice_connection_state_ =
3950 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003951 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3952 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003953 if (ice_gathering_state_ != kIceGatheringComplete) {
3954 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003955 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003956 }
3957 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003958 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003959}
3960
deadbeefeb459812015-12-15 19:24:43 -08003961void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3962 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003963 if (IsClosed()) {
3964 return;
3965 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003966 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003967 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003968}
3969
deadbeefeb459812015-12-15 19:24:43 -08003970void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3971 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003972 if (IsClosed()) {
3973 return;
3974 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003975 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003976 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003977}
3978
3979void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3980 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003981 if (IsClosed()) {
3982 return;
3983 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003984 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003985 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003986}
3987
3988void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3989 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003990 if (IsClosed()) {
3991 return;
3992 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003993 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003994 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003995}
3996
Henrik Boström31638672017-11-23 17:48:32 +01003997void PeerConnection::PostSetSessionDescriptionSuccess(
3998 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003999 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4000 signaling_thread()->Post(RTC_FROM_HERE, this,
4001 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01004002}
4003
deadbeefab9b2d12015-10-14 11:33:11 -07004004void PeerConnection::PostSetSessionDescriptionFailure(
4005 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00004006 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004007 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004008 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
4009 msg->error = std::move(error);
4010 signaling_thread()->Post(RTC_FROM_HERE, this,
4011 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004012}
4013
4014void PeerConnection::PostCreateSessionDescriptionFailure(
4015 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01004016 RTCError error) {
4017 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00004018 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
4019 msg->error = std::move(error);
4020 signaling_thread()->Post(RTC_FROM_HERE, this,
4021 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07004022}
4023
zhihuang1c378ed2017-08-17 14:10:50 -07004024void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08004025 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07004026 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08004027 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004028
Steve Antondcc3c022017-12-22 16:02:54 -08004029 if (IsUnifiedPlan()) {
4030 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
4031 } else {
4032 GetOptionsForPlanBOffer(offer_answer_options, session_options);
4033 }
4034
Steve Antonfa2260d2017-12-28 16:38:23 -08004035 // Intentionally unset the data channel type for RTP data channel with the
4036 // second condition. Otherwise the RTP data channels would be successfully
4037 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
4038 // when building with chromium. We want to leave RTP data channels broken, so
4039 // people won't try to use them.
4040 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4041 session_options->data_channel_type = data_channel_type();
4042 }
4043
Steve Antondcc3c022017-12-22 16:02:54 -08004044 // Apply ICE restart flag and renomination flag.
4045 for (auto& options : session_options->media_description_options) {
4046 options.transport_options.ice_restart = offer_answer_options.ice_restart;
4047 options.transport_options.enable_ice_renomination =
4048 configuration_.enable_ice_renomination;
4049 }
4050
4051 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004052 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004053 session_options->pooled_ice_credentials =
4054 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4055 RTC_FROM_HERE,
4056 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4057 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01004058 session_options->offer_extmap_allow_mixed =
4059 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08004060}
4061
4062void PeerConnection::GetOptionsForPlanBOffer(
4063 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4064 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004065 // Figure out transceiver directional preferences.
4066 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4067 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4068
4069 // By default, generate sendrecv/recvonly m= sections.
4070 bool recv_audio = true;
4071 bool recv_video = true;
4072
4073 // By default, only offer a new m= section if we have media to send with it.
4074 bool offer_new_audio_description = send_audio;
4075 bool offer_new_video_description = send_video;
4076 bool offer_new_data_description = HasDataChannels();
4077
4078 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004079 if (offer_answer_options.offer_to_receive_audio !=
4080 RTCOfferAnswerOptions::kUndefined) {
4081 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004082 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004083 offer_new_audio_description ||
4084 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004085 }
Steve Antondcc3c022017-12-22 16:02:54 -08004086 if (offer_answer_options.offer_to_receive_video !=
4087 RTCOfferAnswerOptions::kUndefined) {
4088 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004089 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08004090 offer_new_video_description ||
4091 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004092 }
4093
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004094 absl::optional<size_t> audio_index;
4095 absl::optional<size_t> video_index;
4096 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07004097 // If a current description exists, generate m= sections in the same order,
4098 // using the first audio/video/data section that appears and rejecting
4099 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08004100 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07004101 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08004102 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08004103 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4104 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4105 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07004106 }
4107
zhihuang1c378ed2017-08-17 14:10:50 -07004108 // Add audio/video/data m= sections to the end if needed.
4109 if (!audio_index && offer_new_audio_description) {
4110 session_options->media_description_options.push_back(
4111 cricket::MediaDescriptionOptions(
4112 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08004113 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4114 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004115 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004116 }
zhihuang1c378ed2017-08-17 14:10:50 -07004117 if (!video_index && offer_new_video_description) {
4118 session_options->media_description_options.push_back(
4119 cricket::MediaDescriptionOptions(
4120 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004121 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4122 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004123 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004124 }
zhihuang1c378ed2017-08-17 14:10:50 -07004125 if (!data_index && offer_new_data_description) {
4126 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004127 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004128 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004129 }
4130
4131 cricket::MediaDescriptionOptions* audio_media_description_options =
4132 !audio_index ? nullptr
4133 : &session_options->media_description_options[*audio_index];
4134 cricket::MediaDescriptionOptions* video_media_description_options =
4135 !video_index ? nullptr
4136 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004137
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004138 AddPlanBRtpSenderOptions(GetSendersInternal(),
4139 audio_media_description_options,
4140 video_media_description_options,
4141 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004142}
4143
Steve Antondcc3c022017-12-22 16:02:54 -08004144static cricket::MediaDescriptionOptions
4145GetMediaDescriptionOptionsForTransceiver(
4146 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4147 transceiver,
4148 const std::string& mid) {
4149 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004150 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004151 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004152 // This behavior is specified in JSEP. The gist is that:
4153 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4154 // sendrecv.
4155 // 2. If the MSID is included, then it must be included in any subsequent
4156 // offer/answer exactly the same until the RtpTransceiver is stopped.
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004157 if (transceiver->stopped() ||
4158 (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
4159 !transceiver->internal()->has_ever_been_used_to_send())) {
4160 return media_description_options;
Steve Anton5f94aa22018-02-01 10:58:30 -08004161 }
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004162
4163 cricket::SenderOptions sender_options;
4164 sender_options.track_id = transceiver->sender()->id();
4165 sender_options.stream_ids = transceiver->sender()->stream_ids();
4166
4167 // The following sets up RIDs and Simulcast.
4168 // RIDs are included if Simulcast is requested or if any RID was specified.
4169 RtpParameters send_parameters = transceiver->sender()->GetParameters();
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004170 bool has_rids = std::any_of(send_parameters.encodings.begin(),
4171 send_parameters.encodings.end(),
4172 [](const RtpEncodingParameters& encoding) {
4173 return !encoding.rid.empty();
4174 });
4175
Amit Hilbuchb7446ed2019-01-28 12:25:25 -08004176 std::vector<RidDescription> send_rids;
4177 SimulcastLayerList send_layers;
4178 for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
4179 if (encoding.rid.empty()) {
4180 continue;
4181 }
4182 send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
4183 send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
4184 }
4185
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004186 if (has_rids) {
4187 sender_options.rids = send_rids;
4188 }
4189
4190 sender_options.simulcast_layers = send_layers;
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08004191 // When RIDs are configured, we must set num_sim_layers to 0 to.
4192 // Otherwise, num_sim_layers must be 1 because either there is no
4193 // simulcast, or simulcast is acheived by munging the SDP.
4194 sender_options.num_sim_layers = has_rids ? 0 : 1;
4195 media_description_options.sender_options.push_back(sender_options);
4196
Steve Antondcc3c022017-12-22 16:02:54 -08004197 return media_description_options;
4198}
4199
Steve Anton5c72e712018-12-10 14:25:30 -08004200// Returns the ContentInfo at mline index |i|, or null if none exists.
4201static const ContentInfo* GetContentByIndex(
4202 const SessionDescriptionInterface* sdesc,
4203 size_t i) {
4204 if (!sdesc) {
4205 return nullptr;
4206 }
4207 const ContentInfos& contents = sdesc->description()->contents();
4208 return (i < contents.size() ? &contents[i] : nullptr);
4209}
4210
Steve Antondcc3c022017-12-22 16:02:54 -08004211void PeerConnection::GetOptionsForUnifiedPlanOffer(
4212 const RTCOfferAnswerOptions& offer_answer_options,
4213 cricket::MediaSessionOptions* session_options) {
4214 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4215 // Offers) and 5.2.2 (Subsequent Offers).
4216 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4217 const ContentInfos& local_contents =
4218 (local_description() ? local_description()->description()->contents()
4219 : ContentInfos());
4220 const ContentInfos& remote_contents =
4221 (remote_description() ? remote_description()->description()->contents()
4222 : ContentInfos());
4223 // The mline indices that can be recycled. New transceivers should reuse these
4224 // slots first.
4225 std::queue<size_t> recycleable_mline_indices;
Steve Antondcc3c022017-12-22 16:02:54 -08004226 // First, go through each media section that exists in either the local or
4227 // remote description and generate a media section in this offer for the
4228 // associated transceiver. If a media section can be recycled, generate a
4229 // default, rejected media section here that can be later overwritten.
4230 for (size_t i = 0;
4231 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4232 // Either |local_content| or |remote_content| is non-null.
4233 const ContentInfo* local_content =
4234 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004235 const ContentInfo* current_local_content =
4236 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004237 const ContentInfo* remote_content =
4238 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004239 const ContentInfo* current_remote_content =
4240 GetContentByIndex(current_remote_description(), i);
4241 bool had_been_rejected =
4242 (current_local_content && current_local_content->rejected) ||
4243 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004244 const std::string& mid =
4245 (local_content ? local_content->name : remote_content->name);
4246 cricket::MediaType media_type =
4247 (local_content ? local_content->media_description()->type()
4248 : remote_content->media_description()->type());
4249 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4250 media_type == cricket::MEDIA_TYPE_VIDEO) {
4251 auto transceiver = GetAssociatedTransceiver(mid);
4252 RTC_CHECK(transceiver);
4253 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004254 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004255 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004256 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004257 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4258 RtpTransceiverDirection::kInactive,
4259 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004260 recycleable_mline_indices.push(i);
4261 } else {
4262 session_options->media_description_options.push_back(
4263 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4264 // CreateOffer shouldn't really cause any state changes in
4265 // PeerConnection, but we need a way to match new transceivers to new
4266 // media sections in SetLocalDescription and JSEP specifies this is done
4267 // by recording the index of the media section generated for the
4268 // transceiver in the offer.
4269 transceiver->internal()->set_mline_index(i);
4270 }
4271 } else {
4272 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004273 RTC_CHECK(GetDataMid());
4274 if (had_been_rejected || mid != *GetDataMid()) {
4275 session_options->media_description_options.push_back(
4276 GetMediaDescriptionOptionsForRejectedData(mid));
4277 } else {
4278 session_options->media_description_options.push_back(
4279 GetMediaDescriptionOptionsForActiveData(mid));
4280 }
Steve Antondcc3c022017-12-22 16:02:54 -08004281 }
4282 }
Amit Hilbuchae3df542019-01-07 12:13:08 -08004283
Steve Antondcc3c022017-12-22 16:02:54 -08004284 // Next, look for transceivers that are newly added (that is, are not stopped
4285 // and not associated). Reuse media sections marked as recyclable first,
4286 // otherwise append to the end of the offer. New media sections should be
4287 // added in the order they were added to the PeerConnection.
Mirko Bonadei739baf02019-01-27 17:29:42 +01004288 for (const auto& transceiver : transceivers_) {
Steve Antondcc3c022017-12-22 16:02:54 -08004289 if (transceiver->mid() || transceiver->stopped()) {
4290 continue;
4291 }
4292 size_t mline_index;
4293 if (!recycleable_mline_indices.empty()) {
4294 mline_index = recycleable_mline_indices.front();
4295 recycleable_mline_indices.pop();
4296 session_options->media_description_options[mline_index] =
4297 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004298 mid_generator_());
Steve Antondcc3c022017-12-22 16:02:54 -08004299 } else {
4300 mline_index = session_options->media_description_options.size();
4301 session_options->media_description_options.push_back(
4302 GetMediaDescriptionOptionsForTransceiver(transceiver,
Amit Hilbuchae3df542019-01-07 12:13:08 -08004303 mid_generator_()));
Steve Antondcc3c022017-12-22 16:02:54 -08004304 }
4305 // See comment above for why CreateOffer changes the transceiver's state.
4306 transceiver->internal()->set_mline_index(mline_index);
4307 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004308 // Lastly, add a m-section if we have local data channels and an m section
4309 // does not already exist.
4310 if (!GetDataMid() && HasDataChannels()) {
4311 session_options->media_description_options.push_back(
Amit Hilbuchae3df542019-01-07 12:13:08 -08004312 GetMediaDescriptionOptionsForActiveData(mid_generator_()));
Steve Antonfa2260d2017-12-28 16:38:23 -08004313 }
Steve Antondcc3c022017-12-22 16:02:54 -08004314}
4315
4316void PeerConnection::GetOptionsForAnswer(
4317 const RTCOfferAnswerOptions& offer_answer_options,
4318 cricket::MediaSessionOptions* session_options) {
4319 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4320
4321 if (IsUnifiedPlan()) {
4322 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4323 } else {
4324 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4325 }
4326
Steve Antonfa2260d2017-12-28 16:38:23 -08004327 // Intentionally unset the data channel type for RTP data channel. Otherwise
4328 // the RTP data channels would be successfully negotiated by default and the
4329 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4330 // We want to leave RTP data channels broken, so people won't try to use them.
4331 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4332 session_options->data_channel_type = data_channel_type();
4333 }
4334
Steve Antondcc3c022017-12-22 16:02:54 -08004335 // Apply ICE renomination flag.
4336 for (auto& options : session_options->media_description_options) {
4337 options.transport_options.enable_ice_renomination =
4338 configuration_.enable_ice_renomination;
4339 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004340
4341 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004342 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004343 session_options->pooled_ice_credentials =
4344 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4345 RTC_FROM_HERE,
4346 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4347 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004348}
4349
Steve Antondcc3c022017-12-22 16:02:54 -08004350void PeerConnection::GetOptionsForPlanBAnswer(
4351 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004352 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004353 // Figure out transceiver directional preferences.
4354 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4355 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4356
4357 // By default, generate sendrecv/recvonly m= sections. The direction is also
4358 // restricted by the direction in the offer.
4359 bool recv_audio = true;
4360 bool recv_video = true;
4361
4362 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004363 if (offer_answer_options.offer_to_receive_audio !=
4364 RTCOfferAnswerOptions::kUndefined) {
4365 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004366 }
Steve Antondcc3c022017-12-22 16:02:54 -08004367 if (offer_answer_options.offer_to_receive_video !=
4368 RTCOfferAnswerOptions::kUndefined) {
4369 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004370 }
4371
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004372 absl::optional<size_t> audio_index;
4373 absl::optional<size_t> video_index;
4374 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004375
4376 // Generate m= sections that match those in the offer.
4377 // Note that mediasession.cc will handle intersection our preferred
4378 // direction with the offered direction.
4379 GenerateMediaDescriptionOptions(
4380 remote_description(),
4381 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4382 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4383 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004384
4385 cricket::MediaDescriptionOptions* audio_media_description_options =
4386 !audio_index ? nullptr
4387 : &session_options->media_description_options[*audio_index];
4388 cricket::MediaDescriptionOptions* video_media_description_options =
4389 !video_index ? nullptr
4390 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004391
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004392 AddPlanBRtpSenderOptions(GetSendersInternal(),
4393 audio_media_description_options,
4394 video_media_description_options,
4395 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004396}
zhihuangaf388472016-11-02 16:49:48 -07004397
Steve Antondcc3c022017-12-22 16:02:54 -08004398void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4399 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4400 cricket::MediaSessionOptions* session_options) {
4401 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4402 // Answers) and 5.3.2 (Subsequent Answers).
4403 RTC_DCHECK(remote_description());
4404 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4405 for (const ContentInfo& content :
4406 remote_description()->description()->contents()) {
4407 cricket::MediaType media_type = content.media_description()->type();
4408 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4409 media_type == cricket::MEDIA_TYPE_VIDEO) {
4410 auto transceiver = GetAssociatedTransceiver(content.name);
4411 RTC_CHECK(transceiver);
4412 session_options->media_description_options.push_back(
4413 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4414 } else {
4415 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004416 // Reject all data sections if data channels are disabled.
4417 // Reject a data section if it has already been rejected.
4418 // Reject all data sections except for the first one.
4419 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4420 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004421 session_options->media_description_options.push_back(
4422 GetMediaDescriptionOptionsForRejectedData(content.name));
4423 } else {
4424 session_options->media_description_options.push_back(
4425 GetMediaDescriptionOptionsForActiveData(content.name));
4426 }
Steve Antondcc3c022017-12-22 16:02:54 -08004427 }
4428 }
htaa2a49d92016-03-04 02:51:39 -08004429}
4430
zhihuang1c378ed2017-08-17 14:10:50 -07004431void PeerConnection::GenerateMediaDescriptionOptions(
4432 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004433 RtpTransceiverDirection audio_direction,
4434 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004435 absl::optional<size_t>* audio_index,
4436 absl::optional<size_t>* video_index,
4437 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004438 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004439 for (const cricket::ContentInfo& content :
4440 session_desc->description()->contents()) {
4441 if (IsAudioContent(&content)) {
4442 // If we already have an audio m= section, reject this extra one.
4443 if (*audio_index) {
4444 session_options->media_description_options.push_back(
4445 cricket::MediaDescriptionOptions(
4446 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004447 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004448 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004449 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004450 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004451 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4452 content.name, audio_direction,
4453 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004454 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004455 }
4456 } else if (IsVideoContent(&content)) {
4457 // If we already have an video m= section, reject this extra one.
4458 if (*video_index) {
4459 session_options->media_description_options.push_back(
4460 cricket::MediaDescriptionOptions(
4461 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004462 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004463 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004464 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004465 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004466 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4467 content.name, video_direction,
4468 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004469 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004470 }
4471 } else {
4472 RTC_DCHECK(IsDataContent(&content));
4473 // If we already have an data m= section, reject this extra one.
4474 if (*data_index) {
4475 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004476 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004477 } else {
4478 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004479 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004480 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004481 }
4482 }
htaa2a49d92016-03-04 02:51:39 -08004483 }
deadbeefab9b2d12015-10-14 11:33:11 -07004484}
4485
Steve Antonfa2260d2017-12-28 16:38:23 -08004486cricket::MediaDescriptionOptions
4487PeerConnection::GetMediaDescriptionOptionsForActiveData(
4488 const std::string& mid) const {
4489 // Direction for data sections is meaningless, but legacy endpoints might
4490 // expect sendrecv.
4491 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4492 RtpTransceiverDirection::kSendRecv,
4493 /*stopped=*/false);
4494 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4495 return options;
4496}
4497
4498cricket::MediaDescriptionOptions
4499PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4500 const std::string& mid) const {
4501 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4502 RtpTransceiverDirection::kInactive,
4503 /*stopped=*/true);
4504 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4505 return options;
4506}
4507
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004508absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004509 switch (data_channel_type_) {
4510 case cricket::DCT_RTP:
4511 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004512 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004513 }
4514 return rtp_data_channel_->content_name();
4515 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004516 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004517 case cricket::DCT_MEDIA_TRANSPORT:
4518 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004519 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004520 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004521 }
4522}
4523
Steve Anton4171afb2017-11-20 10:20:22 -08004524void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4525 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4526 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004527 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004528}
4529
Steve Anton4171afb2017-11-20 10:20:22 -08004530void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004531 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004532 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004533 cricket::MediaType media_type,
4534 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004535 RTC_DCHECK(!IsUnifiedPlan());
4536
Steve Anton4171afb2017-11-20 10:20:22 -08004537 std::vector<RtpSenderInfo>* current_senders =
4538 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004539
Steve Anton4171afb2017-11-20 10:20:22 -08004540 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004541 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004542 for (auto sender_it = current_senders->begin();
4543 sender_it != current_senders->end();
4544 /* incremented manually */) {
4545 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004546 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004547 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004548 std::string params_stream_id;
4549 if (params) {
4550 params_stream_id =
4551 (!params->first_stream_id().empty() ? params->first_stream_id()
4552 : kDefaultStreamId);
4553 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004554 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004555 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004556 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004557 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004558 sender_exists) {
4559 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004560 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004561 OnRemoteSenderRemoved(info, media_type);
4562 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004563 }
4564 }
4565
Steve Anton4171afb2017-11-20 10:20:22 -08004566 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004567 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004568 if (!params.has_ssrcs()) {
4569 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4570 // sender, this means it is coming from a Unified Plan endpoint,so we just
4571 // create a default.
4572 default_sender_needed = true;
4573 break;
4574 }
4575
Seth Hampson845e8782018-03-02 11:34:10 -08004576 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004577 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004578 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4579 // not supported in Plan B, we just take the first here and create the
4580 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004581 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004582 (!params.first_stream_id().empty() ? params.first_stream_id()
4583 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004584 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004585 uint32_t ssrc = params.first_ssrc();
4586
4587 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004588 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004589 if (!stream) {
4590 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004591 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004592 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004593 remote_streams_->AddStream(stream);
4594 new_streams->AddStream(stream);
4595 }
4596
Steve Anton4171afb2017-11-20 10:20:22 -08004597 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004598 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004599 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004600 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004601 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004602 }
4603 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004604
Steve Anton4171afb2017-11-20 10:20:22 -08004605 // Add default sender if necessary.
4606 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004607 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004608 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004609 if (!default_stream) {
4610 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004611 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004612 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004613 remote_streams_->AddStream(default_stream);
4614 new_streams->AddStream(default_stream);
4615 }
Steve Anton4171afb2017-11-20 10:20:22 -08004616 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4617 ? kDefaultAudioSenderId
4618 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004619 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004620 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004621 if (!default_sender_info) {
4622 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004623 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004624 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004625 }
4626 }
deadbeefab9b2d12015-10-14 11:33:11 -07004627}
4628
Steve Anton4171afb2017-11-20 10:20:22 -08004629void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4630 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004631 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4632 << " receiver for track_id=" << sender_info.sender_id
4633 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004634
Steve Anton3d954a62018-04-02 11:27:23 -07004635 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004636 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004637 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004638 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004639 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004640 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004641 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004642 }
4643}
4644
Steve Anton4171afb2017-11-20 10:20:22 -08004645void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4646 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004647 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4648 << " receiver for track_id=" << sender_info.sender_id
4649 << " and stream_id=" << sender_info.stream_id;
4650
Seth Hampson845e8782018-03-02 11:34:10 -08004651 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004652
Henrik Boström933d8b02017-10-10 10:05:16 -07004653 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004654 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004655 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4656 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004657 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004658 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004659 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004660 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004661 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004662 }
4663 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004664 // Stopping or destroying a VideoRtpReceiver will end the
4665 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004666 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004667 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004668 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004669 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004670 // There's no guarantee the track is still available, e.g. the track may
4671 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004672 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004673 }
4674 } else {
nisseede5da42017-01-12 05:15:36 -08004675 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004676 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004677 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004678 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004679 }
deadbeefab9b2d12015-10-14 11:33:11 -07004680}
4681
4682void PeerConnection::UpdateEndedRemoteMediaStreams() {
4683 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4684 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4685 MediaStreamInterface* stream = remote_streams_->at(i);
4686 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4687 streams_to_remove.push_back(stream);
4688 }
4689 }
4690
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004691 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004692 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004693 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004694 }
4695}
4696
Steve Anton4171afb2017-11-20 10:20:22 -08004697void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004698 const std::vector<cricket::StreamParams>& streams,
4699 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004700 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004701
Seth Hampson845e8782018-03-02 11:34:10 -08004702 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004703 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004704 for (auto sender_it = current_senders->begin();
4705 sender_it != current_senders->end();
4706 /* incremented manually */) {
4707 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004708 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004709 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4710 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004711 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004712 OnLocalSenderRemoved(info, media_type);
4713 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004714 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004715 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004716 }
4717 }
4718
Steve Anton4171afb2017-11-20 10:20:22 -08004719 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004720 for (const cricket::StreamParams& params : streams) {
4721 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004722 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004723 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004724 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004725 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004726 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004727 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004728 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004729 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004730 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004731 }
4732 }
4733}
4734
Steve Anton4171afb2017-11-20 10:20:22 -08004735void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4736 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004737 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004738 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004739 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004740 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4741 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004742 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004743 return;
4744 }
4745
deadbeeffac06552015-11-25 11:26:01 -08004746 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004747 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004748 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004749 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004750 }
deadbeeffac06552015-11-25 11:26:01 -08004751
Seth Hampson5b4f0752018-04-02 16:31:36 -07004752 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004753 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004754}
4755
Steve Anton4171afb2017-11-20 10:20:22 -08004756void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4757 cricket::MediaType media_type) {
4758 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004759 if (!sender) {
4760 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004761 // SessionDescriptions has been renegotiated.
4762 return;
4763 }
deadbeeffac06552015-11-25 11:26:01 -08004764
4765 // A sender has been removed from the SessionDescription but it's still
4766 // associated with the PeerConnection. This only occurs if the SDP doesn't
4767 // match with the calls to CreateSender, AddStream and RemoveStream.
4768 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004769 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004770 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004771 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004772 }
deadbeeffac06552015-11-25 11:26:01 -08004773
Steve Anton4171afb2017-11-20 10:20:22 -08004774 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004775}
4776
4777void PeerConnection::UpdateLocalRtpDataChannels(
4778 const cricket::StreamParamsVec& streams) {
4779 std::vector<std::string> existing_channels;
4780
4781 // Find new and active data channels.
4782 for (const cricket::StreamParams& params : streams) {
4783 // |it->sync_label| is actually the data channel label. The reason is that
4784 // we use the same naming of data channels as we do for
4785 // MediaStreams and Tracks.
4786 // For MediaStreams, the sync_label is the MediaStream label and the
4787 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004788 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004789 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004790 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004791 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004792 continue;
4793 }
4794 // Set the SSRC the data channel should use for sending.
4795 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4796 existing_channels.push_back(data_channel_it->first);
4797 }
4798
4799 UpdateClosingRtpDataChannels(existing_channels, true);
4800}
4801
4802void PeerConnection::UpdateRemoteRtpDataChannels(
4803 const cricket::StreamParamsVec& streams) {
4804 std::vector<std::string> existing_channels;
4805
4806 // Find new and active data channels.
4807 for (const cricket::StreamParams& params : streams) {
4808 // The data channel label is either the mslabel or the SSRC if the mslabel
4809 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004810 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004811 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004812 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004813 auto data_channel_it = rtp_data_channels_.find(label);
4814 if (data_channel_it == rtp_data_channels_.end()) {
4815 // This is a new data channel.
4816 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4817 } else {
4818 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4819 }
4820 existing_channels.push_back(label);
4821 }
4822
4823 UpdateClosingRtpDataChannels(existing_channels, false);
4824}
4825
4826void PeerConnection::UpdateClosingRtpDataChannels(
4827 const std::vector<std::string>& active_channels,
4828 bool is_local_update) {
4829 auto it = rtp_data_channels_.begin();
4830 while (it != rtp_data_channels_.end()) {
4831 DataChannel* data_channel = it->second;
Steve Anton64b626b2019-01-28 17:25:26 -08004832 if (absl::c_linear_search(active_channels, data_channel->label())) {
deadbeefab9b2d12015-10-14 11:33:11 -07004833 ++it;
4834 continue;
4835 }
4836
4837 if (is_local_update) {
4838 data_channel->SetSendSsrc(0);
4839 } else {
4840 data_channel->RemotePeerRequestClose();
4841 }
4842
4843 if (data_channel->state() == DataChannel::kClosed) {
4844 rtp_data_channels_.erase(it);
4845 it = rtp_data_channels_.begin();
4846 } else {
4847 ++it;
4848 }
4849 }
4850}
4851
4852void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4853 uint32_t remote_ssrc) {
4854 rtc::scoped_refptr<DataChannel> channel(
4855 InternalCreateDataChannel(label, nullptr));
4856 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004857 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004858 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004859 return;
4860 }
4861 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004862 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4863 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004864 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004865}
4866
4867rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4868 const std::string& label,
4869 const InternalDataChannelInit* config) {
4870 if (IsClosed()) {
4871 return nullptr;
4872 }
Steve Anton75737c02017-11-06 10:37:17 -08004873 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004874 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004875 << "InternalCreateDataChannel: Data is not supported in this call.";
4876 return nullptr;
4877 }
4878 InternalDataChannelInit new_config =
4879 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004880 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004881 if (new_config.id < 0) {
4882 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004883 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004884 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004885 RTC_LOG(LS_ERROR)
4886 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004887 return nullptr;
4888 }
4889 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004890 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004891 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004892 return nullptr;
4893 }
4894 }
4895
Steve Anton75737c02017-11-06 10:37:17 -08004896 rtc::scoped_refptr<DataChannel> channel(
4897 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004898 if (!channel) {
4899 sid_allocator_.ReleaseSid(new_config.id);
4900 return nullptr;
4901 }
4902
4903 if (channel->data_channel_type() == cricket::DCT_RTP) {
4904 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004905 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4906 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004907 return nullptr;
4908 }
4909 rtp_data_channels_[channel->label()] = channel;
4910 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004911 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004912 sctp_data_channels_.push_back(channel);
4913 channel->SignalClosed.connect(this,
4914 &PeerConnection::OnSctpDataChannelClosed);
4915 }
4916
Steve Anton2d8609c2018-01-23 16:38:46 -08004917 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004918 return channel;
4919}
4920
4921bool PeerConnection::HasDataChannels() const {
4922 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4923}
4924
4925void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4926 for (const auto& channel : sctp_data_channels_) {
4927 if (channel->id() < 0) {
4928 int sid;
4929 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004930 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004931 continue;
4932 }
4933 channel->SetSctpSid(sid);
4934 }
4935 }
4936}
4937
4938void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004939 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004940 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4941 ++it) {
4942 if (it->get() == channel) {
4943 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004944 // After the closing procedure is done, it's safe to use this ID for
4945 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004946 sid_allocator_.ReleaseSid(channel->id());
4947 }
deadbeefbd292462015-12-14 18:15:29 -08004948 // Since this method is triggered by a signal from the DataChannel,
4949 // we can't free it directly here; we need to free it asynchronously.
4950 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004951 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004952 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4953 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004954 return;
4955 }
4956 }
4957}
4958
deadbeefab9b2d12015-10-14 11:33:11 -07004959void PeerConnection::OnDataChannelDestroyed() {
4960 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4961 // DataChannel may callback to us and try to modify the list.
4962 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4963 temp_rtp_dcs.swap(rtp_data_channels_);
4964 for (const auto& kv : temp_rtp_dcs) {
4965 kv.second->OnTransportChannelDestroyed();
4966 }
4967
4968 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4969 temp_sctp_dcs.swap(sctp_data_channels_);
4970 for (const auto& channel : temp_sctp_dcs) {
4971 channel->OnTransportChannelDestroyed();
4972 }
4973}
4974
4975void PeerConnection::OnDataChannelOpenMessage(
4976 const std::string& label,
4977 const InternalDataChannelInit& config) {
4978 rtc::scoped_refptr<DataChannel> channel(
4979 InternalCreateDataChannel(label, &config));
4980 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004981 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004982 return;
4983 }
4984
deadbeefa601f5c2016-06-06 14:27:39 -07004985 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4986 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004987 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004988 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004989}
4990
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004991bool PeerConnection::HandleOpenMessage_s(
4992 const cricket::ReceiveDataParams& params,
4993 const rtc::CopyOnWriteBuffer& buffer) {
4994 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4995 // Received OPEN message; parse and signal that a new data channel should
4996 // be created.
4997 std::string label;
4998 InternalDataChannelInit config;
4999 config.id = params.ssrc;
5000 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
5001 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
5002 << params.ssrc;
5003 return true;
5004 }
5005 config.open_handshake_role = InternalDataChannelInit::kAcker;
5006 OnDataChannelOpenMessage(label, config);
5007 return true;
5008 }
5009 return false;
5010}
5011
Steve Anton4171afb2017-11-20 10:20:22 -08005012rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5013PeerConnection::GetAudioTransceiver() const {
5014 // This method only works with Plan B SDP, where there is a single
5015 // audio/video transceiver.
5016 RTC_DCHECK(!IsUnifiedPlan());
5017 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005018 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005019 return transceiver;
5020 }
5021 }
5022 RTC_NOTREACHED();
5023 return nullptr;
5024}
5025
5026rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5027PeerConnection::GetVideoTransceiver() const {
5028 // This method only works with Plan B SDP, where there is a single
5029 // audio/video transceiver.
5030 RTC_DCHECK(!IsUnifiedPlan());
5031 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08005032 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08005033 return transceiver;
5034 }
5035 }
5036 RTC_NOTREACHED();
5037 return nullptr;
5038}
5039
5040// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
5041// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07005042bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08005043 switch (type) {
5044 case cricket::MEDIA_TYPE_AUDIO:
5045 return !GetAudioTransceiver()->internal()->senders().empty();
5046 case cricket::MEDIA_TYPE_VIDEO:
5047 return !GetVideoTransceiver()->internal()->senders().empty();
5048 case cricket::MEDIA_TYPE_DATA:
5049 return false;
5050 }
5051 RTC_NOTREACHED();
5052 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07005053}
5054
Steve Anton4171afb2017-11-20 10:20:22 -08005055rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5056PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005057 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005058 for (auto sender : transceiver->internal()->senders()) {
5059 if (sender->track() == track) {
5060 return sender;
5061 }
5062 }
5063 }
5064 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08005065}
5066
Steve Anton4171afb2017-11-20 10:20:22 -08005067rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
5068PeerConnection::FindSenderById(const std::string& sender_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005069 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005070 for (auto sender : transceiver->internal()->senders()) {
5071 if (sender->id() == sender_id) {
5072 return sender;
5073 }
5074 }
5075 }
5076 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005077}
5078
Steve Anton4171afb2017-11-20 10:20:22 -08005079rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
5080PeerConnection::FindReceiverById(const std::string& receiver_id) const {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005081 for (const auto& transceiver : transceivers_) {
Steve Anton4171afb2017-11-20 10:20:22 -08005082 for (auto receiver : transceiver->internal()->receivers()) {
5083 if (receiver->id() == receiver_id) {
5084 return receiver;
5085 }
5086 }
5087 }
5088 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07005089}
5090
Steve Anton4171afb2017-11-20 10:20:22 -08005091std::vector<PeerConnection::RtpSenderInfo>*
5092PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
5093 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5094 media_type == cricket::MEDIA_TYPE_VIDEO);
5095 return (media_type == cricket::MEDIA_TYPE_AUDIO)
5096 ? &remote_audio_sender_infos_
5097 : &remote_video_sender_infos_;
5098}
5099
5100std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07005101 cricket::MediaType media_type) {
5102 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
5103 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08005104 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
5105 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07005106}
5107
Steve Anton4171afb2017-11-20 10:20:22 -08005108const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
5109 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005110 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08005111 const std::string sender_id) const {
5112 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00005113 if (sender_info.stream_id == stream_id &&
5114 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08005115 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07005116 }
5117 }
5118 return nullptr;
5119}
5120
5121DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
5122 for (const auto& channel : sctp_data_channels_) {
5123 if (channel->id() == sid) {
5124 return channel;
5125 }
5126 }
5127 return nullptr;
5128}
5129
deadbeef91dd5672016-05-18 16:55:30 -07005130bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005131 const cricket::ServerAddresses& stun_servers,
5132 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005133 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07005134 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005135 // To handle both internal and externally created port allocator, we will
5136 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07005137 port_allocator_flags_ = port_allocator_->flags();
5138 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
5139 cricket::PORTALLOCATOR_ENABLE_IPV6 |
5140 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005141 // If the disable-IPv6 flag was specified, we'll not override it
5142 // by experiment.
5143 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005144 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005145 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5146 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005147 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005148 }
5149
zhihuangb09b3f92017-03-07 14:40:51 -08005150 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005151 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005152 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005153 }
5154
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005155 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005156 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005157 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005158 }
5159
honghaiz60347052016-05-31 18:29:12 -07005160 if (configuration.candidate_network_policy ==
5161 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005162 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005163 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005164 }
5165
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005166 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005167 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005168 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5169 }
5170
Qingsi Wanga2d60672018-04-11 16:57:45 -07005171 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005172 // No step delay is used while allocating ports.
5173 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5174 port_allocator_->set_candidate_filter(
5175 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005176 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005177
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005178 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005179 for (auto& turn_server : turn_servers_copy) {
5180 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005181 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005182 // Call this last since it may create pooled allocator sessions using the
5183 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005184 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005185 stun_servers, std::move(turn_servers_copy),
5186 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5187 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005188 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005189 return true;
5190}
5191
deadbeef91dd5672016-05-18 16:55:30 -07005192bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005193 const cricket::ServerAddresses& stun_servers,
5194 const std::vector<cricket::RelayServerConfig>& turn_servers,
5195 IceTransportsType type,
5196 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005197 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005198 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005199 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005200 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005201 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005202 // According to JSEP, after setLocalDescription, changing the candidate pool
5203 // size is not allowed, and changing the set of ICE servers will not result
5204 // in new candidates being gathered.
5205 if (local_description()) {
5206 port_allocator_->FreezeCandidatePool();
5207 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005208 // Add the custom tls turn servers if they exist.
5209 auto turn_servers_copy = turn_servers;
5210 for (auto& turn_server : turn_servers_copy) {
5211 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5212 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005213 // Call this last since it may create pooled allocator sessions using the
5214 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005215 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005216 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5217 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005218}
5219
Steve Antonba818672017-11-06 10:21:57 -08005220cricket::ChannelManager* PeerConnection::channel_manager() const {
5221 return factory_->channel_manager();
5222}
5223
Elad Alon99c3fe52017-10-13 16:29:40 +02005224bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005225 std::unique_ptr<RtcEventLogOutput> output,
5226 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005227 if (!event_log_) {
5228 return false;
5229 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005230 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005231}
5232
5233void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005234 if (event_log_) {
5235 event_log_->StopLogging();
5236 }
ivoc14d5dbe2016-07-04 07:06:55 -07005237}
nisseeaabdf62017-05-05 02:23:02 -07005238
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005239cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005240 const std::string& content_name) {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005241 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005242 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005243 if (channel && channel->content_name() == content_name) {
5244 return channel;
5245 }
Steve Anton75737c02017-11-06 10:37:17 -08005246 }
5247 if (rtp_data_channel() &&
5248 rtp_data_channel()->content_name() == content_name) {
5249 return rtp_data_channel();
5250 }
5251 return nullptr;
5252}
5253
5254bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005255 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005256 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005257 RTC_LOG(LS_INFO)
5258 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005259 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005260 return false;
5261 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005262 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005263 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005264 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005265 return false;
5266 }
5267
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005268 absl::optional<rtc::SSLRole> dtls_role;
5269 if (sctp_mid_) {
5270 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5271 } else if (is_caller_) {
5272 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5273 }
Zhi Huange830e682018-03-30 10:48:35 -07005274 if (dtls_role) {
5275 *role = *dtls_role;
5276 return true;
5277 }
5278 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005279}
5280
5281bool PeerConnection::GetSslRole(const std::string& content_name,
5282 rtc::SSLRole* role) {
5283 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005284 RTC_LOG(LS_INFO)
5285 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005286 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005287 return false;
5288 }
5289
Zhi Huange830e682018-03-30 10:48:35 -07005290 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5291 if (dtls_role) {
5292 *role = *dtls_role;
5293 return true;
5294 }
5295 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005296}
5297
Steve Antonf8470812017-12-04 10:46:21 -08005298void PeerConnection::SetSessionError(SessionError error,
5299 const std::string& error_desc) {
5300 RTC_DCHECK_RUN_ON(signaling_thread());
5301 if (error != session_error_) {
5302 session_error_ = error;
5303 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005304 }
5305}
5306
Zhi Huange830e682018-03-30 10:48:35 -07005307RTCError PeerConnection::UpdateSessionState(
5308 SdpType type,
5309 cricket::ContentSource source,
5310 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005311 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005312
5313 // If there's already a pending error then no state transition should happen.
5314 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005315 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005316
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005317 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005318 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005319 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005320 }
5321
5322 // Update the signaling state according to the specified state machine (see
5323 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005324 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005325 ChangeSignalingState(source == cricket::CS_LOCAL
5326 ? PeerConnectionInterface::kHaveLocalOffer
5327 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005328 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005329 ChangeSignalingState(source == cricket::CS_LOCAL
5330 ? PeerConnectionInterface::kHaveLocalPrAnswer
5331 : PeerConnectionInterface::kHaveRemotePrAnswer);
5332 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005333 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005334 ChangeSignalingState(PeerConnectionInterface::kStable);
5335 }
5336
5337 // Update internal objects according to the session description's media
5338 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005339 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005340 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005341 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005342 }
5343
Steve Anton8a006912017-12-04 15:25:56 -08005344 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005345}
5346
Steve Anton8a006912017-12-04 15:25:56 -08005347RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005348 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005349 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005350 const SessionDescriptionInterface* sdesc =
5351 (source == cricket::CS_LOCAL ? local_description()
5352 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005353 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005354
5355 // Push down the new SDP media section for each audio/video transceiver.
Mirko Bonadei739baf02019-01-27 17:29:42 +01005356 for (const auto& transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005357 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005358 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005359 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005360 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005361 continue;
5362 }
5363 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005364 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005365 if (!content_desc) {
5366 continue;
5367 }
5368 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005369 bool success = (source == cricket::CS_LOCAL)
5370 ? channel->SetLocalContent(content_desc, type, &error)
5371 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005372 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005373 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005374 }
5375 }
5376
5377 // If using the RtpDataChannel, push down the new SDP section for it too.
5378 if (rtp_data_channel_) {
5379 const ContentInfo* data_content =
5380 cricket::GetFirstDataContent(sdesc->description());
5381 if (data_content && !data_content->rejected) {
5382 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005383 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005384 if (data_desc) {
5385 std::string error;
5386 bool success =
5387 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005388 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005389 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005390 if (!success) {
Yves Gereyae6e0b22019-01-22 21:48:57 +01005391 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
Steve Antoned10bd92017-12-05 10:52:59 -08005392 }
Steve Anton75737c02017-11-06 10:37:17 -08005393 }
5394 }
5395 }
Steve Antoned10bd92017-12-05 10:52:59 -08005396
Steve Anton75737c02017-11-06 10:37:17 -08005397 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5398 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5399 if (sctp_transport_ && local_description() && remote_description() &&
5400 cricket::GetFirstDataContent(local_description()->description()) &&
5401 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005402 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005403 RTC_FROM_HERE,
5404 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005405 if (!success) {
5406 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5407 "Failed to push down SCTP parameters.");
5408 }
Steve Anton75737c02017-11-06 10:37:17 -08005409 }
Steve Antoned10bd92017-12-05 10:52:59 -08005410
Steve Anton8a006912017-12-04 15:25:56 -08005411 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005412}
5413
5414bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5415 RTC_DCHECK(network_thread()->IsCurrent());
5416 RTC_DCHECK(local_description());
5417 RTC_DCHECK(remote_description());
5418 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5419 // When we support "max-message-size", that would also be pushed down here.
5420 return sctp_transport_->Start(
5421 GetSctpPort(local_description()->description()),
5422 GetSctpPort(remote_description()->description()));
5423}
5424
Steve Anton8a006912017-12-04 15:25:56 -08005425RTCError PeerConnection::PushdownTransportDescription(
5426 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005427 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005428 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005429
Zhi Huange830e682018-03-30 10:48:35 -07005430 if (source == cricket::CS_LOCAL) {
5431 const SessionDescriptionInterface* sdesc = local_description();
5432 RTC_DCHECK(sdesc);
5433 return transport_controller_->SetLocalDescription(type,
5434 sdesc->description());
5435 } else {
5436 const SessionDescriptionInterface* sdesc = remote_description();
5437 RTC_DCHECK(sdesc);
5438 return transport_controller_->SetRemoteDescription(type,
5439 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005440 }
Steve Anton75737c02017-11-06 10:37:17 -08005441}
5442
5443bool PeerConnection::GetTransportDescription(
5444 const SessionDescription* description,
5445 const std::string& content_name,
5446 cricket::TransportDescription* tdesc) {
5447 if (!description || !tdesc) {
5448 return false;
5449 }
5450 const TransportInfo* transport_info =
5451 description->GetTransportInfoByName(content_name);
5452 if (!transport_info) {
5453 return false;
5454 }
5455 *tdesc = transport_info->description;
5456 return true;
5457}
5458
Steve Anton75737c02017-11-06 10:37:17 -08005459cricket::IceConfig PeerConnection::ParseIceConfig(
5460 const PeerConnectionInterface::RTCConfiguration& config) const {
5461 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005462 switch (config.continual_gathering_policy) {
5463 case PeerConnectionInterface::GATHER_ONCE:
5464 gathering_policy = cricket::GATHER_ONCE;
5465 break;
5466 case PeerConnectionInterface::GATHER_CONTINUALLY:
5467 gathering_policy = cricket::GATHER_CONTINUALLY;
5468 break;
5469 default:
5470 RTC_NOTREACHED();
5471 gathering_policy = cricket::GATHER_ONCE;
5472 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005473
Steve Anton75737c02017-11-06 10:37:17 -08005474 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005475 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5476 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005477 ice_config.prioritize_most_likely_candidate_pairs =
5478 config.prioritize_most_likely_ice_candidate_pairs;
5479 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005480 RTCConfigurationToIceConfigOptionalInt(
5481 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005482 ice_config.continual_gathering_policy = gathering_policy;
5483 ice_config.presume_writable_when_fully_relayed =
5484 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005485 ice_config.ice_check_interval_strong_connectivity =
5486 config.ice_check_interval_strong_connectivity;
5487 ice_config.ice_check_interval_weak_connectivity =
5488 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005489 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005490 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5491 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005492 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005493 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005494 ice_config.regather_all_networks_interval_range =
5495 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005496 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005497 return ice_config;
5498}
5499
Steve Antona41959e2018-11-28 11:15:33 -08005500static absl::string_view GetTrackIdBySsrc(
5501 const SessionDescriptionInterface* session_description,
5502 uint32_t ssrc) {
5503 if (!session_description) {
5504 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005505 }
Steve Antona41959e2018-11-28 11:15:33 -08005506 for (const cricket::ContentInfo& content :
5507 session_description->description()->contents()) {
5508 const cricket::MediaContentDescription& media =
5509 *content.media_description();
5510 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5511 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5512 const cricket::StreamParams* stream_params =
5513 cricket::GetStreamBySsrc(media.streams(), ssrc);
5514 if (stream_params) {
5515 return stream_params->id;
5516 }
5517 }
5518 }
5519 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005520}
5521
Steve Antona41959e2018-11-28 11:15:33 -08005522absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5523 return GetTrackIdBySsrc(local_description(), ssrc);
5524}
5525
5526absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5527 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005528}
5529
5530bool PeerConnection::SendData(const cricket::SendDataParams& params,
5531 const rtc::CopyOnWriteBuffer& payload,
5532 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005533 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5534 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5535 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005536 return false;
5537 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005538 if (media_transport_) {
5539 SendDataParams send_params;
5540 send_params.type = ToWebrtcDataMessageType(params.type);
5541 send_params.ordered = params.ordered;
5542 if (params.max_rtx_count >= 0) {
5543 send_params.max_rtx_count = params.max_rtx_count;
5544 } else if (params.max_rtx_ms >= 0) {
5545 send_params.max_rtx_ms = params.max_rtx_ms;
5546 }
5547 return media_transport_->SendData(params.sid, send_params, payload).ok();
5548 }
Steve Anton75737c02017-11-06 10:37:17 -08005549 return rtp_data_channel_
5550 ? rtp_data_channel_->SendData(params, payload, result)
5551 : network_thread()->Invoke<bool>(
5552 RTC_FROM_HERE,
5553 Bind(&cricket::SctpTransportInternal::SendData,
5554 sctp_transport_.get(), params, payload, result));
5555}
5556
5557bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005558 RTC_DCHECK_RUN_ON(signaling_thread());
5559 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005560 // Don't log an error here, because DataChannels are expected to call
5561 // ConnectDataChannel in this state. It's the only way to initially tell
5562 // whether or not the underlying transport is ready.
5563 return false;
5564 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005565 if (media_transport_) {
5566 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5567 &DataChannel::OnChannelReady);
5568 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5569 &DataChannel::OnDataReceived);
5570 SignalMediaTransportChannelClosing_s.connect(
5571 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5572 SignalMediaTransportChannelClosed_s.connect(
5573 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5574 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005575 rtp_data_channel_->SignalReadyToSendData.connect(
5576 webrtc_data_channel, &DataChannel::OnChannelReady);
5577 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5578 &DataChannel::OnDataReceived);
5579 } else {
5580 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5581 &DataChannel::OnChannelReady);
5582 SignalSctpDataReceived.connect(webrtc_data_channel,
5583 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005584 SignalSctpClosingProcedureStartedRemotely.connect(
5585 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5586 SignalSctpClosingProcedureComplete.connect(
5587 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005588 }
5589 return true;
5590}
5591
5592void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005593 RTC_DCHECK_RUN_ON(signaling_thread());
5594 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005595 RTC_LOG(LS_ERROR)
5596 << "DisconnectDataChannel called when rtp_data_channel_ and "
5597 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005598 return;
5599 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005600 if (media_transport_) {
5601 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5602 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5603 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5604 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5605 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005606 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5607 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5608 } else {
5609 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5610 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005611 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5612 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005613 }
5614}
5615
5616void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005617 if (media_transport_) {
5618 // No-op. Media transport does not need to add streams.
5619 return;
5620 }
Steve Anton75737c02017-11-06 10:37:17 -08005621 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005622 RTC_LOG(LS_ERROR)
5623 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005624 return;
5625 }
5626 network_thread()->Invoke<void>(
5627 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5628 sctp_transport_.get(), sid));
5629}
5630
5631void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005632 if (media_transport_) {
5633 media_transport_->CloseChannel(sid);
5634 return;
5635 }
Steve Anton75737c02017-11-06 10:37:17 -08005636 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005637 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005638 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005639 return;
5640 }
5641 network_thread()->Invoke<void>(
5642 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5643 sctp_transport_.get(), sid));
5644}
5645
5646bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005647 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005648 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005649 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005650 sctp_ready_to_send_data_;
5651}
5652
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005653void PeerConnection::OnDataReceived(int channel_id,
5654 DataMessageType type,
5655 const rtc::CopyOnWriteBuffer& buffer) {
5656 cricket::ReceiveDataParams params;
5657 params.sid = channel_id;
5658 params.type = ToCricketDataMessageType(type);
5659 media_transport_invoker_->AsyncInvoke<void>(
5660 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5661 RTC_DCHECK_RUN_ON(signaling_thread());
5662 if (!HandleOpenMessage_s(params, buffer)) {
5663 SignalMediaTransportReceivedData_s(params, buffer);
5664 }
5665 });
5666}
5667
5668void PeerConnection::OnChannelClosing(int channel_id) {
5669 media_transport_invoker_->AsyncInvoke<void>(
5670 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5671 RTC_DCHECK_RUN_ON(signaling_thread());
5672 SignalMediaTransportChannelClosing_s(channel_id);
5673 });
5674}
5675
5676void PeerConnection::OnChannelClosed(int channel_id) {
5677 media_transport_invoker_->AsyncInvoke<void>(
5678 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5679 RTC_DCHECK_RUN_ON(signaling_thread());
5680 SignalMediaTransportChannelClosed_s(channel_id);
5681 });
5682}
5683
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005684absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005685 if (sctp_mid_ && transport_controller_) {
5686 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5687 if (dtls_transport) {
5688 return dtls_transport->transport_name();
5689 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005690 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005691 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005692 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005693}
5694
Qingsi Wang72a43a12018-02-20 16:03:18 -08005695cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5696 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005697 network_thread()->Invoke<void>(
5698 RTC_FROM_HERE,
5699 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5700 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005701 return candidate_states_list;
5702}
5703
Steve Anton5dfde182018-02-06 10:34:40 -08005704std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5705 const {
5706 std::map<std::string, std::string> transport_names_by_mid;
Mirko Bonadei739baf02019-01-27 17:29:42 +01005707 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005708 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005709 if (channel) {
5710 transport_names_by_mid[channel->content_name()] =
5711 channel->transport_name();
5712 }
Steve Anton75737c02017-11-06 10:37:17 -08005713 }
Steve Anton5dfde182018-02-06 10:34:40 -08005714 if (rtp_data_channel_) {
5715 transport_names_by_mid[rtp_data_channel_->content_name()] =
5716 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005717 }
5718 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005719 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005720 RTC_DCHECK(transport_name);
5721 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005722 }
Steve Anton5dfde182018-02-06 10:34:40 -08005723 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005724}
5725
Steve Anton5dfde182018-02-06 10:34:40 -08005726std::map<std::string, cricket::TransportStats>
5727PeerConnection::GetTransportStatsByNames(
5728 const std::set<std::string>& transport_names) {
5729 if (!network_thread()->IsCurrent()) {
5730 return network_thread()
5731 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5732 RTC_FROM_HERE,
5733 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005734 }
Steve Anton5dfde182018-02-06 10:34:40 -08005735 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5736 for (const std::string& transport_name : transport_names) {
5737 cricket::TransportStats transport_stats;
5738 bool success =
5739 transport_controller_->GetStats(transport_name, &transport_stats);
5740 if (success) {
5741 transport_stats_by_name[transport_name] = std::move(transport_stats);
5742 } else {
5743 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5744 << transport_name;
5745 }
5746 }
5747 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005748}
5749
5750bool PeerConnection::GetLocalCertificate(
5751 const std::string& transport_name,
5752 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005753 if (!certificate) {
5754 return false;
5755 }
5756 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5757 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005758}
5759
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005760std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005761 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005762 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005763}
5764
5765cricket::DataChannelType PeerConnection::data_channel_type() const {
5766 return data_channel_type_;
5767}
5768
5769bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5770 return pending_ice_restarts_.find(content_name) !=
5771 pending_ice_restarts_.end();
5772}
5773
Steve Anton75737c02017-11-06 10:37:17 -08005774bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5775 return transport_controller_->NeedsIceRestart(content_name);
5776}
5777
5778void PeerConnection::OnCertificateReady(
5779 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5780 transport_controller_->SetLocalCertificate(certificate);
5781}
5782
5783void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005784 SetSessionError(SessionError::kTransport,
5785 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005786}
5787
Alex Loiko9289eda2018-11-23 16:18:59 +00005788void PeerConnection::OnTransportControllerConnectionState(
5789 cricket::IceConnectionState state) {
5790 switch (state) {
5791 case cricket::kIceConnectionConnecting:
5792 // If the current state is Connected or Completed, then there were
5793 // writable channels but now there are not, so the next state must
5794 // be Disconnected.
5795 // kIceConnectionConnecting is currently used as the default,
5796 // un-connected state by the TransportController, so its only use is
5797 // detecting disconnections.
5798 if (ice_connection_state_ ==
5799 PeerConnectionInterface::kIceConnectionConnected ||
5800 ice_connection_state_ ==
5801 PeerConnectionInterface::kIceConnectionCompleted) {
5802 SetIceConnectionState(
5803 PeerConnectionInterface::kIceConnectionDisconnected);
5804 }
5805 break;
5806 case cricket::kIceConnectionFailed:
5807 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5808 break;
5809 case cricket::kIceConnectionConnected:
5810 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5811 "all transports are writable.";
5812 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5813 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5814 break;
5815 case cricket::kIceConnectionCompleted:
5816 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5817 "all transports are complete.";
5818 if (ice_connection_state_ !=
5819 PeerConnectionInterface::kIceConnectionConnected) {
5820 // If jumping directly from "checking" to "connected",
5821 // signal "connected" first.
5822 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5823 }
5824 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5825 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5826 ReportTransportStats();
5827 break;
5828 default:
5829 RTC_NOTREACHED();
5830 }
5831}
5832
Steve Anton75737c02017-11-06 10:37:17 -08005833void PeerConnection::OnTransportControllerCandidatesGathered(
5834 const std::string& transport_name,
5835 const cricket::Candidates& candidates) {
5836 RTC_DCHECK(signaling_thread()->IsCurrent());
5837 int sdp_mline_index;
5838 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005839 RTC_LOG(LS_ERROR)
5840 << "OnTransportControllerCandidatesGathered: content name "
5841 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005842 return;
5843 }
5844
5845 for (cricket::Candidates::const_iterator citer = candidates.begin();
5846 citer != candidates.end(); ++citer) {
5847 // Use transport_name as the candidate media id.
5848 std::unique_ptr<JsepIceCandidate> candidate(
5849 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5850 if (local_description()) {
5851 mutable_local_description()->AddCandidate(candidate.get());
5852 }
5853 OnIceCandidate(std::move(candidate));
5854 }
5855}
5856
5857void PeerConnection::OnTransportControllerCandidatesRemoved(
5858 const std::vector<cricket::Candidate>& candidates) {
5859 RTC_DCHECK(signaling_thread()->IsCurrent());
5860 // Sanity check.
5861 for (const cricket::Candidate& candidate : candidates) {
5862 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005863 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005864 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005865 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005866 return;
5867 }
5868 }
5869
5870 if (local_description()) {
5871 mutable_local_description()->RemoveCandidates(candidates);
5872 }
5873 OnIceCandidatesRemoved(candidates);
5874}
5875
5876void PeerConnection::OnTransportControllerDtlsHandshakeError(
5877 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005878 RTC_HISTOGRAM_ENUMERATION(
5879 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5880 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005881}
5882
Steve Antoned10bd92017-12-05 10:52:59 -08005883void PeerConnection::EnableSending() {
Mirko Bonadei739baf02019-01-27 17:29:42 +01005884 for (const auto& transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005885 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005886 if (channel && !channel->enabled()) {
5887 channel->Enable(true);
5888 }
Steve Anton75737c02017-11-06 10:37:17 -08005889 }
5890
Steve Anton4171afb2017-11-20 10:20:22 -08005891 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005892 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005893 }
Steve Anton75737c02017-11-06 10:37:17 -08005894}
5895
5896// Returns the media index for a local ice candidate given the content name.
5897bool PeerConnection::GetLocalCandidateMediaIndex(
5898 const std::string& content_name,
5899 int* sdp_mline_index) {
5900 if (!local_description() || !sdp_mline_index) {
5901 return false;
5902 }
5903
5904 bool content_found = false;
5905 const ContentInfos& contents = local_description()->description()->contents();
5906 for (size_t index = 0; index < contents.size(); ++index) {
5907 if (contents[index].name == content_name) {
5908 *sdp_mline_index = static_cast<int>(index);
5909 content_found = true;
5910 break;
5911 }
5912 }
5913 return content_found;
5914}
5915
5916bool PeerConnection::UseCandidatesInSessionDescription(
5917 const SessionDescriptionInterface* remote_desc) {
5918 if (!remote_desc) {
5919 return true;
5920 }
5921 bool ret = true;
5922
5923 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5924 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5925 for (size_t n = 0; n < candidates->count(); ++n) {
5926 const IceCandidateInterface* candidate = candidates->at(n);
5927 bool valid = false;
5928 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5929 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005930 RTC_LOG(LS_INFO)
5931 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005932 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005933 }
5934 continue;
5935 }
5936 ret = UseCandidate(candidate);
5937 if (!ret) {
5938 break;
5939 }
5940 }
5941 }
5942 return ret;
5943}
5944
5945bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5946 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5947 size_t remote_content_size =
5948 remote_description()->description()->contents().size();
5949 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005950 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005951 return false;
5952 }
5953
5954 cricket::ContentInfo content =
5955 remote_description()->description()->contents()[mediacontent_index];
5956 std::vector<cricket::Candidate> candidates;
5957 candidates.push_back(candidate->candidate());
5958 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005959 RTCError error =
5960 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005961 if (error.ok()) {
5962 // Candidates successfully submitted for checking.
5963 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5964 ice_connection_state_ ==
5965 PeerConnectionInterface::kIceConnectionDisconnected) {
5966 // If state is New, then the session has just gotten its first remote ICE
5967 // candidates, so go to Checking.
5968 // If state is Disconnected, the session is re-using old candidates or
5969 // receiving additional ones, so go to Checking.
5970 // If state is Connected, stay Connected.
5971 // TODO(bemasc): If state is Connected, and the new candidates are for a
5972 // newly added transport, then the state actually _should_ move to
5973 // checking. Add a way to distinguish that case.
5974 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5975 }
5976 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005977 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005978 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005979 }
5980 return true;
5981}
5982
5983void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005984 // Destroy video channel first since it may have a pointer to the
5985 // voice channel.
5986 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005987 if (!video_info || video_info->rejected) {
5988 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005989 }
5990
Steve Anton6fec8802017-12-04 10:37:29 -08005991 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5992 if (!audio_info || audio_info->rejected) {
5993 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005994 }
5995
5996 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5997 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005998 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005999 }
6000}
6001
Steve Antondcc3c022017-12-22 16:02:54 -08006002RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
6003 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08006004 const cricket::ContentGroup* bundle_group = nullptr;
6005 if (configuration_.bundle_policy ==
6006 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08006007 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08006008 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08006009 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6010 "max-bundle configured but session description "
6011 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08006012 }
6013 }
Steve Antondcc3c022017-12-22 16:02:54 -08006014 return std::move(bundle_group);
6015}
6016
6017RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07006018 // Creating the media channels. Transports should already have been created
6019 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08006020 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006021 if (voice && !voice->rejected &&
6022 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006023 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006024 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006025 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6026 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08006027 }
6028 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
6029 }
6030
Steve Antondcc3c022017-12-22 16:02:54 -08006031 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006032 if (video && !video->rejected &&
6033 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07006034 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08006035 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08006036 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6037 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006038 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08006039 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08006040 }
6041
Steve Antondcc3c022017-12-22 16:02:54 -08006042 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08006043 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006044 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006045 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08006046 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
6047 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08006048 }
6049 }
6050
Steve Anton8a006912017-12-04 15:25:56 -08006051 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006052}
6053
Steve Anton4171afb2017-11-20 10:20:22 -08006054// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006055cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006056 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006057 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07006058 MediaTransportInterface* media_transport = nullptr;
6059 if (configuration_.use_media_transport) {
6060 media_transport = GetMediaTransport(mid);
6061 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006062
Steve Anton75737c02017-11-06 10:37:17 -08006063 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006064 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006065 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006066 &ssrc_generator_, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006067 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006068 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006069 }
Steve Anton75737c02017-11-06 10:37:17 -08006070 voice_channel->SignalDtlsSrtpSetupFailure.connect(
6071 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006072 voice_channel->SignalSentPacket.connect(this,
6073 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006074 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006075
Steve Antoneda6ccd2017-12-04 10:21:55 -08006076 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006077}
6078
Steve Anton4171afb2017-11-20 10:20:22 -08006079// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08006080cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07006081 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006082 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Niels Möller46879152019-01-07 15:54:47 +01006083 MediaTransportInterface* media_transport = nullptr;
6084 if (configuration_.use_media_transport) {
6085 media_transport = GetMediaTransport(mid);
6086 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07006087
Steve Anton75737c02017-11-06 10:37:17 -08006088 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Niels Möller46879152019-01-07 15:54:47 +01006089 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006090 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006091 &ssrc_generator_, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08006092 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08006093 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08006094 }
Steve Anton75737c02017-11-06 10:37:17 -08006095 video_channel->SignalDtlsSrtpSetupFailure.connect(
6096 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08006097 video_channel->SignalSentPacket.connect(this,
6098 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07006099 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08006100
Steve Antoneda6ccd2017-12-04 10:21:55 -08006101 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08006102}
6103
Zhi Huange830e682018-03-30 10:48:35 -07006104bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006105 switch (data_channel_type_) {
6106 case cricket::DCT_MEDIA_TRANSPORT:
6107 if (network_thread()->Invoke<bool>(
6108 RTC_FROM_HERE,
6109 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
6110 this, mid))) {
6111 for (const auto& channel : sctp_data_channels_) {
6112 channel->OnTransportChannelCreated();
6113 }
6114 return true;
6115 }
Steve Anton75737c02017-11-06 10:37:17 -08006116 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006117 case cricket::DCT_SCTP:
6118 if (!sctp_factory_) {
6119 RTC_LOG(LS_ERROR)
6120 << "Trying to create SCTP transport, but didn't compile with "
6121 "SCTP support (HAVE_SCTP)";
6122 return false;
6123 }
6124 if (!network_thread()->Invoke<bool>(
6125 RTC_FROM_HERE,
6126 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
6127 return false;
6128 }
6129 for (const auto& channel : sctp_data_channels_) {
6130 channel->OnTransportChannelCreated();
6131 }
6132 return true;
6133 case cricket::DCT_RTP:
6134 default:
6135 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
6136 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
6137 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Amit Hilbuchbcd39d42019-01-25 17:13:56 -08006138 SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006139 if (!rtp_data_channel_) {
6140 return false;
6141 }
6142 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
6143 this, &PeerConnection::OnDtlsSrtpSetupFailure);
6144 rtp_data_channel_->SignalSentPacket.connect(
6145 this, &PeerConnection::OnSentPacket_w);
6146 rtp_data_channel_->SetRtpTransport(rtp_transport);
6147 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006148 }
6149
Steve Anton75737c02017-11-06 10:37:17 -08006150 return true;
6151}
6152
6153Call::Stats PeerConnection::GetCallStats() {
6154 if (!worker_thread()->IsCurrent()) {
6155 return worker_thread()->Invoke<Call::Stats>(
6156 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6157 }
6158 if (call_) {
6159 return call_->GetStats();
6160 } else {
6161 return Call::Stats();
6162 }
6163}
6164
Zhi Huange830e682018-03-30 10:48:35 -07006165bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006166 RTC_DCHECK(network_thread()->IsCurrent());
6167 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006168 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006169 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006170 RTC_DCHECK(dtls_transport);
6171 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006172 RTC_DCHECK(sctp_transport_);
6173 sctp_invoker_.reset(new rtc::AsyncInvoker());
6174 sctp_transport_->SignalReadyToSendData.connect(
6175 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6176 sctp_transport_->SignalDataReceived.connect(
6177 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006178 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6179 // another thread. Would be nice if there was a helper class similar to
6180 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6181 // code.
6182 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6183 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6184 sctp_transport_->SignalClosingProcedureComplete.connect(
6185 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006186 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006187 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006188 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006189}
6190
6191void PeerConnection::DestroySctpTransport_n() {
6192 RTC_DCHECK(network_thread()->IsCurrent());
6193 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006194 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006195 sctp_invoker_.reset(nullptr);
6196 sctp_ready_to_send_data_ = false;
6197}
6198
6199void PeerConnection::OnSctpTransportReadyToSendData_n() {
6200 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6201 RTC_DCHECK(network_thread()->IsCurrent());
6202 // Note: Cannot use rtc::Bind here because it will grab a reference to
6203 // PeerConnection and potentially cause PeerConnection to live longer than
6204 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6205 // be destroyed before PeerConnection is destroyed, and at that point all
6206 // pending tasks will be cleared.
6207 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6208 OnSctpTransportReadyToSendData_s(true);
6209 });
6210}
6211
6212void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6213 RTC_DCHECK(signaling_thread()->IsCurrent());
6214 sctp_ready_to_send_data_ = ready;
6215 SignalSctpReadyToSendData(ready);
6216}
6217
6218void PeerConnection::OnSctpTransportDataReceived_n(
6219 const cricket::ReceiveDataParams& params,
6220 const rtc::CopyOnWriteBuffer& payload) {
6221 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6222 RTC_DCHECK(network_thread()->IsCurrent());
6223 // Note: Cannot use rtc::Bind here because it will grab a reference to
6224 // PeerConnection and potentially cause PeerConnection to live longer than
6225 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6226 // be destroyed before PeerConnection is destroyed, and at that point all
6227 // pending tasks will be cleared.
6228 sctp_invoker_->AsyncInvoke<void>(
6229 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6230 OnSctpTransportDataReceived_s(params, payload);
6231 });
6232}
6233
6234void PeerConnection::OnSctpTransportDataReceived_s(
6235 const cricket::ReceiveDataParams& params,
6236 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006237 RTC_DCHECK_RUN_ON(signaling_thread());
6238 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006239 SignalSctpDataReceived(params, payload);
6240 }
6241}
6242
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006243void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006244 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6245 RTC_DCHECK(network_thread()->IsCurrent());
6246 sctp_invoker_->AsyncInvoke<void>(
6247 RTC_FROM_HERE, signaling_thread(),
6248 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006249 &SignalSctpClosingProcedureStartedRemotely, sid));
6250}
6251
6252void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6253 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6254 RTC_DCHECK(network_thread()->IsCurrent());
6255 sctp_invoker_->AsyncInvoke<void>(
6256 RTC_FROM_HERE, signaling_thread(),
6257 rtc::Bind(&sigslot::signal1<int>::operator(),
6258 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006259}
6260
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006261bool PeerConnection::SetupMediaTransportForDataChannels_n(
6262 const std::string& mid) {
6263 media_transport_ = transport_controller_->GetMediaTransport(mid);
6264 if (!media_transport_) {
6265 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6266 return false;
6267 }
6268
6269 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6270 media_transport_->SetDataSink(this);
6271 media_transport_data_mid_ = mid;
6272 transport_controller_->SignalMediaTransportStateChanged.connect(
6273 this, &PeerConnection::OnMediaTransportStateChanged_n);
6274 // Check the initial state right away, in case transport is already writable.
6275 OnMediaTransportStateChanged_n();
6276 return true;
6277}
6278
6279void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6280 if (!media_transport_) {
6281 return;
6282 }
6283 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6284 media_transport_data_mid_.reset();
6285 media_transport_->SetDataSink(nullptr);
6286 media_transport_invoker_ = nullptr;
6287 media_transport_ = nullptr;
6288}
6289
6290void PeerConnection::OnMediaTransportStateChanged_n() {
6291 if (!media_transport_data_mid_ ||
6292 transport_controller_->GetMediaTransportState(
6293 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6294 return;
6295 }
6296 media_transport_invoker_->AsyncInvoke<void>(
6297 RTC_FROM_HERE, signaling_thread(), [this] {
6298 RTC_DCHECK_RUN_ON(signaling_thread());
6299 media_transport_ready_to_send_data_ = true;
6300 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6301 });
6302}
6303
Steve Anton75737c02017-11-06 10:37:17 -08006304// Returns false if bundle is enabled and rtcp_mux is disabled.
6305bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6306 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6307 if (!bundle_enabled)
6308 return true;
6309
6310 const cricket::ContentGroup* bundle_group =
6311 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6312 RTC_DCHECK(bundle_group != NULL);
6313
6314 const cricket::ContentInfos& contents = desc->contents();
6315 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6316 citer != contents.end(); ++citer) {
6317 const cricket::ContentInfo* content = (&*citer);
6318 RTC_DCHECK(content != NULL);
6319 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006320 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006321 if (!HasRtcpMuxEnabled(content))
6322 return false;
6323 }
6324 }
6325 // RTCP-MUX is enabled in all the contents.
6326 return true;
6327}
6328
6329bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006330 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006331}
6332
Steve Anton06817cd2018-12-18 15:55:30 -08006333static RTCError ValidateMids(const cricket::SessionDescription& description) {
6334 std::set<std::string> mids;
6335 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006336 if (content.name.empty()) {
6337 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6338 "A media section is missing a MID attribute.");
6339 }
Steve Anton06817cd2018-12-18 15:55:30 -08006340 if (!mids.insert(content.name).second) {
6341 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6342 "Duplicate a=mid value '" + content.name + "'.");
6343 }
6344 }
6345 return RTCError::OK();
6346}
6347
Steve Anton8a006912017-12-04 15:25:56 -08006348RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006349 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006350 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006351 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006352 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006353 }
6354
6355 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006356 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006357 }
6358
Steve Anton3828c062017-12-06 10:34:51 -08006359 SdpType type = sdesc->GetType();
6360 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6361 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006362 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006363 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006364 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006365 }
6366
Steve Anton06817cd2018-12-18 15:55:30 -08006367 RTCError error = ValidateMids(*sdesc->description());
6368 if (!error.ok()) {
6369 return error;
6370 }
6371
Steve Anton75737c02017-11-06 10:37:17 -08006372 // Verify crypto settings.
6373 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006374 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6375 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006376 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006377 if (!crypto_error.ok()) {
6378 return crypto_error;
6379 }
Steve Anton75737c02017-11-06 10:37:17 -08006380 }
6381
6382 // Verify ice-ufrag and ice-pwd.
6383 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006384 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6385 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006386 }
6387
6388 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006389 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6390 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006391 }
6392
6393 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6394 // m-lines that do not rtcp-mux enabled.
6395
6396 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006397 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006398 // With an answer we want to compare the new answer session description with
6399 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006400 const cricket::SessionDescription* offer_desc =
6401 (source == cricket::CS_LOCAL) ? remote_description()->description()
6402 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006403 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6404 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6405 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006406 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6407 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006408 }
6409 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006410 // The re-offers should respect the order of m= sections in current
6411 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006412 // With a re-offer, either the current local or current remote descriptions
6413 // could be the most up to date, so we would like to check against both of
6414 // them if they exist. It could be the case that one of them has a 0 port
6415 // for a media section, but the other does not. This is important to check
6416 // against in the case that we are recycling an m= section.
6417 const cricket::SessionDescription* current_desc = nullptr;
6418 const cricket::SessionDescription* secondary_current_desc = nullptr;
6419 if (local_description()) {
6420 current_desc = local_description()->description();
6421 if (remote_description()) {
6422 secondary_current_desc = remote_description()->description();
6423 }
6424 } else if (remote_description()) {
6425 current_desc = remote_description()->description();
6426 }
Steve Anton75737c02017-11-06 10:37:17 -08006427 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006428 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6429 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6431 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006432 }
6433 }
6434
Steve Antonba42e992018-04-09 14:10:01 -07006435 if (IsUnifiedPlan()) {
6436 // Ensure that each audio and video media section has at most one
6437 // "StreamParams". This will return an error if receiving a session
6438 // description from a "Plan B" endpoint which adds multiple tracks of the
6439 // same type. With Unified Plan, there can only be at most one track per
6440 // media section.
6441 for (const ContentInfo& content : sdesc->description()->contents()) {
6442 const MediaContentDescription& desc = *content.description;
6443 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6444 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6445 desc.streams().size() > 1u) {
6446 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6447 "Media section has more than one track specified "
6448 "with a=ssrc lines which is not supported with "
6449 "Unified Plan.");
6450 }
6451 }
6452 }
6453
Steve Anton8a006912017-12-04 15:25:56 -08006454 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006455}
6456
Steve Anton3828c062017-12-06 10:34:51 -08006457bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006458 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006459 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006460 return (state == PeerConnectionInterface::kStable) ||
6461 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006462 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006463 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006464 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6465 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6466 }
6467}
6468
Steve Anton3828c062017-12-06 10:34:51 -08006469bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006470 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006471 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006472 return (state == PeerConnectionInterface::kStable) ||
6473 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006474 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006475 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006476 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6477 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6478 }
6479}
6480
Steve Antonf8470812017-12-04 10:46:21 -08006481const char* PeerConnection::SessionErrorToString(SessionError error) const {
6482 switch (error) {
6483 case SessionError::kNone:
6484 return "ERROR_NONE";
6485 case SessionError::kContent:
6486 return "ERROR_CONTENT";
6487 case SessionError::kTransport:
6488 return "ERROR_TRANSPORT";
6489 }
6490 RTC_NOTREACHED();
6491 return "";
6492}
6493
Steve Anton75737c02017-11-06 10:37:17 -08006494std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006495 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006496 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6497 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006498 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006499}
6500
Steve Anton8e20f172018-03-06 10:55:04 -08006501void PeerConnection::ReportSdpFormatReceived(
6502 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006503 int num_audio_mlines = 0;
6504 int num_video_mlines = 0;
6505 int num_audio_tracks = 0;
6506 int num_video_tracks = 0;
6507 for (const ContentInfo& content : remote_offer.description()->contents()) {
6508 cricket::MediaType media_type = content.media_description()->type();
6509 int num_tracks = std::max(
6510 1, static_cast<int>(content.media_description()->streams().size()));
6511 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6512 num_audio_mlines += 1;
6513 num_audio_tracks += num_tracks;
6514 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6515 num_video_mlines += 1;
6516 num_video_tracks += num_tracks;
6517 }
6518 }
6519 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6520 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6521 format = kSdpFormatReceivedComplexUnifiedPlan;
6522 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6523 format = kSdpFormatReceivedComplexPlanB;
6524 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6525 format = kSdpFormatReceivedSimple;
6526 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006527 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6528 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006529}
6530
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006531void PeerConnection::NoteUsageEvent(UsageEvent event) {
6532 RTC_DCHECK_RUN_ON(signaling_thread());
6533 usage_event_accumulator_ |= static_cast<int>(event);
6534}
6535
6536void PeerConnection::ReportUsagePattern() const {
6537 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006538 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6539 usage_event_accumulator_,
6540 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006541 const int bad_bits =
6542 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6543 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6544 const int good_bits =
6545 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6546 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6547 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6548 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6549 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006550 // If called after close(), we can't report, because observer may have
6551 // been deallocated, and therefore pointer is null. Write to log instead.
6552 if (observer_) {
6553 Observer()->OnInterestingUsage(usage_event_accumulator_);
6554 } else {
6555 RTC_LOG(LS_INFO) << "Interesting usage signature "
6556 << usage_event_accumulator_
6557 << " observed after observer shutdown";
6558 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006559 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006560}
6561
Steve Anton0ffaaa22018-02-23 10:31:30 -08006562void PeerConnection::ReportNegotiatedSdpSemantics(
6563 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006564 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006565 switch (answer.description()->msid_signaling()) {
6566 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006567 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006568 break;
6569 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006570 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006571 break;
6572 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006573 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006574 break;
6575 case cricket::kMsidSignalingMediaSection |
6576 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006577 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006578 break;
6579 default:
6580 RTC_NOTREACHED();
6581 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006582 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6583 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006584}
6585
Steve Anton75737c02017-11-06 10:37:17 -08006586// We need to check the local/remote description for the Transport instead of
6587// the session, because a new Transport added during renegotiation may have
6588// them unset while the session has them set from the previous negotiation.
6589// Not doing so may trigger the auto generation of transport description and
6590// mess up DTLS identity information, ICE credential, etc.
6591bool PeerConnection::ReadyToUseRemoteCandidate(
6592 const IceCandidateInterface* candidate,
6593 const SessionDescriptionInterface* remote_desc,
6594 bool* valid) {
6595 *valid = true;
6596
6597 const SessionDescriptionInterface* current_remote_desc =
6598 remote_desc ? remote_desc : remote_description();
6599
6600 if (!current_remote_desc) {
6601 return false;
6602 }
6603
6604 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6605 size_t remote_content_size =
6606 current_remote_desc->description()->contents().size();
6607 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006608 RTC_LOG(LS_ERROR)
6609 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6610 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006611
6612 *valid = false;
6613 return false;
6614 }
6615
6616 cricket::ContentInfo content =
6617 current_remote_desc->description()->contents()[mediacontent_index];
6618
6619 const std::string transport_name = GetTransportName(content.name);
6620 if (transport_name.empty()) {
6621 return false;
6622 }
Zhi Huange830e682018-03-30 10:48:35 -07006623 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006624}
6625
6626bool PeerConnection::SrtpRequired() const {
6627 return dtls_enabled_ ||
6628 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6629}
6630
6631void PeerConnection::OnTransportControllerGatheringState(
6632 cricket::IceGatheringState state) {
6633 RTC_DCHECK(signaling_thread()->IsCurrent());
6634 if (state == cricket::kIceGatheringGathering) {
6635 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6636 } else if (state == cricket::kIceGatheringComplete) {
6637 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6638 }
6639}
6640
6641void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006642 std::map<std::string, std::set<cricket::MediaType>>
6643 media_types_by_transport_name;
Mirko Bonadei739baf02019-01-27 17:29:42 +01006644 for (const auto& transceiver : transceivers_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006645 if (transceiver->internal()->channel()) {
6646 const std::string& transport_name =
6647 transceiver->internal()->channel()->transport_name();
6648 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006649 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006650 }
Steve Anton75737c02017-11-06 10:37:17 -08006651 }
6652 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006653 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6654 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006655 }
Zhi Huange830e682018-03-30 10:48:35 -07006656
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006657 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006658 if (transport_name) {
6659 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006660 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006661 }
Zhi Huange830e682018-03-30 10:48:35 -07006662
Steve Antonc7b964c2018-02-01 14:39:45 -08006663 for (const auto& entry : media_types_by_transport_name) {
6664 const std::string& transport_name = entry.first;
6665 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006666 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006667 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006668 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006669 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006670 }
6671 }
6672}
6673// Walk through the ConnectionInfos to gather best connection usage
6674// for IPv4 and IPv6.
6675void PeerConnection::ReportBestConnectionState(
6676 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006677 for (const cricket::TransportChannelStats& channel_stats :
6678 stats.channel_stats) {
6679 for (const cricket::ConnectionInfo& connection_info :
6680 channel_stats.connection_infos) {
6681 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006682 continue;
6683 }
6684
Steve Antonc7b964c2018-02-01 14:39:45 -08006685 const cricket::Candidate& local = connection_info.local_candidate;
6686 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006687
6688 // Increment the counter for IceCandidatePairType.
6689 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6690 (local.type() == RELAY_PORT_TYPE &&
6691 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006692 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6693 GetIceCandidatePairCounter(local, remote),
6694 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006695 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006696 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6697 GetIceCandidatePairCounter(local, remote),
6698 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006699 } else {
6700 RTC_CHECK(0);
6701 }
Steve Anton75737c02017-11-06 10:37:17 -08006702
6703 // Increment the counter for IP type.
6704 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006705 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6706 kBestConnections_IPv4,
6707 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006708 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006709 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6710 kBestConnections_IPv6,
6711 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006712 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006713 RTC_CHECK(!local.address().hostname().empty() &&
6714 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006715 }
6716
6717 return;
6718 }
6719 }
6720}
6721
6722void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006723 const cricket::TransportStats& stats,
6724 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006725 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6726 return;
6727 }
6728
6729 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6730 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6731 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6732 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6733 return;
6734 }
6735
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006736 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6737 for (cricket::MediaType media_type : media_types) {
6738 switch (media_type) {
6739 case cricket::MEDIA_TYPE_AUDIO:
6740 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6741 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6742 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6743 break;
6744 case cricket::MEDIA_TYPE_VIDEO:
6745 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6746 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6747 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6748 break;
6749 case cricket::MEDIA_TYPE_DATA:
6750 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6751 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6752 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6753 break;
6754 default:
6755 RTC_NOTREACHED();
6756 continue;
6757 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006758 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006759 }
6760
6761 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6762 for (cricket::MediaType media_type : media_types) {
6763 switch (media_type) {
6764 case cricket::MEDIA_TYPE_AUDIO:
6765 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6766 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6767 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6768 break;
6769 case cricket::MEDIA_TYPE_VIDEO:
6770 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6771 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6772 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6773 break;
6774 case cricket::MEDIA_TYPE_DATA:
6775 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6776 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6777 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6778 break;
6779 default:
6780 RTC_NOTREACHED();
6781 continue;
6782 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006783 }
Steve Anton75737c02017-11-06 10:37:17 -08006784 }
6785}
6786
6787void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6788 RTC_DCHECK(worker_thread()->IsCurrent());
6789 RTC_DCHECK(call_);
6790 call_->OnSentPacket(sent_packet);
6791}
6792
6793const std::string PeerConnection::GetTransportName(
6794 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006795 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006796 if (channel) {
6797 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006798 }
Steve Anton6fec8802017-12-04 10:37:29 -08006799 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006800 RTC_DCHECK(sctp_mid_);
6801 if (content_name == *sctp_mid_) {
6802 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006803 }
6804 }
6805 // Return an empty string if failed to retrieve the transport name.
6806 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006807}
6808
Steve Anton6fec8802017-12-04 10:37:29 -08006809void PeerConnection::DestroyTransceiverChannel(
6810 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6811 transceiver) {
6812 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006813
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006814 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006815 if (channel) {
6816 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006817 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006818 }
6819}
6820
6821void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006822 if (rtp_data_channel_) {
6823 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006824 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006825 rtp_data_channel_ = nullptr;
6826 }
6827
6828 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6829 // grab a reference to this PeerConnection. If this is called from the
6830 // PeerConnection destructor, the RefCountedObject vtable will have already
6831 // been destroyed (since it is a subclass of PeerConnection) and using
6832 // rtc::Bind will cause "Pure virtual function called" error to appear.
6833
6834 if (sctp_transport_) {
6835 OnDataChannelDestroyed();
6836 network_thread()->Invoke<void>(RTC_FROM_HERE,
6837 [this] { DestroySctpTransport_n(); });
6838 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006839
6840 if (media_transport_) {
6841 OnDataChannelDestroyed();
6842 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6843 RTC_DCHECK_RUN_ON(network_thread());
6844 TeardownMediaTransportForDataChannels_n();
6845 });
6846 }
Steve Anton6fec8802017-12-04 10:37:29 -08006847}
6848
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006849void PeerConnection::DestroyChannelInterface(
6850 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006851 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006852 switch (channel->media_type()) {
6853 case cricket::MEDIA_TYPE_AUDIO:
6854 channel_manager()->DestroyVoiceChannel(
6855 static_cast<cricket::VoiceChannel*>(channel));
6856 break;
6857 case cricket::MEDIA_TYPE_VIDEO:
6858 channel_manager()->DestroyVideoChannel(
6859 static_cast<cricket::VideoChannel*>(channel));
6860 break;
6861 case cricket::MEDIA_TYPE_DATA:
6862 channel_manager()->DestroyRtpDataChannel(
6863 static_cast<cricket::RtpDataChannel*>(channel));
6864 break;
6865 default:
6866 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6867 break;
6868 }
Zhi Huange830e682018-03-30 10:48:35 -07006869}
Steve Anton6fec8802017-12-04 10:37:29 -08006870
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006871bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006872 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006873 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006874 cricket::DtlsTransportInternal* dtls_transport,
6875 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006876 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006877 auto base_channel = GetChannel(mid);
6878 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006879 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006880 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006881 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006882 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006883 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006884
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08006885 if (configuration_.use_media_transport) {
6886 // Only pass media transport to call object if media transport is used
6887 // for media (and not data channel).
6888 call_->MediaTransportChange(media_transport);
6889 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006890
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006891 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006892}
6893
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006894PeerConnectionObserver* PeerConnection::Observer() const {
6895 // In earlier production code, the pointer was not cleared on close,
6896 // which might have led to undefined behavior if the observer was not
6897 // deallocated, or strange crashes if it was.
6898 // We use CHECK in order to catch such behavior if it exists.
6899 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6900 RTC_CHECK(observer_);
6901 return observer_;
6902}
6903
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006904CryptoOptions PeerConnection::GetCryptoOptions() {
6905 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6906 // after it has been removed.
6907 return configuration_.crypto_options.has_value()
6908 ? *configuration_.crypto_options
6909 : factory_->options().crypto_options;
6910}
6911
Harald Alvestrand89061872018-01-02 14:08:34 +01006912void PeerConnection::ClearStatsCache() {
6913 if (stats_collector_) {
6914 stats_collector_->ClearCachedStatsReport();
6915 }
6916}
6917
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006918void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006919 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6920 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006921}
6922
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006923} // namespace webrtc