blob: b90bf2c14695b57dd72722ebbe9f50289932d25d [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2012, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/app/webrtc/webrtcsession.h"
29
pbos@webrtc.org371243d2014-03-07 15:22:04 +000030#include <limits.h>
31
henrike@webrtc.org28e20752013-07-10 00:45:36 +000032#include <algorithm>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000033#include <vector>
34
35#include "talk/app/webrtc/jsepicecandidate.h"
36#include "talk/app/webrtc/jsepsessiondescription.h"
37#include "talk/app/webrtc/mediaconstraintsinterface.h"
38#include "talk/app/webrtc/mediastreamsignaling.h"
39#include "talk/app/webrtc/peerconnectioninterface.h"
wu@webrtc.org91053e72013-08-10 07:18:04 +000040#include "talk/app/webrtc/webrtcsessiondescriptionfactory.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000041#include "talk/media/base/constants.h"
42#include "talk/media/base/videocapturer.h"
43#include "talk/session/media/channel.h"
44#include "talk/session/media/channelmanager.h"
45#include "talk/session/media/mediasession.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000046#include "webrtc/base/basictypes.h"
47#include "webrtc/base/helpers.h"
48#include "webrtc/base/logging.h"
49#include "webrtc/base/stringencode.h"
50#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051
52using cricket::ContentInfo;
53using cricket::ContentInfos;
54using cricket::MediaContentDescription;
55using cricket::SessionDescription;
56using cricket::TransportInfo;
57
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058namespace webrtc {
59
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060// Error messages
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000061const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
62 "is enabled.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000063const char kCreateChannelFailed[] = "Failed to create channels.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064const char kInvalidCandidates[] = "Description contains invalid candidates.";
65const char kInvalidSdp[] = "Invalid session description.";
66const char kMlineMismatch[] =
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000067 "Offer and answer descriptions m-lines are not matching. Rejecting answer.";
68const char kPushDownTDFailed[] =
69 "Failed to push down transport description:";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000070const char kSdpWithoutDtlsFingerprint[] =
71 "Called with SDP without DTLS fingerprint.";
72const char kSdpWithoutSdesCrypto[] =
73 "Called with SDP without SDES crypto.";
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +000074const char kSdpWithoutIceUfragPwd[] =
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000075 "Called with SDP without ice-ufrag and ice-pwd.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076const char kSessionError[] = "Session error code: ";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000077const char kSessionErrorDesc[] = "Session error description: ";
buildbot@webrtc.org53df88c2014-08-07 22:46:01 +000078const int kMaxUnsignalledRecvStreams = 20;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000079
80// Compares |answer| against |offer|. Comparision is done
81// for number of m-lines in answer against offer. If matches true will be
82// returned otherwise false.
83static bool VerifyMediaDescriptions(
84 const SessionDescription* answer, const SessionDescription* offer) {
85 if (offer->contents().size() != answer->contents().size())
86 return false;
87
88 for (size_t i = 0; i < offer->contents().size(); ++i) {
89 if ((offer->contents()[i].name) != answer->contents()[i].name) {
90 return false;
91 }
wu@webrtc.org4e393072014-04-07 17:04:35 +000092 const MediaContentDescription* offer_mdesc =
93 static_cast<const MediaContentDescription*>(
94 offer->contents()[i].description);
95 const MediaContentDescription* answer_mdesc =
96 static_cast<const MediaContentDescription*>(
97 answer->contents()[i].description);
98 if (offer_mdesc->type() != answer_mdesc->type()) {
99 return false;
100 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101 }
102 return true;
103}
104
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105// Checks that each non-rejected content has SDES crypto keys or a DTLS
106// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
107// keys, will be caught in Transport negotiation, and backstopped by Channel's
108// |secure_required| check.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000109static bool VerifyCrypto(const SessionDescription* desc,
110 bool dtls_enabled,
111 std::string* error) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 const ContentInfos& contents = desc->contents();
113 for (size_t index = 0; index < contents.size(); ++index) {
114 const ContentInfo* cinfo = &contents[index];
115 if (cinfo->rejected) {
116 continue;
117 }
118
119 // If the content isn't rejected, crypto must be present.
120 const MediaContentDescription* media =
121 static_cast<const MediaContentDescription*>(cinfo->description);
122 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
123 if (!media || !tinfo) {
124 // Something is not right.
125 LOG(LS_ERROR) << kInvalidSdp;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000126 *error = kInvalidSdp;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000127 return false;
128 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000129 if (dtls_enabled) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000130 if (!tinfo->description.identity_fingerprint) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000131 LOG(LS_WARNING) <<
132 "Session description must have DTLS fingerprint if DTLS enabled.";
133 *error = kSdpWithoutDtlsFingerprint;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000134 return false;
135 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000136 } else {
137 if (media->cryptos().empty()) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000138 LOG(LS_WARNING) <<
139 "Session description must have SDES when DTLS disabled.";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000140 *error = kSdpWithoutSdesCrypto;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000141 return false;
142 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000143 }
144 }
145
146 return true;
147}
148
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +0000149// Checks that each non-rejected content has ice-ufrag and ice-pwd set.
150static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
151 const ContentInfos& contents = desc->contents();
152 for (size_t index = 0; index < contents.size(); ++index) {
153 const ContentInfo* cinfo = &contents[index];
154 if (cinfo->rejected) {
155 continue;
156 }
157
158 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
159 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
160 if (!tinfo) {
161 // Something is not right.
162 LOG(LS_ERROR) << kInvalidSdp;
163 return false;
164 }
165 if (tinfo->description.ice_ufrag.empty() ||
166 tinfo->description.ice_pwd.empty()) {
167 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
168 return false;
169 }
170 }
171 return true;
172}
173
wu@webrtc.org91053e72013-08-10 07:18:04 +0000174// Forces |sdesc->crypto_required| to the appropriate state based on the
175// current security policy, to ensure a failure occurs if there is an error
176// in crypto negotiation.
177// Called when processing the local session description.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000178static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
179 SessionDescription* sdesc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000180 if (!sdesc) {
181 return;
182 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000183
wu@webrtc.org91053e72013-08-10 07:18:04 +0000184 // Updating the |crypto_required_| in MediaContentDescription to the
185 // appropriate state based on the current security policy.
186 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
187 iter != sdesc->contents().end(); ++iter) {
188 if (cricket::IsMediaContent(&*iter)) {
189 MediaContentDescription* mdesc =
190 static_cast<MediaContentDescription*> (iter->description);
191 if (mdesc) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000192 mdesc->set_crypto_required(type);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000193 }
194 }
195 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000196}
197
198static bool GetAudioSsrcByTrackId(
199 const SessionDescription* session_description,
200 const std::string& track_id, uint32 *ssrc) {
201 const cricket::ContentInfo* audio_info =
202 cricket::GetFirstAudioContent(session_description);
203 if (!audio_info) {
204 LOG(LS_ERROR) << "Audio not used in this call";
205 return false;
206 }
207
208 const cricket::MediaContentDescription* audio_content =
209 static_cast<const cricket::MediaContentDescription*>(
210 audio_info->description);
211 cricket::StreamParams stream;
212 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
213 &stream)) {
214 return false;
215 }
216 *ssrc = stream.first_ssrc();
217 return true;
218}
219
220static bool GetTrackIdBySsrc(const SessionDescription* session_description,
221 uint32 ssrc, std::string* track_id) {
222 ASSERT(track_id != NULL);
223
224 cricket::StreamParams stream_out;
225 const cricket::ContentInfo* audio_info =
226 cricket::GetFirstAudioContent(session_description);
227 if (!audio_info) {
228 return false;
229 }
230 const cricket::MediaContentDescription* audio_content =
231 static_cast<const cricket::MediaContentDescription*>(
232 audio_info->description);
233
234 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
235 *track_id = stream_out.id;
236 return true;
237 }
238
239 const cricket::ContentInfo* video_info =
240 cricket::GetFirstVideoContent(session_description);
241 if (!video_info) {
242 return false;
243 }
244 const cricket::MediaContentDescription* video_content =
245 static_cast<const cricket::MediaContentDescription*>(
246 video_info->description);
247
248 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
249 *track_id = stream_out.id;
250 return true;
251 }
252 return false;
253}
254
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000255static bool BadSdp(const std::string& source,
256 const std::string& type,
257 const std::string& reason,
258 std::string* err_desc) {
259 std::ostringstream desc;
260 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
261
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262 if (err_desc) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000263 *err_desc = desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000265 LOG(LS_ERROR) << desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266 return false;
267}
268
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000269static bool BadSdp(cricket::ContentSource source,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000270 const std::string& type,
271 const std::string& reason,
272 std::string* err_desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000273 if (source == cricket::CS_LOCAL) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000274 return BadSdp("local", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275 } else {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000276 return BadSdp("remote", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000277 }
278}
279
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000280static bool BadLocalSdp(const std::string& type,
281 const std::string& reason,
282 std::string* err_desc) {
283 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
284}
285
286static bool BadRemoteSdp(const std::string& type,
287 const std::string& reason,
288 std::string* err_desc) {
289 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
290}
291
292static bool BadOfferSdp(cricket::ContentSource source,
293 const std::string& reason,
294 std::string* err_desc) {
295 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
296}
297
298static bool BadPranswerSdp(cricket::ContentSource source,
299 const std::string& reason,
300 std::string* err_desc) {
301 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
302 reason, err_desc);
303}
304
305static bool BadAnswerSdp(cricket::ContentSource source,
306 const std::string& reason,
307 std::string* err_desc) {
308 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000309}
310
311#define GET_STRING_OF_STATE(state) \
312 case cricket::BaseSession::state: \
313 result = #state; \
314 break;
315
316static std::string GetStateString(cricket::BaseSession::State state) {
317 std::string result;
318 switch (state) {
319 GET_STRING_OF_STATE(STATE_INIT)
320 GET_STRING_OF_STATE(STATE_SENTINITIATE)
321 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
322 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
323 GET_STRING_OF_STATE(STATE_SENTACCEPT)
324 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
325 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
326 GET_STRING_OF_STATE(STATE_SENTMODIFY)
327 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
328 GET_STRING_OF_STATE(STATE_SENTREJECT)
329 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
330 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
331 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
332 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
333 GET_STRING_OF_STATE(STATE_INPROGRESS)
334 GET_STRING_OF_STATE(STATE_DEINIT)
335 default:
336 ASSERT(false);
337 break;
338 }
339 return result;
340}
341
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000342#define GET_STRING_OF_ERROR_CODE(err) \
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000343 case cricket::BaseSession::err: \
344 result = #err; \
345 break;
346
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000347static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000348 std::string result;
349 switch (err) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000350 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
351 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
352 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
353 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
354 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
355 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356 default:
357 ASSERT(false);
358 break;
359 }
360 return result;
361}
362
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000363static std::string MakeErrorString(const std::string& error,
364 const std::string& desc) {
365 std::ostringstream ret;
366 ret << error << " " << desc;
367 return ret.str();
368}
369
370static std::string MakeTdErrorString(const std::string& desc) {
371 return MakeErrorString(kPushDownTDFailed, desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000372}
373
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000374// Set |option| to the highest-priority value of |key| in the optional
375// constraints if the key is found and has a valid value.
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000376template<typename T>
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000377static void SetOptionFromOptionalConstraint(
378 const MediaConstraintsInterface* constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000379 const std::string& key, cricket::Settable<T>* option) {
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000380 if (!constraints) {
381 return;
382 }
383 std::string string_value;
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000384 T value;
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000385 if (constraints->GetOptional().FindFirst(key, &string_value)) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000386 if (rtc::FromString(string_value, &value)) {
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000387 option->Set(value);
388 }
389 }
390}
391
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000392// Help class used to remember if a a remote peer has requested ice restart by
393// by sending a description with new ice ufrag and password.
394class IceRestartAnswerLatch {
395 public:
396 IceRestartAnswerLatch() : ice_restart_(false) { }
397
wu@webrtc.org91053e72013-08-10 07:18:04 +0000398 // Returns true if CheckForRemoteIceRestart has been called with a new session
399 // description where ice password and ufrag has changed since last time
400 // Reset() was called.
401 bool Get() const {
402 return ice_restart_;
403 }
404
405 void Reset() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000406 if (ice_restart_) {
407 ice_restart_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000408 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000409 }
410
411 void CheckForRemoteIceRestart(
412 const SessionDescriptionInterface* old_desc,
413 const SessionDescriptionInterface* new_desc) {
414 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
415 return;
416 }
417 const SessionDescription* new_sd = new_desc->description();
418 const SessionDescription* old_sd = old_desc->description();
419 const ContentInfos& contents = new_sd->contents();
420 for (size_t index = 0; index < contents.size(); ++index) {
421 const ContentInfo* cinfo = &contents[index];
422 if (cinfo->rejected) {
423 continue;
424 }
425 // If the content isn't rejected, check if ufrag and password has
426 // changed.
427 const cricket::TransportDescription* new_transport_desc =
428 new_sd->GetTransportDescriptionByName(cinfo->name);
429 const cricket::TransportDescription* old_transport_desc =
430 old_sd->GetTransportDescriptionByName(cinfo->name);
431 if (!new_transport_desc || !old_transport_desc) {
432 // No transport description exist. This is not an ice restart.
433 continue;
434 }
jiayl@webrtc.orgdb397e52014-06-20 16:32:09 +0000435 if (cricket::IceCredentialsChanged(old_transport_desc->ice_ufrag,
436 old_transport_desc->ice_pwd,
437 new_transport_desc->ice_ufrag,
438 new_transport_desc->ice_pwd)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000439 LOG(LS_INFO) << "Remote peer request ice restart.";
440 ice_restart_ = true;
441 break;
442 }
443 }
444 }
445
446 private:
447 bool ice_restart_;
448};
449
wu@webrtc.org91053e72013-08-10 07:18:04 +0000450WebRtcSession::WebRtcSession(
451 cricket::ChannelManager* channel_manager,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000452 rtc::Thread* signaling_thread,
453 rtc::Thread* worker_thread,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000454 cricket::PortAllocator* port_allocator,
455 MediaStreamSignaling* mediastream_signaling)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000456 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000457 rtc::ToString(rtc::CreateRandomId64() &
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000458 LLONG_MAX),
459 cricket::NS_JINGLE_RTP, false),
460 // RFC 3264: The numeric value of the session id and version in the
461 // o line MUST be representable with a "64 bit signed integer".
462 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
463 channel_manager_(channel_manager),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000464 mediastream_signaling_(mediastream_signaling),
465 ice_observer_(NULL),
466 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000467 older_version_remote_peer_(false),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000468 dtls_enabled_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000469 data_channel_type_(cricket::DCT_NONE),
470 ice_restart_latch_(new IceRestartAnswerLatch) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000471}
472
473WebRtcSession::~WebRtcSession() {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +0000474 // Destroy video_channel_ first since it may have a pointer to the
475 // voice_channel_.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000476 if (video_channel_.get()) {
477 SignalVideoChannelDestroyed();
478 channel_manager_->DestroyVideoChannel(video_channel_.release());
479 }
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +0000480 if (voice_channel_.get()) {
481 SignalVoiceChannelDestroyed();
482 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
483 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000484 if (data_channel_.get()) {
485 SignalDataChannelDestroyed();
486 channel_manager_->DestroyDataChannel(data_channel_.release());
487 }
488 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
489 delete saved_candidates_[i];
490 }
491 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000492}
493
wu@webrtc.org91053e72013-08-10 07:18:04 +0000494bool WebRtcSession::Initialize(
wu@webrtc.org97077a32013-10-25 21:18:33 +0000495 const PeerConnectionFactoryInterface::Options& options,
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000496 const MediaConstraintsInterface* constraints,
497 DTLSIdentityServiceInterface* dtls_identity_service,
498 PeerConnectionInterface::IceTransportsType ice_transport) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000499 // TODO(perkj): Take |constraints| into consideration. Return false if not all
500 // mandatory constraints can be fulfilled. Note that |constraints|
501 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000502 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000503
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000504 if (options.disable_encryption) {
505 dtls_enabled_ = false;
506 } else {
507 // Enable DTLS by default if |dtls_identity_service| is valid.
508 dtls_enabled_ = (dtls_identity_service != NULL);
509 // |constraints| can override the default |dtls_enabled_| value.
510 if (FindConstraint(
511 constraints,
512 MediaConstraintsInterface::kEnableDtlsSrtp,
513 &value, NULL)) {
514 dtls_enabled_ = value;
515 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000516 }
517
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000518 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000519 // It takes precendence over the disable_sctp_data_channels
520 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000521 if (FindConstraint(
522 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
523 &value, NULL) && value) {
524 LOG(LS_INFO) << "Allowing RTP data engine.";
525 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000526 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000527 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000528 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000529 LOG(LS_INFO) << "Allowing SCTP data engine.";
530 data_channel_type_ = cricket::DCT_SCTP;
531 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000532 }
533 if (data_channel_type_ != cricket::DCT_NONE) {
534 mediastream_signaling_->SetDataChannelFactory(this);
535 }
536
wu@webrtc.orgde305012013-10-31 15:40:38 +0000537 // Find DSCP constraint.
538 if (FindConstraint(
539 constraints,
540 MediaConstraintsInterface::kEnableDscp,
541 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000542 audio_options_.dscp.Set(value);
543 video_options_.dscp.Set(value);
544 }
545
546 // Find Suspend Below Min Bitrate constraint.
547 if (FindConstraint(
548 constraints,
549 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
550 &value,
551 NULL)) {
552 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000553 }
554
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000555 SetOptionFromOptionalConstraint(constraints,
556 MediaConstraintsInterface::kScreencastMinBitrate,
557 &video_options_.screencast_min_bitrate);
558
559 // Find constraints for cpu overuse detection.
560 SetOptionFromOptionalConstraint(constraints,
561 MediaConstraintsInterface::kCpuUnderuseThreshold,
562 &video_options_.cpu_underuse_threshold);
563 SetOptionFromOptionalConstraint(constraints,
564 MediaConstraintsInterface::kCpuOveruseThreshold,
565 &video_options_.cpu_overuse_threshold);
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000566 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000567 MediaConstraintsInterface::kCpuOveruseDetection,
568 &video_options_.cpu_overuse_detection);
569 SetOptionFromOptionalConstraint(constraints,
570 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
571 &video_options_.cpu_overuse_encode_usage);
572 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000573 MediaConstraintsInterface::kCpuUnderuseEncodeRsdThreshold,
574 &video_options_.cpu_underuse_encode_rsd_threshold);
575 SetOptionFromOptionalConstraint(constraints,
576 MediaConstraintsInterface::kCpuOveruseEncodeRsdThreshold,
577 &video_options_.cpu_overuse_encode_rsd_threshold);
buildbot@webrtc.orgdb563902014-06-13 13:05:48 +0000578
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000579 // Find payload padding constraint.
580 SetOptionFromOptionalConstraint(constraints,
581 MediaConstraintsInterface::kPayloadPadding,
582 &video_options_.use_payload_padding);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000583
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000584 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org53df88c2014-08-07 22:46:01 +0000585 MediaConstraintsInterface::kNumUnsignalledRecvStreams,
586 &video_options_.unsignalled_recv_stream_limit);
587 if (video_options_.unsignalled_recv_stream_limit.IsSet()) {
588 int stream_limit;
589 video_options_.unsignalled_recv_stream_limit.Get(&stream_limit);
590 stream_limit = rtc::_min(kMaxUnsignalledRecvStreams, stream_limit);
591 stream_limit = rtc::_max(0, stream_limit);
592 video_options_.unsignalled_recv_stream_limit.Set(stream_limit);
593 }
594
595 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000596 MediaConstraintsInterface::kHighStartBitrate,
597 &video_options_.video_start_bitrate);
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000598
599 if (FindConstraint(
600 constraints,
601 MediaConstraintsInterface::kVeryHighBitrate,
602 &value,
603 NULL)) {
604 video_options_.video_highest_bitrate.Set(
605 cricket::VideoOptions::VERY_HIGH);
606 } else if (FindConstraint(
607 constraints,
608 MediaConstraintsInterface::kHighBitrate,
609 &value,
610 NULL)) {
611 video_options_.video_highest_bitrate.Set(
612 cricket::VideoOptions::HIGH);
613 }
614
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +0000615 SetOptionFromOptionalConstraint(constraints,
616 MediaConstraintsInterface::kCombinedAudioVideoBwe,
617 &audio_options_.combined_audio_video_bwe);
618
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000619 const cricket::VideoCodec default_codec(
620 JsepSessionDescription::kDefaultVideoCodecId,
621 JsepSessionDescription::kDefaultVideoCodecName,
622 JsepSessionDescription::kMaxVideoCodecWidth,
623 JsepSessionDescription::kMaxVideoCodecHeight,
624 JsepSessionDescription::kDefaultVideoCodecFramerate,
625 JsepSessionDescription::kDefaultVideoCodecPreference);
626 channel_manager_->SetDefaultVideoEncoderConfig(
627 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000628
629 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
630 signaling_thread(),
631 channel_manager_,
632 mediastream_signaling_,
633 dtls_identity_service,
634 this,
635 id(),
636 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000637 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000638
639 webrtc_session_desc_factory_->SignalIdentityReady.connect(
640 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000641
wu@webrtc.org97077a32013-10-25 21:18:33 +0000642 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000643 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000644 }
645
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000646 return true;
647}
648
649void WebRtcSession::Terminate() {
650 SetState(STATE_RECEIVEDTERMINATE);
651 RemoveUnusedChannelsAndTransports(NULL);
652 ASSERT(voice_channel_.get() == NULL);
653 ASSERT(video_channel_.get() == NULL);
654 ASSERT(data_channel_.get() == NULL);
655}
656
657bool WebRtcSession::StartCandidatesAllocation() {
658 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
659 // from TransportProxy to start gathering ice candidates.
660 SpeculativelyConnectAllTransportChannels();
661 if (!saved_candidates_.empty()) {
662 // If there are saved candidates which arrived before local description is
663 // set, copy those to remote description.
664 CopySavedCandidates(remote_desc_.get());
665 }
666 // Push remote candidates present in remote description to transport channels.
667 UseCandidatesInSessionDescription(remote_desc_.get());
668 return true;
669}
670
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000671void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
672 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000673}
674
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000675cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
676 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000677}
678
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000679bool WebRtcSession::GetSslRole(rtc::SSLRole* role) {
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000680 if (local_description() == NULL || remote_description() == NULL) {
681 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
682 << "SSL Role of the session.";
683 return false;
684 }
685
686 // TODO(mallinath) - Return role of each transport, as role may differ from
687 // one another.
688 // In current implementaion we just return the role of first transport in the
689 // transport map.
690 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
691 iter != transport_proxies().end(); ++iter) {
692 if (iter->second->impl()) {
693 return iter->second->impl()->GetSslRole(role);
694 }
695 }
696 return false;
697}
698
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000699void WebRtcSession::CreateOffer(
700 CreateSessionDescriptionObserver* observer,
701 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
702 webrtc_session_desc_factory_->CreateOffer(observer, options);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000703}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704
wu@webrtc.org91053e72013-08-10 07:18:04 +0000705void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
706 const MediaConstraintsInterface* constraints) {
707 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708}
709
710bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
711 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000712 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000713 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000714
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000715 // Validate SDP.
716 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
717 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718 }
719
720 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000721 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 if (state() == STATE_INIT && action == kOffer) {
723 set_initiator(true);
724 }
725
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000726 cricket::SecurePolicy sdes_policy =
727 webrtc_session_desc_factory_->SdesPolicy();
728 cricket::CryptoType crypto_required = dtls_enabled_ ?
729 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
730 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000732 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733
734 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000735 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736
737 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000738 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000739 // TODO(mallinath) - Handle CreateChannel failure, as new local description
740 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000741 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742 }
743
744 // Remove channel and transport proxies, if MediaContentDescription is
745 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000746 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000748 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749 return false;
750 }
751 // Kick starting the ice candidates allocation.
752 StartCandidatesAllocation();
753
754 // Update state and SSRC of local MediaStreams and DataChannels based on the
755 // local session description.
756 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
757
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000758 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000759 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
760 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
761 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000763 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764 }
765 return true;
766}
767
768bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
769 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000770 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000771 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000772
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000773 // Validate SDP.
774 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
775 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000776 }
777
778 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000779 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780 if (action == kOffer && !CreateChannels(desc->description())) {
781 // TODO(mallinath) - Handle CreateChannel failure, as new local description
782 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000783 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000784 }
785
786 // Remove channel and transport proxies, if MediaContentDescription is
787 // rejected.
788 RemoveUnusedChannelsAndTransports(desc->description());
789
790 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
791 // is called.
792 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000793 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794 return false;
795 }
796
797 // Update remote MediaStreams.
798 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
799 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000800 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000801 }
802
803 // Copy all saved candidates.
804 CopySavedCandidates(desc);
805 // We retain all received candidates.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000806 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
807 remote_desc_.get(), desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808 // Check if this new SessionDescription contains new ice ufrag and password
809 // that indicates the remote peer requests ice restart.
810 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
811 desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000812 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000813
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000814 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000815 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
816 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
817 }
818
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000820 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 }
822 return true;
823}
824
825bool WebRtcSession::UpdateSessionState(
826 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 std::string* err_desc) {
828 // If there's already a pending error then no state transition should happen.
829 // But all call-sites should be verifying this before calling us!
830 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000831 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000833 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
834 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 }
836 SetState(source == cricket::CS_LOCAL ?
837 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
838 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000839 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840 }
841 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000842 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
843 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000844 }
845 EnableChannels();
846 SetState(source == cricket::CS_LOCAL ?
847 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
848 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000849 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850 }
851 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000852 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
853 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000854 }
855 MaybeEnableMuxingSupport();
856 EnableChannels();
857 SetState(source == cricket::CS_LOCAL ?
858 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
859 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000860 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000861 }
862 }
863 return true;
864}
865
866WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
867 if (type == SessionDescriptionInterface::kOffer) {
868 return WebRtcSession::kOffer;
869 } else if (type == SessionDescriptionInterface::kPrAnswer) {
870 return WebRtcSession::kPrAnswer;
871 } else if (type == SessionDescriptionInterface::kAnswer) {
872 return WebRtcSession::kAnswer;
873 }
874 ASSERT(false && "unknown action type");
875 return WebRtcSession::kOffer;
876}
877
878bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
879 if (state() == STATE_INIT) {
880 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
881 << "without any offer (local or remote) "
882 << "session description.";
883 return false;
884 }
885
886 if (!candidate) {
887 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
888 return false;
889 }
890
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +0000891 bool valid = false;
892 if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
893 if (valid) {
894 LOG(LS_INFO) << "ProcessIceMessage: Candidate saved";
895 saved_candidates_.push_back(
896 new JsepIceCandidate(candidate->sdp_mid(),
897 candidate->sdp_mline_index(),
898 candidate->candidate()));
buildbot@webrtc.org61c1b8e2014-04-09 06:06:38 +0000899 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +0000900 return valid;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901 }
902
903 // Add this candidate to the remote session description.
904 if (!remote_desc_->AddCandidate(candidate)) {
905 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
906 return false;
907 }
908
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000909 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910}
911
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000912bool WebRtcSession::UpdateIce(PeerConnectionInterface::IceTransportsType type) {
913 return false;
914}
915
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000916bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 if (!BaseSession::local_description())
918 return false;
919 return webrtc::GetTrackIdBySsrc(
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000920 BaseSession::local_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921}
922
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000923bool WebRtcSession::GetRemoteTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924 if (!BaseSession::remote_description())
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000925 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926 return webrtc::GetTrackIdBySsrc(
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000927 BaseSession::remote_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928}
929
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000930std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000932 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933 return desc.str();
934}
935
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000936void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
937 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 ASSERT(signaling_thread()->IsCurrent());
939 if (!voice_channel_) {
940 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
941 return;
942 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000943 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
944 // SetRenderer() can fail if the ssrc does not match any playout channel.
945 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
946 return;
947 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
949 // Allow that SetOutputScaling fail if |enable| is false but assert
950 // otherwise. This in the normal case when the underlying media channel has
951 // already been deleted.
952 ASSERT(enable == false);
953 }
954}
955
956void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000957 const cricket::AudioOptions& options,
958 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959 ASSERT(signaling_thread()->IsCurrent());
960 if (!voice_channel_) {
961 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
962 return;
963 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000964 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
965 // SetRenderer() can fail if the ssrc does not match any send channel.
966 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
967 return;
968 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 if (!voice_channel_->MuteStream(ssrc, !enable)) {
970 // Allow that MuteStream fail if |enable| is false but assert otherwise.
971 // This in the normal case when the underlying media channel has already
972 // been deleted.
973 ASSERT(enable == false);
974 return;
975 }
976 if (enable)
977 voice_channel_->SetChannelOptions(options);
978}
979
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000980void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
981 ASSERT(signaling_thread()->IsCurrent());
982 ASSERT(volume >= 0 && volume <= 10);
983 if (!voice_channel_) {
984 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
985 return;
986 }
987
988 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
989 ASSERT(false);
990}
991
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
993 cricket::VideoCapturer* camera) {
994 ASSERT(signaling_thread()->IsCurrent());
995
996 if (!video_channel_.get()) {
997 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
998 // support video.
999 LOG(LS_WARNING) << "Video not used in this call.";
1000 return false;
1001 }
1002 if (!video_channel_->SetCapturer(ssrc, camera)) {
1003 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1004 // This in the normal case when the underlying media channel has already
1005 // been deleted.
1006 ASSERT(camera == NULL);
1007 return false;
1008 }
1009 return true;
1010}
1011
1012void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1013 bool enable,
1014 cricket::VideoRenderer* renderer) {
1015 ASSERT(signaling_thread()->IsCurrent());
1016 if (!video_channel_) {
1017 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1018 return;
1019 }
1020 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1021 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1022 // This in the normal case when the underlying media channel has already
1023 // been deleted.
1024 ASSERT(renderer == NULL);
1025 }
1026}
1027
1028void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1029 const cricket::VideoOptions* options) {
1030 ASSERT(signaling_thread()->IsCurrent());
1031 if (!video_channel_) {
1032 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1033 return;
1034 }
1035 if (!video_channel_->MuteStream(ssrc, !enable)) {
1036 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1037 // This in the normal case when the underlying media channel has already
1038 // been deleted.
1039 ASSERT(enable == false);
1040 return;
1041 }
1042 if (enable && options)
1043 video_channel_->SetChannelOptions(*options);
1044}
1045
1046bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1047 ASSERT(signaling_thread()->IsCurrent());
1048 if (!voice_channel_) {
1049 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1050 return false;
1051 }
1052 uint32 send_ssrc = 0;
1053 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1054 // exists.
1055 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1056 &send_ssrc)) {
1057 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1058 return false;
1059 }
1060 return voice_channel_->CanInsertDtmf();
1061}
1062
1063bool WebRtcSession::InsertDtmf(const std::string& track_id,
1064 int code, int duration) {
1065 ASSERT(signaling_thread()->IsCurrent());
1066 if (!voice_channel_) {
1067 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1068 return false;
1069 }
1070 uint32 send_ssrc = 0;
1071 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1072 track_id, &send_ssrc))) {
1073 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1074 return false;
1075 }
1076 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1077 cricket::DF_SEND)) {
1078 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1079 return false;
1080 }
1081 return true;
1082}
1083
1084sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1085 return &SignalVoiceChannelDestroyed;
1086}
1087
wu@webrtc.org78187522013-10-07 23:32:02 +00001088bool WebRtcSession::SendData(const cricket::SendDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001089 const rtc::Buffer& payload,
wu@webrtc.org78187522013-10-07 23:32:02 +00001090 cricket::SendDataResult* result) {
1091 if (!data_channel_.get()) {
1092 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1093 return false;
1094 }
1095 return data_channel_->SendData(params, payload, result);
1096}
1097
1098bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1099 if (!data_channel_.get()) {
1100 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1101 return false;
1102 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001103 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1104 &DataChannel::OnChannelReady);
1105 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1106 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001107 return true;
1108}
1109
1110void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001111 if (!data_channel_.get()) {
1112 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1113 return;
1114 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001115 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1116 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1117}
1118
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001119void WebRtcSession::AddSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001120 if (!data_channel_.get()) {
1121 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1122 return;
1123 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001124 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1125 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001126}
1127
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001128void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
jiayl@webrtc.org2eaac182014-06-17 16:02:46 +00001129 mediastream_signaling_->RemoveSctpDataChannel(static_cast<int>(sid));
1130
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001131 if (!data_channel_.get()) {
1132 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1133 << "NULL.";
1134 return;
1135 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001136 data_channel_->RemoveRecvStream(sid);
1137 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001138}
1139
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001140bool WebRtcSession::ReadyToSendData() const {
1141 return data_channel_.get() && data_channel_->ready_to_send_data();
1142}
1143
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001144rtc::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001145 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001146 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147 if (state() == STATE_RECEIVEDTERMINATE) {
1148 return NULL;
1149 }
1150 if (data_channel_type_ == cricket::DCT_NONE) {
1151 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1152 return NULL;
1153 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001154 InternalDataChannelInit new_config =
1155 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156 if (data_channel_type_ == cricket::DCT_SCTP) {
1157 if (new_config.id < 0) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001158 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001159 if (GetSslRole(&role) &&
1160 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001161 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1162 return NULL;
1163 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001164 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1166 << "because the id is already in use or out of range.";
1167 return NULL;
1168 }
1169 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001170
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001171 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001172 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001173 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001175
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001176 return channel;
1177}
1178
1179cricket::DataChannelType WebRtcSession::data_channel_type() const {
1180 return data_channel_type_;
1181}
1182
wu@webrtc.org91053e72013-08-10 07:18:04 +00001183bool WebRtcSession::IceRestartPending() const {
1184 return ice_restart_latch_->Get();
1185}
1186
1187void WebRtcSession::ResetIceRestartLatch() {
1188 ice_restart_latch_->Reset();
1189}
1190
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001191void WebRtcSession::OnIdentityReady(rtc::SSLIdentity* identity) {
wu@webrtc.org91053e72013-08-10 07:18:04 +00001192 SetIdentity(identity);
1193}
1194
1195bool WebRtcSession::waiting_for_identity() const {
1196 return webrtc_session_desc_factory_->waiting_for_identity();
1197}
1198
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001199void WebRtcSession::SetIceConnectionState(
1200 PeerConnectionInterface::IceConnectionState state) {
1201 if (ice_connection_state_ == state) {
1202 return;
1203 }
1204
1205 // ASSERT that the requested transition is allowed. Note that
1206 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1207 // within PeerConnection). This switch statement should compile away when
1208 // ASSERTs are disabled.
1209 switch (ice_connection_state_) {
1210 case PeerConnectionInterface::kIceConnectionNew:
1211 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1212 break;
1213 case PeerConnectionInterface::kIceConnectionChecking:
1214 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1215 state == PeerConnectionInterface::kIceConnectionConnected);
1216 break;
1217 case PeerConnectionInterface::kIceConnectionConnected:
1218 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1219 state == PeerConnectionInterface::kIceConnectionChecking ||
1220 state == PeerConnectionInterface::kIceConnectionCompleted);
1221 break;
1222 case PeerConnectionInterface::kIceConnectionCompleted:
1223 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1224 state == PeerConnectionInterface::kIceConnectionDisconnected);
1225 break;
1226 case PeerConnectionInterface::kIceConnectionFailed:
1227 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1228 break;
1229 case PeerConnectionInterface::kIceConnectionDisconnected:
1230 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1231 state == PeerConnectionInterface::kIceConnectionConnected ||
1232 state == PeerConnectionInterface::kIceConnectionCompleted ||
1233 state == PeerConnectionInterface::kIceConnectionFailed);
1234 break;
1235 case PeerConnectionInterface::kIceConnectionClosed:
1236 ASSERT(false);
1237 break;
1238 default:
1239 ASSERT(false);
1240 break;
1241 }
1242
1243 ice_connection_state_ = state;
1244 if (ice_observer_) {
1245 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1246 }
1247}
1248
1249void WebRtcSession::OnTransportRequestSignaling(
1250 cricket::Transport* transport) {
1251 ASSERT(signaling_thread()->IsCurrent());
1252 transport->OnSignalingReady();
1253 if (ice_observer_) {
1254 ice_observer_->OnIceGatheringChange(
1255 PeerConnectionInterface::kIceGatheringGathering);
1256 }
1257}
1258
1259void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1260 ASSERT(signaling_thread()->IsCurrent());
1261 // start monitoring for the write state of the transport.
1262 OnTransportWritable(transport);
1263}
1264
1265void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1266 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001268 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001269 } else if (transport->HasChannels()) {
1270 // If the current state is Connected or Completed, then there were writable
1271 // channels but now there are not, so the next state must be Disconnected.
1272 if (ice_connection_state_ ==
1273 PeerConnectionInterface::kIceConnectionConnected ||
1274 ice_connection_state_ ==
1275 PeerConnectionInterface::kIceConnectionCompleted) {
1276 SetIceConnectionState(
1277 PeerConnectionInterface::kIceConnectionDisconnected);
1278 }
1279 }
1280}
1281
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001282void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1283 ASSERT(signaling_thread()->IsCurrent());
1284 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1285}
1286
1287void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1288 ASSERT(signaling_thread()->IsCurrent());
1289 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1290}
1291
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001292void WebRtcSession::OnTransportProxyCandidatesReady(
1293 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1294 ASSERT(signaling_thread()->IsCurrent());
1295 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1296}
1297
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001298void WebRtcSession::OnCandidatesAllocationDone() {
1299 ASSERT(signaling_thread()->IsCurrent());
1300 if (ice_observer_) {
1301 ice_observer_->OnIceGatheringChange(
1302 PeerConnectionInterface::kIceGatheringComplete);
1303 ice_observer_->OnIceComplete();
1304 }
1305}
1306
1307// Enabling voice and video channel.
1308void WebRtcSession::EnableChannels() {
1309 if (voice_channel_ && !voice_channel_->enabled())
1310 voice_channel_->Enable(true);
1311
1312 if (video_channel_ && !video_channel_->enabled())
1313 video_channel_->Enable(true);
1314
1315 if (data_channel_.get() && !data_channel_->enabled())
1316 data_channel_->Enable(true);
1317}
1318
1319void WebRtcSession::ProcessNewLocalCandidate(
1320 const std::string& content_name,
1321 const cricket::Candidates& candidates) {
1322 int sdp_mline_index;
1323 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1324 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1325 << content_name << " not found";
1326 return;
1327 }
1328
1329 for (cricket::Candidates::const_iterator citer = candidates.begin();
1330 citer != candidates.end(); ++citer) {
1331 // Use content_name as the candidate media id.
1332 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1333 if (ice_observer_) {
1334 ice_observer_->OnIceCandidate(&candidate);
1335 }
1336 if (local_desc_) {
1337 local_desc_->AddCandidate(&candidate);
1338 }
1339 }
1340}
1341
1342// Returns the media index for a local ice candidate given the content name.
1343bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1344 int* sdp_mline_index) {
1345 if (!BaseSession::local_description() || !sdp_mline_index)
1346 return false;
1347
1348 bool content_found = false;
1349 const ContentInfos& contents = BaseSession::local_description()->contents();
1350 for (size_t index = 0; index < contents.size(); ++index) {
1351 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001352 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353 content_found = true;
1354 break;
1355 }
1356 }
1357 return content_found;
1358}
1359
1360bool WebRtcSession::UseCandidatesInSessionDescription(
1361 const SessionDescriptionInterface* remote_desc) {
1362 if (!remote_desc)
1363 return true;
1364 bool ret = true;
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001365
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1367 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1368 for (size_t n = 0; n < candidates->count(); ++n) {
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001369 const IceCandidateInterface* candidate = candidates->at(n);
1370 bool valid = false;
1371 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
1372 if (valid) {
1373 LOG(LS_INFO) << "UseCandidatesInSessionDescription: Candidate saved.";
1374 saved_candidates_.push_back(
1375 new JsepIceCandidate(candidate->sdp_mid(),
1376 candidate->sdp_mline_index(),
1377 candidate->candidate()));
1378 }
1379 continue;
1380 }
1381
1382 ret = UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383 if (!ret)
1384 break;
1385 }
1386 }
1387 return ret;
1388}
1389
1390bool WebRtcSession::UseCandidate(
1391 const IceCandidateInterface* candidate) {
1392
1393 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1394 size_t remote_content_size =
1395 BaseSession::remote_description()->contents().size();
1396 if (mediacontent_index >= remote_content_size) {
1397 LOG(LS_ERROR)
1398 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1399 return false;
1400 }
1401
1402 cricket::ContentInfo content =
1403 BaseSession::remote_description()->contents()[mediacontent_index];
1404 std::vector<cricket::Candidate> candidates;
1405 candidates.push_back(candidate->candidate());
1406 // Invoking BaseSession method to handle remote candidates.
1407 std::string error;
1408 if (OnRemoteCandidates(content.name, candidates, &error)) {
1409 // Candidates successfully submitted for checking.
1410 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1411 ice_connection_state_ ==
1412 PeerConnectionInterface::kIceConnectionDisconnected) {
1413 // If state is New, then the session has just gotten its first remote ICE
1414 // candidates, so go to Checking.
1415 // If state is Disconnected, the session is re-using old candidates or
1416 // receiving additional ones, so go to Checking.
1417 // If state is Connected, stay Connected.
1418 // TODO(bemasc): If state is Connected, and the new candidates are for a
1419 // newly added transport, then the state actually _should_ move to
1420 // checking. Add a way to distinguish that case.
1421 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1422 }
1423 // TODO(bemasc): If state is Completed, go back to Connected.
1424 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001425 if (!error.empty()) {
1426 LOG(LS_WARNING) << error;
1427 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001428 }
1429 return true;
1430}
1431
1432void WebRtcSession::RemoveUnusedChannelsAndTransports(
1433 const SessionDescription* desc) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001434 // Destroy video_channel_ first since it may have a pointer to the
1435 // voice_channel_.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001436 const cricket::ContentInfo* video_info =
1437 cricket::GetFirstVideoContent(desc);
1438 if ((!video_info || video_info->rejected) && video_channel_) {
1439 mediastream_signaling_->OnVideoChannelClose();
1440 SignalVideoChannelDestroyed();
1441 const std::string content_name = video_channel_->content_name();
1442 channel_manager_->DestroyVideoChannel(video_channel_.release());
1443 DestroyTransportProxy(content_name);
1444 }
1445
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001446 const cricket::ContentInfo* voice_info =
1447 cricket::GetFirstAudioContent(desc);
1448 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1449 mediastream_signaling_->OnAudioChannelClose();
1450 SignalVoiceChannelDestroyed();
1451 const std::string content_name = voice_channel_->content_name();
1452 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1453 DestroyTransportProxy(content_name);
1454 }
1455
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456 const cricket::ContentInfo* data_info =
1457 cricket::GetFirstDataContent(desc);
1458 if ((!data_info || data_info->rejected) && data_channel_) {
1459 mediastream_signaling_->OnDataChannelClose();
1460 SignalDataChannelDestroyed();
1461 const std::string content_name = data_channel_->content_name();
1462 channel_manager_->DestroyDataChannel(data_channel_.release());
1463 DestroyTransportProxy(content_name);
1464 }
1465}
1466
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001467// TODO(mallinath) - Add a correct error code if the channels are not creatued
1468// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1470 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001471 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1472 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 port_allocator()->set_flags(port_allocator()->flags() &
1474 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1475 }
1476
1477 // Creating the media channels and transport proxies.
1478 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1479 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001480 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001481 LOG(LS_ERROR) << "Failed to create voice channel.";
1482 return false;
1483 }
1484 }
1485
1486 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1487 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001488 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489 LOG(LS_ERROR) << "Failed to create video channel.";
1490 return false;
1491 }
1492 }
1493
1494 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1495 if (data_channel_type_ != cricket::DCT_NONE &&
1496 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001497 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001498 LOG(LS_ERROR) << "Failed to create data channel.";
1499 return false;
1500 }
1501 }
1502
1503 return true;
1504}
1505
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001506bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001507 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001508 this, content->name, true));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001509 if (!voice_channel_.get())
1510 return false;
1511
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001512 voice_channel_->SetChannelOptions(audio_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001513 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514}
1515
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001516bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001517 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001518 this, content->name, true, voice_channel_.get()));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001519 if (!video_channel_.get())
1520 return false;
1521
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001522 video_channel_->SetChannelOptions(video_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001523 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001524}
1525
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001526bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001527 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001529 this, content->name, !sctp, data_channel_type_));
wu@webrtc.org91053e72013-08-10 07:18:04 +00001530 if (!data_channel_.get()) {
1531 return false;
1532 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001533 if (sctp) {
1534 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001535 data_channel_->SignalDataReceived.connect(
1536 this, &WebRtcSession::OnDataChannelMessageReceived);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +00001537 data_channel_->SignalStreamClosedRemotely.connect(
1538 mediastream_signaling_,
1539 &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001540 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001541 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001542}
1543
1544void WebRtcSession::CopySavedCandidates(
1545 SessionDescriptionInterface* dest_desc) {
1546 if (!dest_desc) {
1547 ASSERT(false);
1548 return;
1549 }
1550 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1551 dest_desc->AddCandidate(saved_candidates_[i]);
1552 delete saved_candidates_[i];
1553 }
1554 saved_candidates_.clear();
1555}
1556
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001557void WebRtcSession::OnDataChannelMessageReceived(
1558 cricket::DataChannel* channel,
1559 const cricket::ReceiveDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001560 const rtc::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001561 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001562 if (params.type == cricket::DMT_CONTROL &&
1563 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1564 // Received CONTROL on unused sid, process as an OPEN message.
1565 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001567 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568}
1569
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001570// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001571bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001572 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1573 if (!bundle_enabled)
1574 return true;
1575
1576 const cricket::ContentGroup* bundle_group =
1577 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1578 ASSERT(bundle_group != NULL);
1579
1580 const cricket::ContentInfos& contents = desc->contents();
1581 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1582 citer != contents.end(); ++citer) {
1583 const cricket::ContentInfo* content = (&*citer);
1584 ASSERT(content != NULL);
1585 if (bundle_group->HasContentName(content->name) &&
1586 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1587 if (!HasRtcpMuxEnabled(content))
1588 return false;
1589 }
1590 }
1591 // RTCP-MUX is enabled in all the contents.
1592 return true;
1593}
1594
1595bool WebRtcSession::HasRtcpMuxEnabled(
1596 const cricket::ContentInfo* content) {
1597 const cricket::MediaContentDescription* description =
1598 static_cast<cricket::MediaContentDescription*>(content->description);
1599 return description->rtcp_mux();
1600}
1601
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001602bool WebRtcSession::ValidateSessionDescription(
1603 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001604 cricket::ContentSource source, std::string* err_desc) {
1605 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001606 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001607 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001608 }
1609
1610 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001611 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001612 }
1613
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001614 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001615 Action action = GetAction(sdesc->type());
1616 if (source == cricket::CS_LOCAL) {
1617 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001618 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001619 } else {
1620 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001621 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001622 }
1623
1624 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001625 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001626 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1627 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001628 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001629 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001630 }
1631
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001632 // Verify ice-ufrag and ice-pwd.
1633 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001634 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001635 }
1636
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001637 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001638 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001639 }
1640
1641 // Verify m-lines in Answer when compared against Offer.
1642 if (action == kAnswer) {
1643 const cricket::SessionDescription* offer_desc =
1644 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1645 local_description()->description();
1646 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001647 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001648 }
1649 }
1650
1651 return true;
1652}
1653
1654bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1655 return ((action == kOffer && state() == STATE_INIT) ||
1656 // update local offer
1657 (action == kOffer && state() == STATE_SENTINITIATE) ||
1658 // update the current ongoing session.
1659 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1660 (action == kOffer && state() == STATE_SENTACCEPT) ||
1661 (action == kOffer && state() == STATE_INPROGRESS) ||
1662 // accept remote offer
1663 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1664 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1665 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1666 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1667}
1668
1669bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1670 return ((action == kOffer && state() == STATE_INIT) ||
1671 // update remote offer
1672 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1673 // update the current ongoing session
1674 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1675 (action == kOffer && state() == STATE_SENTACCEPT) ||
1676 (action == kOffer && state() == STATE_INPROGRESS) ||
1677 // accept local offer
1678 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1679 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1680 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1681 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1682}
1683
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001684std::string WebRtcSession::GetSessionErrorMsg() {
1685 std::ostringstream desc;
1686 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1687 desc << kSessionErrorDesc << error_desc() << ".";
1688 return desc.str();
1689}
1690
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001691// We need to check the local/remote description for the Transport instead of
1692// the session, because a new Transport added during renegotiation may have
1693// them unset while the session has them set from the previous negotiation.
1694// Not doing so may trigger the auto generation of transport description and
1695// mess up DTLS identity information, ICE credential, etc.
1696bool WebRtcSession::ReadyToUseRemoteCandidate(
1697 const IceCandidateInterface* candidate,
1698 const SessionDescriptionInterface* remote_desc,
1699 bool* valid) {
1700 *valid = true;;
1701 cricket::TransportProxy* transport_proxy = NULL;
1702
1703 const SessionDescriptionInterface* current_remote_desc =
1704 remote_desc ? remote_desc : remote_description();
1705
1706 if (!current_remote_desc)
1707 return false;
1708
1709 size_t mediacontent_index =
1710 static_cast<size_t>(candidate->sdp_mline_index());
1711 size_t remote_content_size =
1712 current_remote_desc->description()->contents().size();
1713 if (mediacontent_index >= remote_content_size) {
1714 LOG(LS_ERROR)
1715 << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
1716
1717 *valid = false;
1718 return false;
1719 }
1720
1721 cricket::ContentInfo content =
1722 current_remote_desc->description()->contents()[mediacontent_index];
1723 transport_proxy = GetTransportProxy(content.name);
1724
1725 return transport_proxy && transport_proxy->local_description_set() &&
1726 transport_proxy->remote_description_set();
1727}
1728
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729} // namespace webrtc