blob: ddc88762913a7b03d3e2f65e80bb8396fb66796f [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/base/helpers.h"
42#include "talk/base/logging.h"
43#include "talk/base/stringencode.h"
buildbot@webrtc.org41451d42014-05-03 05:39:45 +000044#include "talk/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000045#include "talk/media/base/constants.h"
46#include "talk/media/base/videocapturer.h"
47#include "talk/session/media/channel.h"
48#include "talk/session/media/channelmanager.h"
49#include "talk/session/media/mediasession.h"
50
51using cricket::ContentInfo;
52using cricket::ContentInfos;
53using cricket::MediaContentDescription;
54using cricket::SessionDescription;
55using cricket::TransportInfo;
56
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057namespace webrtc {
58
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059// Error messages
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000060const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
61 "is enabled.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000062const char kCreateChannelFailed[] = "Failed to create channels.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000063const char kInvalidCandidates[] = "Description contains invalid candidates.";
64const char kInvalidSdp[] = "Invalid session description.";
65const char kMlineMismatch[] =
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000066 "Offer and answer descriptions m-lines are not matching. Rejecting answer.";
67const char kPushDownTDFailed[] =
68 "Failed to push down transport description:";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000069const char kSdpWithoutDtlsFingerprint[] =
70 "Called with SDP without DTLS fingerprint.";
71const char kSdpWithoutSdesCrypto[] =
72 "Called with SDP without SDES crypto.";
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +000073const char kSdpWithoutIceUfragPwd[] =
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000074 "Called with SDP without ice-ufrag and ice-pwd.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075const char kSessionError[] = "Session error code: ";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000076const char kSessionErrorDesc[] = "Session error description: ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077
78// Compares |answer| against |offer|. Comparision is done
79// for number of m-lines in answer against offer. If matches true will be
80// returned otherwise false.
81static bool VerifyMediaDescriptions(
82 const SessionDescription* answer, const SessionDescription* offer) {
83 if (offer->contents().size() != answer->contents().size())
84 return false;
85
86 for (size_t i = 0; i < offer->contents().size(); ++i) {
87 if ((offer->contents()[i].name) != answer->contents()[i].name) {
88 return false;
89 }
wu@webrtc.org4e393072014-04-07 17:04:35 +000090 const MediaContentDescription* offer_mdesc =
91 static_cast<const MediaContentDescription*>(
92 offer->contents()[i].description);
93 const MediaContentDescription* answer_mdesc =
94 static_cast<const MediaContentDescription*>(
95 answer->contents()[i].description);
96 if (offer_mdesc->type() != answer_mdesc->type()) {
97 return false;
98 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099 }
100 return true;
101}
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103// Checks that each non-rejected content has SDES crypto keys or a DTLS
104// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
105// keys, will be caught in Transport negotiation, and backstopped by Channel's
106// |secure_required| check.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000107static bool VerifyCrypto(const SessionDescription* desc,
108 bool dtls_enabled,
109 std::string* error) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 const ContentInfos& contents = desc->contents();
111 for (size_t index = 0; index < contents.size(); ++index) {
112 const ContentInfo* cinfo = &contents[index];
113 if (cinfo->rejected) {
114 continue;
115 }
116
117 // If the content isn't rejected, crypto must be present.
118 const MediaContentDescription* media =
119 static_cast<const MediaContentDescription*>(cinfo->description);
120 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
121 if (!media || !tinfo) {
122 // Something is not right.
123 LOG(LS_ERROR) << kInvalidSdp;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000124 *error = kInvalidSdp;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000125 return false;
126 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000127 if (dtls_enabled) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000128 if (!tinfo->description.identity_fingerprint) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000129 LOG(LS_WARNING) <<
130 "Session description must have DTLS fingerprint if DTLS enabled.";
131 *error = kSdpWithoutDtlsFingerprint;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000132 return false;
133 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000134 } else {
135 if (media->cryptos().empty()) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000136 LOG(LS_WARNING) <<
137 "Session description must have SDES when DTLS disabled.";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000138 *error = kSdpWithoutSdesCrypto;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000139 return false;
140 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000141 }
142 }
143
144 return true;
145}
146
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +0000147// Checks that each non-rejected content has ice-ufrag and ice-pwd set.
148static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
149 const ContentInfos& contents = desc->contents();
150 for (size_t index = 0; index < contents.size(); ++index) {
151 const ContentInfo* cinfo = &contents[index];
152 if (cinfo->rejected) {
153 continue;
154 }
155
156 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
157 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
158 if (!tinfo) {
159 // Something is not right.
160 LOG(LS_ERROR) << kInvalidSdp;
161 return false;
162 }
163 if (tinfo->description.ice_ufrag.empty() ||
164 tinfo->description.ice_pwd.empty()) {
165 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
166 return false;
167 }
168 }
169 return true;
170}
171
wu@webrtc.org91053e72013-08-10 07:18:04 +0000172// Forces |sdesc->crypto_required| to the appropriate state based on the
173// current security policy, to ensure a failure occurs if there is an error
174// in crypto negotiation.
175// Called when processing the local session description.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000176static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
177 SessionDescription* sdesc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000178 if (!sdesc) {
179 return;
180 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000181
wu@webrtc.org91053e72013-08-10 07:18:04 +0000182 // Updating the |crypto_required_| in MediaContentDescription to the
183 // appropriate state based on the current security policy.
184 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
185 iter != sdesc->contents().end(); ++iter) {
186 if (cricket::IsMediaContent(&*iter)) {
187 MediaContentDescription* mdesc =
188 static_cast<MediaContentDescription*> (iter->description);
189 if (mdesc) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000190 mdesc->set_crypto_required(type);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000191 }
192 }
193 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000194}
195
196static bool GetAudioSsrcByTrackId(
197 const SessionDescription* session_description,
198 const std::string& track_id, uint32 *ssrc) {
199 const cricket::ContentInfo* audio_info =
200 cricket::GetFirstAudioContent(session_description);
201 if (!audio_info) {
202 LOG(LS_ERROR) << "Audio not used in this call";
203 return false;
204 }
205
206 const cricket::MediaContentDescription* audio_content =
207 static_cast<const cricket::MediaContentDescription*>(
208 audio_info->description);
209 cricket::StreamParams stream;
210 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
211 &stream)) {
212 return false;
213 }
214 *ssrc = stream.first_ssrc();
215 return true;
216}
217
218static bool GetTrackIdBySsrc(const SessionDescription* session_description,
219 uint32 ssrc, std::string* track_id) {
220 ASSERT(track_id != NULL);
221
222 cricket::StreamParams stream_out;
223 const cricket::ContentInfo* audio_info =
224 cricket::GetFirstAudioContent(session_description);
225 if (!audio_info) {
226 return false;
227 }
228 const cricket::MediaContentDescription* audio_content =
229 static_cast<const cricket::MediaContentDescription*>(
230 audio_info->description);
231
232 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
233 *track_id = stream_out.id;
234 return true;
235 }
236
237 const cricket::ContentInfo* video_info =
238 cricket::GetFirstVideoContent(session_description);
239 if (!video_info) {
240 return false;
241 }
242 const cricket::MediaContentDescription* video_content =
243 static_cast<const cricket::MediaContentDescription*>(
244 video_info->description);
245
246 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
247 *track_id = stream_out.id;
248 return true;
249 }
250 return false;
251}
252
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000253static bool BadSdp(const std::string& source,
254 const std::string& type,
255 const std::string& reason,
256 std::string* err_desc) {
257 std::ostringstream desc;
258 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
259
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000260 if (err_desc) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000261 *err_desc = desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000262 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000263 LOG(LS_ERROR) << desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264 return false;
265}
266
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000267static bool BadSdp(cricket::ContentSource source,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000268 const std::string& type,
269 const std::string& reason,
270 std::string* err_desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271 if (source == cricket::CS_LOCAL) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000272 return BadSdp("local", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000273 } else {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000274 return BadSdp("remote", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275 }
276}
277
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000278static bool BadLocalSdp(const std::string& type,
279 const std::string& reason,
280 std::string* err_desc) {
281 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
282}
283
284static bool BadRemoteSdp(const std::string& type,
285 const std::string& reason,
286 std::string* err_desc) {
287 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
288}
289
290static bool BadOfferSdp(cricket::ContentSource source,
291 const std::string& reason,
292 std::string* err_desc) {
293 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
294}
295
296static bool BadPranswerSdp(cricket::ContentSource source,
297 const std::string& reason,
298 std::string* err_desc) {
299 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
300 reason, err_desc);
301}
302
303static bool BadAnswerSdp(cricket::ContentSource source,
304 const std::string& reason,
305 std::string* err_desc) {
306 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000307}
308
309#define GET_STRING_OF_STATE(state) \
310 case cricket::BaseSession::state: \
311 result = #state; \
312 break;
313
314static std::string GetStateString(cricket::BaseSession::State state) {
315 std::string result;
316 switch (state) {
317 GET_STRING_OF_STATE(STATE_INIT)
318 GET_STRING_OF_STATE(STATE_SENTINITIATE)
319 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
320 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
321 GET_STRING_OF_STATE(STATE_SENTACCEPT)
322 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
323 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
324 GET_STRING_OF_STATE(STATE_SENTMODIFY)
325 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
326 GET_STRING_OF_STATE(STATE_SENTREJECT)
327 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
328 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
329 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
330 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
331 GET_STRING_OF_STATE(STATE_INPROGRESS)
332 GET_STRING_OF_STATE(STATE_DEINIT)
333 default:
334 ASSERT(false);
335 break;
336 }
337 return result;
338}
339
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000340#define GET_STRING_OF_ERROR_CODE(err) \
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000341 case cricket::BaseSession::err: \
342 result = #err; \
343 break;
344
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000345static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000346 std::string result;
347 switch (err) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000348 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
349 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
350 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
351 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
352 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
353 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 default:
355 ASSERT(false);
356 break;
357 }
358 return result;
359}
360
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000361static std::string MakeErrorString(const std::string& error,
362 const std::string& desc) {
363 std::ostringstream ret;
364 ret << error << " " << desc;
365 return ret.str();
366}
367
368static std::string MakeTdErrorString(const std::string& desc) {
369 return MakeErrorString(kPushDownTDFailed, desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370}
371
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000372// Set |option| to the highest-priority value of |key| in the optional
373// constraints if the key is found and has a valid value.
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000374template<typename T>
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000375static void SetOptionFromOptionalConstraint(
376 const MediaConstraintsInterface* constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000377 const std::string& key, cricket::Settable<T>* option) {
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000378 if (!constraints) {
379 return;
380 }
381 std::string string_value;
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000382 T value;
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000383 if (constraints->GetOptional().FindFirst(key, &string_value)) {
384 if (talk_base::FromString(string_value, &value)) {
385 option->Set(value);
386 }
387 }
388}
389
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000390// Help class used to remember if a a remote peer has requested ice restart by
391// by sending a description with new ice ufrag and password.
392class IceRestartAnswerLatch {
393 public:
394 IceRestartAnswerLatch() : ice_restart_(false) { }
395
wu@webrtc.org91053e72013-08-10 07:18:04 +0000396 // Returns true if CheckForRemoteIceRestart has been called with a new session
397 // description where ice password and ufrag has changed since last time
398 // Reset() was called.
399 bool Get() const {
400 return ice_restart_;
401 }
402
403 void Reset() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404 if (ice_restart_) {
405 ice_restart_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000406 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000407 }
408
409 void CheckForRemoteIceRestart(
410 const SessionDescriptionInterface* old_desc,
411 const SessionDescriptionInterface* new_desc) {
412 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
413 return;
414 }
415 const SessionDescription* new_sd = new_desc->description();
416 const SessionDescription* old_sd = old_desc->description();
417 const ContentInfos& contents = new_sd->contents();
418 for (size_t index = 0; index < contents.size(); ++index) {
419 const ContentInfo* cinfo = &contents[index];
420 if (cinfo->rejected) {
421 continue;
422 }
423 // If the content isn't rejected, check if ufrag and password has
424 // changed.
425 const cricket::TransportDescription* new_transport_desc =
426 new_sd->GetTransportDescriptionByName(cinfo->name);
427 const cricket::TransportDescription* old_transport_desc =
428 old_sd->GetTransportDescriptionByName(cinfo->name);
429 if (!new_transport_desc || !old_transport_desc) {
430 // No transport description exist. This is not an ice restart.
431 continue;
432 }
jiayl@webrtc.orgdb397e52014-06-20 16:32:09 +0000433 if (cricket::IceCredentialsChanged(old_transport_desc->ice_ufrag,
434 old_transport_desc->ice_pwd,
435 new_transport_desc->ice_ufrag,
436 new_transport_desc->ice_pwd)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000437 LOG(LS_INFO) << "Remote peer request ice restart.";
438 ice_restart_ = true;
439 break;
440 }
441 }
442 }
443
444 private:
445 bool ice_restart_;
446};
447
wu@webrtc.org91053e72013-08-10 07:18:04 +0000448WebRtcSession::WebRtcSession(
449 cricket::ChannelManager* channel_manager,
450 talk_base::Thread* signaling_thread,
451 talk_base::Thread* worker_thread,
452 cricket::PortAllocator* port_allocator,
453 MediaStreamSignaling* mediastream_signaling)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000454 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
455 talk_base::ToString(talk_base::CreateRandomId64() &
456 LLONG_MAX),
457 cricket::NS_JINGLE_RTP, false),
458 // RFC 3264: The numeric value of the session id and version in the
459 // o line MUST be representable with a "64 bit signed integer".
460 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
461 channel_manager_(channel_manager),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000462 mediastream_signaling_(mediastream_signaling),
463 ice_observer_(NULL),
464 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465 older_version_remote_peer_(false),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000466 dtls_enabled_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000467 data_channel_type_(cricket::DCT_NONE),
468 ice_restart_latch_(new IceRestartAnswerLatch) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000469}
470
471WebRtcSession::~WebRtcSession() {
472 if (voice_channel_.get()) {
473 SignalVoiceChannelDestroyed();
474 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
475 }
476 if (video_channel_.get()) {
477 SignalVideoChannelDestroyed();
478 channel_manager_->DestroyVideoChannel(video_channel_.release());
479 }
480 if (data_channel_.get()) {
481 SignalDataChannelDestroyed();
482 channel_manager_->DestroyDataChannel(data_channel_.release());
483 }
484 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
485 delete saved_candidates_[i];
486 }
487 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000488}
489
wu@webrtc.org91053e72013-08-10 07:18:04 +0000490bool WebRtcSession::Initialize(
wu@webrtc.org97077a32013-10-25 21:18:33 +0000491 const PeerConnectionFactoryInterface::Options& options,
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000492 const MediaConstraintsInterface* constraints,
493 DTLSIdentityServiceInterface* dtls_identity_service,
494 PeerConnectionInterface::IceTransportsType ice_transport) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000495 // TODO(perkj): Take |constraints| into consideration. Return false if not all
496 // mandatory constraints can be fulfilled. Note that |constraints|
497 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000498 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000499
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000500 if (options.disable_encryption) {
501 dtls_enabled_ = false;
502 } else {
503 // Enable DTLS by default if |dtls_identity_service| is valid.
504 dtls_enabled_ = (dtls_identity_service != NULL);
505 // |constraints| can override the default |dtls_enabled_| value.
506 if (FindConstraint(
507 constraints,
508 MediaConstraintsInterface::kEnableDtlsSrtp,
509 &value, NULL)) {
510 dtls_enabled_ = value;
511 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000512 }
513
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000514 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000515 // It takes precendence over the disable_sctp_data_channels
516 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000517 if (FindConstraint(
518 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
519 &value, NULL) && value) {
520 LOG(LS_INFO) << "Allowing RTP data engine.";
521 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000522 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000523 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000524 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000525 LOG(LS_INFO) << "Allowing SCTP data engine.";
526 data_channel_type_ = cricket::DCT_SCTP;
527 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000528 }
529 if (data_channel_type_ != cricket::DCT_NONE) {
530 mediastream_signaling_->SetDataChannelFactory(this);
531 }
532
wu@webrtc.orgde305012013-10-31 15:40:38 +0000533 // Find DSCP constraint.
534 if (FindConstraint(
535 constraints,
536 MediaConstraintsInterface::kEnableDscp,
537 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000538 audio_options_.dscp.Set(value);
539 video_options_.dscp.Set(value);
540 }
541
542 // Find Suspend Below Min Bitrate constraint.
543 if (FindConstraint(
544 constraints,
545 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
546 &value,
547 NULL)) {
548 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000549 }
550
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000551 if (FindConstraint(
552 constraints,
553 MediaConstraintsInterface::kSkipEncodingUnusedStreams,
554 &value,
555 NULL)) {
556 video_options_.skip_encoding_unused_streams.Set(value);
557 }
558
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000559 SetOptionFromOptionalConstraint(constraints,
560 MediaConstraintsInterface::kScreencastMinBitrate,
561 &video_options_.screencast_min_bitrate);
562
563 // Find constraints for cpu overuse detection.
564 SetOptionFromOptionalConstraint(constraints,
565 MediaConstraintsInterface::kCpuUnderuseThreshold,
566 &video_options_.cpu_underuse_threshold);
567 SetOptionFromOptionalConstraint(constraints,
568 MediaConstraintsInterface::kCpuOveruseThreshold,
569 &video_options_.cpu_overuse_threshold);
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000570 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000571 MediaConstraintsInterface::kCpuOveruseDetection,
572 &video_options_.cpu_overuse_detection);
573 SetOptionFromOptionalConstraint(constraints,
574 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
575 &video_options_.cpu_overuse_encode_usage);
576 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000577 MediaConstraintsInterface::kCpuUnderuseEncodeRsdThreshold,
578 &video_options_.cpu_underuse_encode_rsd_threshold);
579 SetOptionFromOptionalConstraint(constraints,
580 MediaConstraintsInterface::kCpuOveruseEncodeRsdThreshold,
581 &video_options_.cpu_overuse_encode_rsd_threshold);
buildbot@webrtc.orgdb563902014-06-13 13:05:48 +0000582
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000583 // Find payload padding constraint.
584 SetOptionFromOptionalConstraint(constraints,
585 MediaConstraintsInterface::kPayloadPadding,
586 &video_options_.use_payload_padding);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000587
588 // Find improved wifi bwe constraint.
589 if (FindConstraint(
590 constraints,
591 MediaConstraintsInterface::kImprovedWifiBwe,
592 &value,
593 NULL)) {
594 video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
buildbot@webrtc.orgff6a3d92014-05-08 16:16:41 +0000595 } else {
596 // Enable by default if the constraint is not set.
597 video_options_.use_improved_wifi_bandwidth_estimator.Set(true);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000598 }
599
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000600 SetOptionFromOptionalConstraint(constraints,
601 MediaConstraintsInterface::kHighStartBitrate,
602 &video_options_.video_start_bitrate);
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000603
604 if (FindConstraint(
605 constraints,
606 MediaConstraintsInterface::kVeryHighBitrate,
607 &value,
608 NULL)) {
609 video_options_.video_highest_bitrate.Set(
610 cricket::VideoOptions::VERY_HIGH);
611 } else if (FindConstraint(
612 constraints,
613 MediaConstraintsInterface::kHighBitrate,
614 &value,
615 NULL)) {
616 video_options_.video_highest_bitrate.Set(
617 cricket::VideoOptions::HIGH);
618 }
619
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000620 SetOptionFromOptionalConstraint(constraints,
621 MediaConstraintsInterface::kOpusFec,
622 &audio_options_.opus_fec);
623
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000624 const cricket::VideoCodec default_codec(
625 JsepSessionDescription::kDefaultVideoCodecId,
626 JsepSessionDescription::kDefaultVideoCodecName,
627 JsepSessionDescription::kMaxVideoCodecWidth,
628 JsepSessionDescription::kMaxVideoCodecHeight,
629 JsepSessionDescription::kDefaultVideoCodecFramerate,
630 JsepSessionDescription::kDefaultVideoCodecPreference);
631 channel_manager_->SetDefaultVideoEncoderConfig(
632 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000633
634 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
635 signaling_thread(),
636 channel_manager_,
637 mediastream_signaling_,
638 dtls_identity_service,
639 this,
640 id(),
641 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000642 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000643
644 webrtc_session_desc_factory_->SignalIdentityReady.connect(
645 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000646
wu@webrtc.org97077a32013-10-25 21:18:33 +0000647 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000648 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000649 }
650
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000651 return true;
652}
653
654void WebRtcSession::Terminate() {
655 SetState(STATE_RECEIVEDTERMINATE);
656 RemoveUnusedChannelsAndTransports(NULL);
657 ASSERT(voice_channel_.get() == NULL);
658 ASSERT(video_channel_.get() == NULL);
659 ASSERT(data_channel_.get() == NULL);
660}
661
662bool WebRtcSession::StartCandidatesAllocation() {
663 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
664 // from TransportProxy to start gathering ice candidates.
665 SpeculativelyConnectAllTransportChannels();
666 if (!saved_candidates_.empty()) {
667 // If there are saved candidates which arrived before local description is
668 // set, copy those to remote description.
669 CopySavedCandidates(remote_desc_.get());
670 }
671 // Push remote candidates present in remote description to transport channels.
672 UseCandidatesInSessionDescription(remote_desc_.get());
673 return true;
674}
675
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000676void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
677 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000678}
679
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000680cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
681 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682}
683
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000684bool WebRtcSession::GetSslRole(talk_base::SSLRole* role) {
685 if (local_description() == NULL || remote_description() == NULL) {
686 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
687 << "SSL Role of the session.";
688 return false;
689 }
690
691 // TODO(mallinath) - Return role of each transport, as role may differ from
692 // one another.
693 // In current implementaion we just return the role of first transport in the
694 // transport map.
695 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
696 iter != transport_proxies().end(); ++iter) {
697 if (iter->second->impl()) {
698 return iter->second->impl()->GetSslRole(role);
699 }
700 }
701 return false;
702}
703
wu@webrtc.org91053e72013-08-10 07:18:04 +0000704void WebRtcSession::CreateOffer(CreateSessionDescriptionObserver* observer,
705 const MediaConstraintsInterface* constraints) {
706 webrtc_session_desc_factory_->CreateOffer(observer, constraints);
707}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000708
wu@webrtc.org91053e72013-08-10 07:18:04 +0000709void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
710 const MediaConstraintsInterface* constraints) {
711 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712}
713
714bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
715 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000716 // Takes the ownership of |desc| regardless of the result.
717 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
718
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000719 // Validate SDP.
720 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
721 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 }
723
724 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000725 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000726 if (state() == STATE_INIT && action == kOffer) {
727 set_initiator(true);
728 }
729
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000730 cricket::SecurePolicy sdes_policy =
731 webrtc_session_desc_factory_->SdesPolicy();
732 cricket::CryptoType crypto_required = dtls_enabled_ ?
733 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
734 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000735 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000736 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737
738 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000739 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000740
741 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000742 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 // TODO(mallinath) - Handle CreateChannel failure, as new local description
744 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000745 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000746 }
747
748 // Remove channel and transport proxies, if MediaContentDescription is
749 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000750 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000751
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000752 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753 return false;
754 }
755 // Kick starting the ice candidates allocation.
756 StartCandidatesAllocation();
757
758 // Update state and SSRC of local MediaStreams and DataChannels based on the
759 // local session description.
760 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
761
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000762 talk_base::SSLRole role;
763 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
764 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
765 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000766 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000767 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000768 }
769 return true;
770}
771
772bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
773 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000774 // Takes the ownership of |desc| regardless of the result.
775 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
776
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000777 // Validate SDP.
778 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
779 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780 }
781
782 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000783 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000784 if (action == kOffer && !CreateChannels(desc->description())) {
785 // TODO(mallinath) - Handle CreateChannel failure, as new local description
786 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000787 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000788 }
789
790 // Remove channel and transport proxies, if MediaContentDescription is
791 // rejected.
792 RemoveUnusedChannelsAndTransports(desc->description());
793
794 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
795 // is called.
796 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000797 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000798 return false;
799 }
800
801 // Update remote MediaStreams.
802 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
803 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000804 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805 }
806
807 // Copy all saved candidates.
808 CopySavedCandidates(desc);
809 // We retain all received candidates.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000810 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
811 remote_desc_.get(), desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812 // Check if this new SessionDescription contains new ice ufrag and password
813 // that indicates the remote peer requests ice restart.
814 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
815 desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000816 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000817
818 talk_base::SSLRole role;
819 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
820 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
821 }
822
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000824 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 }
826 return true;
827}
828
829bool WebRtcSession::UpdateSessionState(
830 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831 std::string* err_desc) {
832 // If there's already a pending error then no state transition should happen.
833 // But all call-sites should be verifying this before calling us!
834 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000835 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000836 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000837 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
838 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839 }
840 SetState(source == cricket::CS_LOCAL ?
841 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
842 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000843 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000844 }
845 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000846 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
847 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848 }
849 EnableChannels();
850 SetState(source == cricket::CS_LOCAL ?
851 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
852 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000853 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000854 }
855 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000856 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
857 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000858 }
859 MaybeEnableMuxingSupport();
860 EnableChannels();
861 SetState(source == cricket::CS_LOCAL ?
862 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
863 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000864 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000865 }
866 }
867 return true;
868}
869
870WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
871 if (type == SessionDescriptionInterface::kOffer) {
872 return WebRtcSession::kOffer;
873 } else if (type == SessionDescriptionInterface::kPrAnswer) {
874 return WebRtcSession::kPrAnswer;
875 } else if (type == SessionDescriptionInterface::kAnswer) {
876 return WebRtcSession::kAnswer;
877 }
878 ASSERT(false && "unknown action type");
879 return WebRtcSession::kOffer;
880}
881
882bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
883 if (state() == STATE_INIT) {
884 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
885 << "without any offer (local or remote) "
886 << "session description.";
887 return false;
888 }
889
890 if (!candidate) {
891 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
892 return false;
893 }
894
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +0000895 bool valid = false;
896 if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
897 if (valid) {
898 LOG(LS_INFO) << "ProcessIceMessage: Candidate saved";
899 saved_candidates_.push_back(
900 new JsepIceCandidate(candidate->sdp_mid(),
901 candidate->sdp_mline_index(),
902 candidate->candidate()));
buildbot@webrtc.org61c1b8e2014-04-09 06:06:38 +0000903 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +0000904 return valid;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905 }
906
907 // Add this candidate to the remote session description.
908 if (!remote_desc_->AddCandidate(candidate)) {
909 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
910 return false;
911 }
912
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000913 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914}
915
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000916bool WebRtcSession::UpdateIce(PeerConnectionInterface::IceTransportsType type) {
917 return false;
918}
919
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000920bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921 if (!BaseSession::local_description())
922 return false;
923 return webrtc::GetTrackIdBySsrc(
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000924 BaseSession::local_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925}
926
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000927bool WebRtcSession::GetRemoteTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928 if (!BaseSession::remote_description())
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000929 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 return webrtc::GetTrackIdBySsrc(
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000931 BaseSession::remote_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932}
933
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000934std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000936 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937 return desc.str();
938}
939
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000940void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
941 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942 ASSERT(signaling_thread()->IsCurrent());
943 if (!voice_channel_) {
944 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
945 return;
946 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000947 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
948 // SetRenderer() can fail if the ssrc does not match any playout channel.
949 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
950 return;
951 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
953 // Allow that SetOutputScaling fail if |enable| is false but assert
954 // otherwise. This in the normal case when the underlying media channel has
955 // already been deleted.
956 ASSERT(enable == false);
957 }
958}
959
960void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000961 const cricket::AudioOptions& options,
962 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 ASSERT(signaling_thread()->IsCurrent());
964 if (!voice_channel_) {
965 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
966 return;
967 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000968 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
969 // SetRenderer() can fail if the ssrc does not match any send channel.
970 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
971 return;
972 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000973 if (!voice_channel_->MuteStream(ssrc, !enable)) {
974 // Allow that MuteStream fail if |enable| is false but assert otherwise.
975 // This in the normal case when the underlying media channel has already
976 // been deleted.
977 ASSERT(enable == false);
978 return;
979 }
980 if (enable)
981 voice_channel_->SetChannelOptions(options);
982}
983
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000984void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
985 ASSERT(signaling_thread()->IsCurrent());
986 ASSERT(volume >= 0 && volume <= 10);
987 if (!voice_channel_) {
988 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
989 return;
990 }
991
992 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
993 ASSERT(false);
994}
995
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
997 cricket::VideoCapturer* camera) {
998 ASSERT(signaling_thread()->IsCurrent());
999
1000 if (!video_channel_.get()) {
1001 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
1002 // support video.
1003 LOG(LS_WARNING) << "Video not used in this call.";
1004 return false;
1005 }
1006 if (!video_channel_->SetCapturer(ssrc, camera)) {
1007 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1008 // This in the normal case when the underlying media channel has already
1009 // been deleted.
1010 ASSERT(camera == NULL);
1011 return false;
1012 }
1013 return true;
1014}
1015
1016void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1017 bool enable,
1018 cricket::VideoRenderer* renderer) {
1019 ASSERT(signaling_thread()->IsCurrent());
1020 if (!video_channel_) {
1021 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1022 return;
1023 }
1024 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1025 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1026 // This in the normal case when the underlying media channel has already
1027 // been deleted.
1028 ASSERT(renderer == NULL);
1029 }
1030}
1031
1032void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1033 const cricket::VideoOptions* options) {
1034 ASSERT(signaling_thread()->IsCurrent());
1035 if (!video_channel_) {
1036 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1037 return;
1038 }
1039 if (!video_channel_->MuteStream(ssrc, !enable)) {
1040 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1041 // This in the normal case when the underlying media channel has already
1042 // been deleted.
1043 ASSERT(enable == false);
1044 return;
1045 }
1046 if (enable && options)
1047 video_channel_->SetChannelOptions(*options);
1048}
1049
1050bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1051 ASSERT(signaling_thread()->IsCurrent());
1052 if (!voice_channel_) {
1053 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1054 return false;
1055 }
1056 uint32 send_ssrc = 0;
1057 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1058 // exists.
1059 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1060 &send_ssrc)) {
1061 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1062 return false;
1063 }
1064 return voice_channel_->CanInsertDtmf();
1065}
1066
1067bool WebRtcSession::InsertDtmf(const std::string& track_id,
1068 int code, int duration) {
1069 ASSERT(signaling_thread()->IsCurrent());
1070 if (!voice_channel_) {
1071 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1072 return false;
1073 }
1074 uint32 send_ssrc = 0;
1075 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1076 track_id, &send_ssrc))) {
1077 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1078 return false;
1079 }
1080 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1081 cricket::DF_SEND)) {
1082 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1083 return false;
1084 }
1085 return true;
1086}
1087
1088sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1089 return &SignalVoiceChannelDestroyed;
1090}
1091
wu@webrtc.org78187522013-10-07 23:32:02 +00001092bool WebRtcSession::SendData(const cricket::SendDataParams& params,
1093 const talk_base::Buffer& payload,
1094 cricket::SendDataResult* result) {
1095 if (!data_channel_.get()) {
1096 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1097 return false;
1098 }
1099 return data_channel_->SendData(params, payload, result);
1100}
1101
1102bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1103 if (!data_channel_.get()) {
1104 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1105 return false;
1106 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001107 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1108 &DataChannel::OnChannelReady);
1109 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1110 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001111 return true;
1112}
1113
1114void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001115 if (!data_channel_.get()) {
1116 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1117 return;
1118 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001119 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1120 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1121}
1122
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001123void WebRtcSession::AddSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001124 if (!data_channel_.get()) {
1125 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1126 return;
1127 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001128 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1129 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001130}
1131
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001132void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
jiayl@webrtc.org2eaac182014-06-17 16:02:46 +00001133 mediastream_signaling_->RemoveSctpDataChannel(static_cast<int>(sid));
1134
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001135 if (!data_channel_.get()) {
1136 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1137 << "NULL.";
1138 return;
1139 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001140 data_channel_->RemoveRecvStream(sid);
1141 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001142}
1143
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001144bool WebRtcSession::ReadyToSendData() const {
1145 return data_channel_.get() && data_channel_->ready_to_send_data();
1146}
1147
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001149 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001150 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001151 if (state() == STATE_RECEIVEDTERMINATE) {
1152 return NULL;
1153 }
1154 if (data_channel_type_ == cricket::DCT_NONE) {
1155 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1156 return NULL;
1157 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001158 InternalDataChannelInit new_config =
1159 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001160 if (data_channel_type_ == cricket::DCT_SCTP) {
1161 if (new_config.id < 0) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001162 talk_base::SSLRole role;
1163 if (GetSslRole(&role) &&
1164 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1166 return NULL;
1167 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001168 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1170 << "because the id is already in use or out of range.";
1171 return NULL;
1172 }
1173 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001174
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001175 talk_base::scoped_refptr<DataChannel> channel(DataChannel::Create(
1176 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001177 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001180 return channel;
1181}
1182
1183cricket::DataChannelType WebRtcSession::data_channel_type() const {
1184 return data_channel_type_;
1185}
1186
wu@webrtc.org91053e72013-08-10 07:18:04 +00001187bool WebRtcSession::IceRestartPending() const {
1188 return ice_restart_latch_->Get();
1189}
1190
1191void WebRtcSession::ResetIceRestartLatch() {
1192 ice_restart_latch_->Reset();
1193}
1194
1195void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
1196 SetIdentity(identity);
1197}
1198
1199bool WebRtcSession::waiting_for_identity() const {
1200 return webrtc_session_desc_factory_->waiting_for_identity();
1201}
1202
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203void WebRtcSession::SetIceConnectionState(
1204 PeerConnectionInterface::IceConnectionState state) {
1205 if (ice_connection_state_ == state) {
1206 return;
1207 }
1208
1209 // ASSERT that the requested transition is allowed. Note that
1210 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1211 // within PeerConnection). This switch statement should compile away when
1212 // ASSERTs are disabled.
1213 switch (ice_connection_state_) {
1214 case PeerConnectionInterface::kIceConnectionNew:
1215 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1216 break;
1217 case PeerConnectionInterface::kIceConnectionChecking:
1218 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1219 state == PeerConnectionInterface::kIceConnectionConnected);
1220 break;
1221 case PeerConnectionInterface::kIceConnectionConnected:
1222 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1223 state == PeerConnectionInterface::kIceConnectionChecking ||
1224 state == PeerConnectionInterface::kIceConnectionCompleted);
1225 break;
1226 case PeerConnectionInterface::kIceConnectionCompleted:
1227 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1228 state == PeerConnectionInterface::kIceConnectionDisconnected);
1229 break;
1230 case PeerConnectionInterface::kIceConnectionFailed:
1231 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1232 break;
1233 case PeerConnectionInterface::kIceConnectionDisconnected:
1234 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1235 state == PeerConnectionInterface::kIceConnectionConnected ||
1236 state == PeerConnectionInterface::kIceConnectionCompleted ||
1237 state == PeerConnectionInterface::kIceConnectionFailed);
1238 break;
1239 case PeerConnectionInterface::kIceConnectionClosed:
1240 ASSERT(false);
1241 break;
1242 default:
1243 ASSERT(false);
1244 break;
1245 }
1246
1247 ice_connection_state_ = state;
1248 if (ice_observer_) {
1249 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1250 }
1251}
1252
1253void WebRtcSession::OnTransportRequestSignaling(
1254 cricket::Transport* transport) {
1255 ASSERT(signaling_thread()->IsCurrent());
1256 transport->OnSignalingReady();
1257 if (ice_observer_) {
1258 ice_observer_->OnIceGatheringChange(
1259 PeerConnectionInterface::kIceGatheringGathering);
1260 }
1261}
1262
1263void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1264 ASSERT(signaling_thread()->IsCurrent());
1265 // start monitoring for the write state of the transport.
1266 OnTransportWritable(transport);
1267}
1268
1269void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1270 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001272 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001273 } else if (transport->HasChannels()) {
1274 // If the current state is Connected or Completed, then there were writable
1275 // channels but now there are not, so the next state must be Disconnected.
1276 if (ice_connection_state_ ==
1277 PeerConnectionInterface::kIceConnectionConnected ||
1278 ice_connection_state_ ==
1279 PeerConnectionInterface::kIceConnectionCompleted) {
1280 SetIceConnectionState(
1281 PeerConnectionInterface::kIceConnectionDisconnected);
1282 }
1283 }
1284}
1285
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001286void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1287 ASSERT(signaling_thread()->IsCurrent());
1288 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1289}
1290
1291void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1292 ASSERT(signaling_thread()->IsCurrent());
1293 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1294}
1295
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296void WebRtcSession::OnTransportProxyCandidatesReady(
1297 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1298 ASSERT(signaling_thread()->IsCurrent());
1299 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1300}
1301
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302void WebRtcSession::OnCandidatesAllocationDone() {
1303 ASSERT(signaling_thread()->IsCurrent());
1304 if (ice_observer_) {
1305 ice_observer_->OnIceGatheringChange(
1306 PeerConnectionInterface::kIceGatheringComplete);
1307 ice_observer_->OnIceComplete();
1308 }
1309}
1310
1311// Enabling voice and video channel.
1312void WebRtcSession::EnableChannels() {
1313 if (voice_channel_ && !voice_channel_->enabled())
1314 voice_channel_->Enable(true);
1315
1316 if (video_channel_ && !video_channel_->enabled())
1317 video_channel_->Enable(true);
1318
1319 if (data_channel_.get() && !data_channel_->enabled())
1320 data_channel_->Enable(true);
1321}
1322
1323void WebRtcSession::ProcessNewLocalCandidate(
1324 const std::string& content_name,
1325 const cricket::Candidates& candidates) {
1326 int sdp_mline_index;
1327 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1328 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1329 << content_name << " not found";
1330 return;
1331 }
1332
1333 for (cricket::Candidates::const_iterator citer = candidates.begin();
1334 citer != candidates.end(); ++citer) {
1335 // Use content_name as the candidate media id.
1336 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1337 if (ice_observer_) {
1338 ice_observer_->OnIceCandidate(&candidate);
1339 }
1340 if (local_desc_) {
1341 local_desc_->AddCandidate(&candidate);
1342 }
1343 }
1344}
1345
1346// Returns the media index for a local ice candidate given the content name.
1347bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1348 int* sdp_mline_index) {
1349 if (!BaseSession::local_description() || !sdp_mline_index)
1350 return false;
1351
1352 bool content_found = false;
1353 const ContentInfos& contents = BaseSession::local_description()->contents();
1354 for (size_t index = 0; index < contents.size(); ++index) {
1355 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001356 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 content_found = true;
1358 break;
1359 }
1360 }
1361 return content_found;
1362}
1363
1364bool WebRtcSession::UseCandidatesInSessionDescription(
1365 const SessionDescriptionInterface* remote_desc) {
1366 if (!remote_desc)
1367 return true;
1368 bool ret = true;
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1371 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1372 for (size_t n = 0; n < candidates->count(); ++n) {
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001373 const IceCandidateInterface* candidate = candidates->at(n);
1374 bool valid = false;
1375 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
1376 if (valid) {
1377 LOG(LS_INFO) << "UseCandidatesInSessionDescription: Candidate saved.";
1378 saved_candidates_.push_back(
1379 new JsepIceCandidate(candidate->sdp_mid(),
1380 candidate->sdp_mline_index(),
1381 candidate->candidate()));
1382 }
1383 continue;
1384 }
1385
1386 ret = UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 if (!ret)
1388 break;
1389 }
1390 }
1391 return ret;
1392}
1393
1394bool WebRtcSession::UseCandidate(
1395 const IceCandidateInterface* candidate) {
1396
1397 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1398 size_t remote_content_size =
1399 BaseSession::remote_description()->contents().size();
1400 if (mediacontent_index >= remote_content_size) {
1401 LOG(LS_ERROR)
1402 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1403 return false;
1404 }
1405
1406 cricket::ContentInfo content =
1407 BaseSession::remote_description()->contents()[mediacontent_index];
1408 std::vector<cricket::Candidate> candidates;
1409 candidates.push_back(candidate->candidate());
1410 // Invoking BaseSession method to handle remote candidates.
1411 std::string error;
1412 if (OnRemoteCandidates(content.name, candidates, &error)) {
1413 // Candidates successfully submitted for checking.
1414 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1415 ice_connection_state_ ==
1416 PeerConnectionInterface::kIceConnectionDisconnected) {
1417 // If state is New, then the session has just gotten its first remote ICE
1418 // candidates, so go to Checking.
1419 // If state is Disconnected, the session is re-using old candidates or
1420 // receiving additional ones, so go to Checking.
1421 // If state is Connected, stay Connected.
1422 // TODO(bemasc): If state is Connected, and the new candidates are for a
1423 // newly added transport, then the state actually _should_ move to
1424 // checking. Add a way to distinguish that case.
1425 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1426 }
1427 // TODO(bemasc): If state is Completed, go back to Connected.
1428 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001429 if (!error.empty()) {
1430 LOG(LS_WARNING) << error;
1431 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 }
1433 return true;
1434}
1435
1436void WebRtcSession::RemoveUnusedChannelsAndTransports(
1437 const SessionDescription* desc) {
1438 const cricket::ContentInfo* voice_info =
1439 cricket::GetFirstAudioContent(desc);
1440 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1441 mediastream_signaling_->OnAudioChannelClose();
1442 SignalVoiceChannelDestroyed();
1443 const std::string content_name = voice_channel_->content_name();
1444 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1445 DestroyTransportProxy(content_name);
1446 }
1447
1448 const cricket::ContentInfo* video_info =
1449 cricket::GetFirstVideoContent(desc);
1450 if ((!video_info || video_info->rejected) && video_channel_) {
1451 mediastream_signaling_->OnVideoChannelClose();
1452 SignalVideoChannelDestroyed();
1453 const std::string content_name = video_channel_->content_name();
1454 channel_manager_->DestroyVideoChannel(video_channel_.release());
1455 DestroyTransportProxy(content_name);
1456 }
1457
1458 const cricket::ContentInfo* data_info =
1459 cricket::GetFirstDataContent(desc);
1460 if ((!data_info || data_info->rejected) && data_channel_) {
1461 mediastream_signaling_->OnDataChannelClose();
1462 SignalDataChannelDestroyed();
1463 const std::string content_name = data_channel_->content_name();
1464 channel_manager_->DestroyDataChannel(data_channel_.release());
1465 DestroyTransportProxy(content_name);
1466 }
1467}
1468
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001469// TODO(mallinath) - Add a correct error code if the channels are not creatued
1470// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1472 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001473 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1474 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475 port_allocator()->set_flags(port_allocator()->flags() &
1476 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1477 }
1478
1479 // Creating the media channels and transport proxies.
1480 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1481 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001482 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483 LOG(LS_ERROR) << "Failed to create voice channel.";
1484 return false;
1485 }
1486 }
1487
1488 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1489 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001490 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001491 LOG(LS_ERROR) << "Failed to create video channel.";
1492 return false;
1493 }
1494 }
1495
1496 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1497 if (data_channel_type_ != cricket::DCT_NONE &&
1498 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001499 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001500 LOG(LS_ERROR) << "Failed to create data channel.";
1501 return false;
1502 }
1503 }
1504
1505 return true;
1506}
1507
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001508bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001510 this, content->name, true));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001511 if (!voice_channel_.get())
1512 return false;
1513
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001514 voice_channel_->SetChannelOptions(audio_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001515 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001516}
1517
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001518bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001520 this, content->name, true, voice_channel_.get()));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001521 if (!video_channel_.get())
1522 return false;
1523
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001524 video_channel_->SetChannelOptions(video_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001525 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001526}
1527
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001528bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001529 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001530 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001531 this, content->name, !sctp, data_channel_type_));
wu@webrtc.org91053e72013-08-10 07:18:04 +00001532 if (!data_channel_.get()) {
1533 return false;
1534 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001535 if (sctp) {
1536 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001537 data_channel_->SignalDataReceived.connect(
1538 this, &WebRtcSession::OnDataChannelMessageReceived);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +00001539 data_channel_->SignalStreamClosedRemotely.connect(
1540 mediastream_signaling_,
1541 &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001542 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001543 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001544}
1545
1546void WebRtcSession::CopySavedCandidates(
1547 SessionDescriptionInterface* dest_desc) {
1548 if (!dest_desc) {
1549 ASSERT(false);
1550 return;
1551 }
1552 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1553 dest_desc->AddCandidate(saved_candidates_[i]);
1554 delete saved_candidates_[i];
1555 }
1556 saved_candidates_.clear();
1557}
1558
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001559void WebRtcSession::OnDataChannelMessageReceived(
1560 cricket::DataChannel* channel,
1561 const cricket::ReceiveDataParams& params,
1562 const talk_base::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001563 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001564 if (params.type == cricket::DMT_CONTROL &&
1565 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1566 // Received CONTROL on unused sid, process as an OPEN message.
1567 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001569 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570}
1571
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001572// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001573bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001574 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1575 if (!bundle_enabled)
1576 return true;
1577
1578 const cricket::ContentGroup* bundle_group =
1579 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1580 ASSERT(bundle_group != NULL);
1581
1582 const cricket::ContentInfos& contents = desc->contents();
1583 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1584 citer != contents.end(); ++citer) {
1585 const cricket::ContentInfo* content = (&*citer);
1586 ASSERT(content != NULL);
1587 if (bundle_group->HasContentName(content->name) &&
1588 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1589 if (!HasRtcpMuxEnabled(content))
1590 return false;
1591 }
1592 }
1593 // RTCP-MUX is enabled in all the contents.
1594 return true;
1595}
1596
1597bool WebRtcSession::HasRtcpMuxEnabled(
1598 const cricket::ContentInfo* content) {
1599 const cricket::MediaContentDescription* description =
1600 static_cast<cricket::MediaContentDescription*>(content->description);
1601 return description->rtcp_mux();
1602}
1603
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001604bool WebRtcSession::ValidateSessionDescription(
1605 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001606 cricket::ContentSource source, std::string* err_desc) {
1607 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001608 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001609 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001610 }
1611
1612 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001613 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001614 }
1615
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001616 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001617 Action action = GetAction(sdesc->type());
1618 if (source == cricket::CS_LOCAL) {
1619 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001620 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001621 } else {
1622 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001623 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001624 }
1625
1626 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001627 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001628 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1629 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001630 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001631 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001632 }
1633
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001634 // Verify ice-ufrag and ice-pwd.
1635 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001636 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001637 }
1638
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001639 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001640 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001641 }
1642
1643 // Verify m-lines in Answer when compared against Offer.
1644 if (action == kAnswer) {
1645 const cricket::SessionDescription* offer_desc =
1646 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1647 local_description()->description();
1648 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001649 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001650 }
1651 }
1652
1653 return true;
1654}
1655
1656bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1657 return ((action == kOffer && state() == STATE_INIT) ||
1658 // update local offer
1659 (action == kOffer && state() == STATE_SENTINITIATE) ||
1660 // update the current ongoing session.
1661 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1662 (action == kOffer && state() == STATE_SENTACCEPT) ||
1663 (action == kOffer && state() == STATE_INPROGRESS) ||
1664 // accept remote offer
1665 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1666 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1667 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1668 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1669}
1670
1671bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1672 return ((action == kOffer && state() == STATE_INIT) ||
1673 // update remote offer
1674 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1675 // update the current ongoing session
1676 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1677 (action == kOffer && state() == STATE_SENTACCEPT) ||
1678 (action == kOffer && state() == STATE_INPROGRESS) ||
1679 // accept local offer
1680 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1681 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1682 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1683 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1684}
1685
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001686std::string WebRtcSession::GetSessionErrorMsg() {
1687 std::ostringstream desc;
1688 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1689 desc << kSessionErrorDesc << error_desc() << ".";
1690 return desc.str();
1691}
1692
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001693// We need to check the local/remote description for the Transport instead of
1694// the session, because a new Transport added during renegotiation may have
1695// them unset while the session has them set from the previous negotiation.
1696// Not doing so may trigger the auto generation of transport description and
1697// mess up DTLS identity information, ICE credential, etc.
1698bool WebRtcSession::ReadyToUseRemoteCandidate(
1699 const IceCandidateInterface* candidate,
1700 const SessionDescriptionInterface* remote_desc,
1701 bool* valid) {
1702 *valid = true;;
1703 cricket::TransportProxy* transport_proxy = NULL;
1704
1705 const SessionDescriptionInterface* current_remote_desc =
1706 remote_desc ? remote_desc : remote_description();
1707
1708 if (!current_remote_desc)
1709 return false;
1710
1711 size_t mediacontent_index =
1712 static_cast<size_t>(candidate->sdp_mline_index());
1713 size_t remote_content_size =
1714 current_remote_desc->description()->contents().size();
1715 if (mediacontent_index >= remote_content_size) {
1716 LOG(LS_ERROR)
1717 << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
1718
1719 *valid = false;
1720 return false;
1721 }
1722
1723 cricket::ContentInfo content =
1724 current_remote_desc->description()->contents()[mediacontent_index];
1725 transport_proxy = GetTransportProxy(content.name);
1726
1727 return transport_proxy && transport_proxy->local_description_set() &&
1728 transport_proxy->remote_description_set();
1729}
1730
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731} // namespace webrtc