blob: 6d57afbcbc8915cf3073c2d8cac151f6ff65326e [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() {
474 if (voice_channel_.get()) {
475 SignalVoiceChannelDestroyed();
476 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
477 }
478 if (video_channel_.get()) {
479 SignalVideoChannelDestroyed();
480 channel_manager_->DestroyVideoChannel(video_channel_.release());
481 }
482 if (data_channel_.get()) {
483 SignalDataChannelDestroyed();
484 channel_manager_->DestroyDataChannel(data_channel_.release());
485 }
486 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
487 delete saved_candidates_[i];
488 }
489 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000490}
491
wu@webrtc.org91053e72013-08-10 07:18:04 +0000492bool WebRtcSession::Initialize(
wu@webrtc.org97077a32013-10-25 21:18:33 +0000493 const PeerConnectionFactoryInterface::Options& options,
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000494 const MediaConstraintsInterface* constraints,
495 DTLSIdentityServiceInterface* dtls_identity_service,
496 PeerConnectionInterface::IceTransportsType ice_transport) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000497 // TODO(perkj): Take |constraints| into consideration. Return false if not all
498 // mandatory constraints can be fulfilled. Note that |constraints|
499 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000500 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000501
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000502 if (options.disable_encryption) {
503 dtls_enabled_ = false;
504 } else {
505 // Enable DTLS by default if |dtls_identity_service| is valid.
506 dtls_enabled_ = (dtls_identity_service != NULL);
507 // |constraints| can override the default |dtls_enabled_| value.
508 if (FindConstraint(
509 constraints,
510 MediaConstraintsInterface::kEnableDtlsSrtp,
511 &value, NULL)) {
512 dtls_enabled_ = value;
513 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000514 }
515
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000516 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000517 // It takes precendence over the disable_sctp_data_channels
518 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000519 if (FindConstraint(
520 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
521 &value, NULL) && value) {
522 LOG(LS_INFO) << "Allowing RTP data engine.";
523 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000524 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000525 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000526 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000527 LOG(LS_INFO) << "Allowing SCTP data engine.";
528 data_channel_type_ = cricket::DCT_SCTP;
529 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000530 }
531 if (data_channel_type_ != cricket::DCT_NONE) {
532 mediastream_signaling_->SetDataChannelFactory(this);
533 }
534
wu@webrtc.orgde305012013-10-31 15:40:38 +0000535 // Find DSCP constraint.
536 if (FindConstraint(
537 constraints,
538 MediaConstraintsInterface::kEnableDscp,
539 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000540 audio_options_.dscp.Set(value);
541 video_options_.dscp.Set(value);
542 }
543
544 // Find Suspend Below Min Bitrate constraint.
545 if (FindConstraint(
546 constraints,
547 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
548 &value,
549 NULL)) {
550 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000551 }
552
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000553 SetOptionFromOptionalConstraint(constraints,
554 MediaConstraintsInterface::kScreencastMinBitrate,
555 &video_options_.screencast_min_bitrate);
556
557 // Find constraints for cpu overuse detection.
558 SetOptionFromOptionalConstraint(constraints,
559 MediaConstraintsInterface::kCpuUnderuseThreshold,
560 &video_options_.cpu_underuse_threshold);
561 SetOptionFromOptionalConstraint(constraints,
562 MediaConstraintsInterface::kCpuOveruseThreshold,
563 &video_options_.cpu_overuse_threshold);
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000564 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000565 MediaConstraintsInterface::kCpuOveruseDetection,
566 &video_options_.cpu_overuse_detection);
567 SetOptionFromOptionalConstraint(constraints,
568 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
569 &video_options_.cpu_overuse_encode_usage);
570 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org27626a62014-06-16 13:39:40 +0000571 MediaConstraintsInterface::kCpuUnderuseEncodeRsdThreshold,
572 &video_options_.cpu_underuse_encode_rsd_threshold);
573 SetOptionFromOptionalConstraint(constraints,
574 MediaConstraintsInterface::kCpuOveruseEncodeRsdThreshold,
575 &video_options_.cpu_overuse_encode_rsd_threshold);
buildbot@webrtc.orgdb563902014-06-13 13:05:48 +0000576
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000577 // Find payload padding constraint.
578 SetOptionFromOptionalConstraint(constraints,
579 MediaConstraintsInterface::kPayloadPadding,
580 &video_options_.use_payload_padding);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000581
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000582 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org53df88c2014-08-07 22:46:01 +0000583 MediaConstraintsInterface::kNumUnsignalledRecvStreams,
584 &video_options_.unsignalled_recv_stream_limit);
585 if (video_options_.unsignalled_recv_stream_limit.IsSet()) {
586 int stream_limit;
587 video_options_.unsignalled_recv_stream_limit.Get(&stream_limit);
588 stream_limit = rtc::_min(kMaxUnsignalledRecvStreams, stream_limit);
589 stream_limit = rtc::_max(0, stream_limit);
590 video_options_.unsignalled_recv_stream_limit.Set(stream_limit);
591 }
592
593 SetOptionFromOptionalConstraint(constraints,
buildbot@webrtc.org44a317a2014-06-17 07:49:15 +0000594 MediaConstraintsInterface::kHighStartBitrate,
595 &video_options_.video_start_bitrate);
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000596
597 if (FindConstraint(
598 constraints,
599 MediaConstraintsInterface::kVeryHighBitrate,
600 &value,
601 NULL)) {
602 video_options_.video_highest_bitrate.Set(
603 cricket::VideoOptions::VERY_HIGH);
604 } else if (FindConstraint(
605 constraints,
606 MediaConstraintsInterface::kHighBitrate,
607 &value,
608 NULL)) {
609 video_options_.video_highest_bitrate.Set(
610 cricket::VideoOptions::HIGH);
611 }
612
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000613 const cricket::VideoCodec default_codec(
614 JsepSessionDescription::kDefaultVideoCodecId,
615 JsepSessionDescription::kDefaultVideoCodecName,
616 JsepSessionDescription::kMaxVideoCodecWidth,
617 JsepSessionDescription::kMaxVideoCodecHeight,
618 JsepSessionDescription::kDefaultVideoCodecFramerate,
619 JsepSessionDescription::kDefaultVideoCodecPreference);
620 channel_manager_->SetDefaultVideoEncoderConfig(
621 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000622
623 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
624 signaling_thread(),
625 channel_manager_,
626 mediastream_signaling_,
627 dtls_identity_service,
628 this,
629 id(),
630 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000631 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000632
633 webrtc_session_desc_factory_->SignalIdentityReady.connect(
634 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000635
wu@webrtc.org97077a32013-10-25 21:18:33 +0000636 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000637 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000638 }
639
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 return true;
641}
642
643void WebRtcSession::Terminate() {
644 SetState(STATE_RECEIVEDTERMINATE);
645 RemoveUnusedChannelsAndTransports(NULL);
646 ASSERT(voice_channel_.get() == NULL);
647 ASSERT(video_channel_.get() == NULL);
648 ASSERT(data_channel_.get() == NULL);
649}
650
651bool WebRtcSession::StartCandidatesAllocation() {
652 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
653 // from TransportProxy to start gathering ice candidates.
654 SpeculativelyConnectAllTransportChannels();
655 if (!saved_candidates_.empty()) {
656 // If there are saved candidates which arrived before local description is
657 // set, copy those to remote description.
658 CopySavedCandidates(remote_desc_.get());
659 }
660 // Push remote candidates present in remote description to transport channels.
661 UseCandidatesInSessionDescription(remote_desc_.get());
662 return true;
663}
664
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000665void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
666 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667}
668
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000669cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
670 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000671}
672
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000673bool WebRtcSession::GetSslRole(rtc::SSLRole* role) {
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000674 if (local_description() == NULL || remote_description() == NULL) {
675 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
676 << "SSL Role of the session.";
677 return false;
678 }
679
680 // TODO(mallinath) - Return role of each transport, as role may differ from
681 // one another.
682 // In current implementaion we just return the role of first transport in the
683 // transport map.
684 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
685 iter != transport_proxies().end(); ++iter) {
686 if (iter->second->impl()) {
687 return iter->second->impl()->GetSslRole(role);
688 }
689 }
690 return false;
691}
692
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000693void WebRtcSession::CreateOffer(
694 CreateSessionDescriptionObserver* observer,
695 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
696 webrtc_session_desc_factory_->CreateOffer(observer, options);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000697}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000698
wu@webrtc.org91053e72013-08-10 07:18:04 +0000699void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
700 const MediaConstraintsInterface* constraints) {
701 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000702}
703
704bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
705 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000706 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000707 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000708
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000709 // Validate SDP.
710 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
711 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000712 }
713
714 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000715 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716 if (state() == STATE_INIT && action == kOffer) {
717 set_initiator(true);
718 }
719
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000720 cricket::SecurePolicy sdes_policy =
721 webrtc_session_desc_factory_->SdesPolicy();
722 cricket::CryptoType crypto_required = dtls_enabled_ ?
723 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
724 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000726 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727
728 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000729 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730
731 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000732 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733 // TODO(mallinath) - Handle CreateChannel failure, as new local description
734 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000735 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 }
737
738 // Remove channel and transport proxies, if MediaContentDescription is
739 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000740 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000741
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000742 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 return false;
744 }
745 // Kick starting the ice candidates allocation.
746 StartCandidatesAllocation();
747
748 // Update state and SSRC of local MediaStreams and DataChannels based on the
749 // local session description.
750 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
751
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000752 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000753 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
754 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
755 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000757 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000758 }
759 return true;
760}
761
762bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
763 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000764 // Takes the ownership of |desc| regardless of the result.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000765 rtc::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000766
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000767 // Validate SDP.
768 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
769 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000770 }
771
772 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000773 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000774 if (action == kOffer && !CreateChannels(desc->description())) {
775 // TODO(mallinath) - Handle CreateChannel failure, as new local description
776 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000777 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000778 }
779
780 // Remove channel and transport proxies, if MediaContentDescription is
781 // rejected.
782 RemoveUnusedChannelsAndTransports(desc->description());
783
784 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
785 // is called.
786 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000787 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000788 return false;
789 }
790
791 // Update remote MediaStreams.
792 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
793 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000794 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795 }
796
797 // Copy all saved candidates.
798 CopySavedCandidates(desc);
799 // We retain all received candidates.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000800 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
801 remote_desc_.get(), desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000802 // Check if this new SessionDescription contains new ice ufrag and password
803 // that indicates the remote peer requests ice restart.
804 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
805 desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000806 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000807
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000808 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000809 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
810 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
811 }
812
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000814 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000815 }
816 return true;
817}
818
819bool WebRtcSession::UpdateSessionState(
820 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 std::string* err_desc) {
822 // If there's already a pending error then no state transition should happen.
823 // But all call-sites should be verifying this before calling us!
824 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000825 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000827 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
828 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829 }
830 SetState(source == cricket::CS_LOCAL ?
831 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
832 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000833 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834 }
835 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000836 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
837 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838 }
839 EnableChannels();
840 SetState(source == cricket::CS_LOCAL ?
841 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
842 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000843 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000844 }
845 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000846 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
847 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848 }
849 MaybeEnableMuxingSupport();
850 EnableChannels();
851 SetState(source == cricket::CS_LOCAL ?
852 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
853 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000854 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855 }
856 }
857 return true;
858}
859
860WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
861 if (type == SessionDescriptionInterface::kOffer) {
862 return WebRtcSession::kOffer;
863 } else if (type == SessionDescriptionInterface::kPrAnswer) {
864 return WebRtcSession::kPrAnswer;
865 } else if (type == SessionDescriptionInterface::kAnswer) {
866 return WebRtcSession::kAnswer;
867 }
868 ASSERT(false && "unknown action type");
869 return WebRtcSession::kOffer;
870}
871
872bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
873 if (state() == STATE_INIT) {
874 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
875 << "without any offer (local or remote) "
876 << "session description.";
877 return false;
878 }
879
880 if (!candidate) {
881 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
882 return false;
883 }
884
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +0000885 bool valid = false;
886 if (!ReadyToUseRemoteCandidate(candidate, NULL, &valid)) {
887 if (valid) {
888 LOG(LS_INFO) << "ProcessIceMessage: Candidate saved";
889 saved_candidates_.push_back(
890 new JsepIceCandidate(candidate->sdp_mid(),
891 candidate->sdp_mline_index(),
892 candidate->candidate()));
buildbot@webrtc.org61c1b8e2014-04-09 06:06:38 +0000893 }
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +0000894 return valid;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000895 }
896
897 // Add this candidate to the remote session description.
898 if (!remote_desc_->AddCandidate(candidate)) {
899 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
900 return false;
901 }
902
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000903 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000904}
905
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000906bool WebRtcSession::UpdateIce(PeerConnectionInterface::IceTransportsType type) {
907 return false;
908}
909
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000910bool WebRtcSession::GetLocalTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000911 if (!BaseSession::local_description())
912 return false;
913 return webrtc::GetTrackIdBySsrc(
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000914 BaseSession::local_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915}
916
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000917bool WebRtcSession::GetRemoteTrackIdBySsrc(uint32 ssrc, std::string* track_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 if (!BaseSession::remote_description())
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000919 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920 return webrtc::GetTrackIdBySsrc(
xians@webrtc.org4cb01282014-06-12 14:57:05 +0000921 BaseSession::remote_description(), ssrc, track_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922}
923
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000924std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000926 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927 return desc.str();
928}
929
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000930void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
931 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932 ASSERT(signaling_thread()->IsCurrent());
933 if (!voice_channel_) {
934 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
935 return;
936 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000937 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
938 // SetRenderer() can fail if the ssrc does not match any playout channel.
939 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
940 return;
941 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
943 // Allow that SetOutputScaling fail if |enable| is false but assert
944 // otherwise. This in the normal case when the underlying media channel has
945 // already been deleted.
946 ASSERT(enable == false);
947 }
948}
949
950void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000951 const cricket::AudioOptions& options,
952 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953 ASSERT(signaling_thread()->IsCurrent());
954 if (!voice_channel_) {
955 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
956 return;
957 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000958 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
959 // SetRenderer() can fail if the ssrc does not match any send channel.
960 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
961 return;
962 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000963 if (!voice_channel_->MuteStream(ssrc, !enable)) {
964 // Allow that MuteStream fail if |enable| is false but assert otherwise.
965 // This in the normal case when the underlying media channel has already
966 // been deleted.
967 ASSERT(enable == false);
968 return;
969 }
970 if (enable)
971 voice_channel_->SetChannelOptions(options);
972}
973
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000974void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
975 ASSERT(signaling_thread()->IsCurrent());
976 ASSERT(volume >= 0 && volume <= 10);
977 if (!voice_channel_) {
978 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
979 return;
980 }
981
982 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
983 ASSERT(false);
984}
985
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000986bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
987 cricket::VideoCapturer* camera) {
988 ASSERT(signaling_thread()->IsCurrent());
989
990 if (!video_channel_.get()) {
991 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
992 // support video.
993 LOG(LS_WARNING) << "Video not used in this call.";
994 return false;
995 }
996 if (!video_channel_->SetCapturer(ssrc, camera)) {
997 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
998 // This in the normal case when the underlying media channel has already
999 // been deleted.
1000 ASSERT(camera == NULL);
1001 return false;
1002 }
1003 return true;
1004}
1005
1006void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1007 bool enable,
1008 cricket::VideoRenderer* renderer) {
1009 ASSERT(signaling_thread()->IsCurrent());
1010 if (!video_channel_) {
1011 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1012 return;
1013 }
1014 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1015 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1016 // This in the normal case when the underlying media channel has already
1017 // been deleted.
1018 ASSERT(renderer == NULL);
1019 }
1020}
1021
1022void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1023 const cricket::VideoOptions* options) {
1024 ASSERT(signaling_thread()->IsCurrent());
1025 if (!video_channel_) {
1026 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1027 return;
1028 }
1029 if (!video_channel_->MuteStream(ssrc, !enable)) {
1030 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1031 // This in the normal case when the underlying media channel has already
1032 // been deleted.
1033 ASSERT(enable == false);
1034 return;
1035 }
1036 if (enable && options)
1037 video_channel_->SetChannelOptions(*options);
1038}
1039
1040bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1041 ASSERT(signaling_thread()->IsCurrent());
1042 if (!voice_channel_) {
1043 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1044 return false;
1045 }
1046 uint32 send_ssrc = 0;
1047 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1048 // exists.
1049 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1050 &send_ssrc)) {
1051 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1052 return false;
1053 }
1054 return voice_channel_->CanInsertDtmf();
1055}
1056
1057bool WebRtcSession::InsertDtmf(const std::string& track_id,
1058 int code, int duration) {
1059 ASSERT(signaling_thread()->IsCurrent());
1060 if (!voice_channel_) {
1061 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1062 return false;
1063 }
1064 uint32 send_ssrc = 0;
1065 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1066 track_id, &send_ssrc))) {
1067 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1068 return false;
1069 }
1070 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1071 cricket::DF_SEND)) {
1072 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1073 return false;
1074 }
1075 return true;
1076}
1077
1078sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1079 return &SignalVoiceChannelDestroyed;
1080}
1081
wu@webrtc.org78187522013-10-07 23:32:02 +00001082bool WebRtcSession::SendData(const cricket::SendDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001083 const rtc::Buffer& payload,
wu@webrtc.org78187522013-10-07 23:32:02 +00001084 cricket::SendDataResult* result) {
1085 if (!data_channel_.get()) {
1086 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1087 return false;
1088 }
1089 return data_channel_->SendData(params, payload, result);
1090}
1091
1092bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1093 if (!data_channel_.get()) {
1094 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1095 return false;
1096 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001097 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1098 &DataChannel::OnChannelReady);
1099 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1100 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001101 return true;
1102}
1103
1104void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001105 if (!data_channel_.get()) {
1106 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1107 return;
1108 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001109 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1110 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1111}
1112
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001113void WebRtcSession::AddSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001114 if (!data_channel_.get()) {
1115 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1116 return;
1117 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001118 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1119 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001120}
1121
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001122void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
jiayl@webrtc.org2eaac182014-06-17 16:02:46 +00001123 mediastream_signaling_->RemoveSctpDataChannel(static_cast<int>(sid));
1124
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001125 if (!data_channel_.get()) {
1126 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1127 << "NULL.";
1128 return;
1129 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001130 data_channel_->RemoveRecvStream(sid);
1131 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001132}
1133
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001134bool WebRtcSession::ReadyToSendData() const {
1135 return data_channel_.get() && data_channel_->ready_to_send_data();
1136}
1137
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001138rtc::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001139 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001140 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001141 if (state() == STATE_RECEIVEDTERMINATE) {
1142 return NULL;
1143 }
1144 if (data_channel_type_ == cricket::DCT_NONE) {
1145 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1146 return NULL;
1147 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001148 InternalDataChannelInit new_config =
1149 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001150 if (data_channel_type_ == cricket::DCT_SCTP) {
1151 if (new_config.id < 0) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001152 rtc::SSLRole role;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001153 if (GetSslRole(&role) &&
1154 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001155 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1156 return NULL;
1157 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001158 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001159 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1160 << "because the id is already in use or out of range.";
1161 return NULL;
1162 }
1163 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001164
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001165 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001166 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001167 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001168 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001169
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001170 return channel;
1171}
1172
1173cricket::DataChannelType WebRtcSession::data_channel_type() const {
1174 return data_channel_type_;
1175}
1176
wu@webrtc.org91053e72013-08-10 07:18:04 +00001177bool WebRtcSession::IceRestartPending() const {
1178 return ice_restart_latch_->Get();
1179}
1180
1181void WebRtcSession::ResetIceRestartLatch() {
1182 ice_restart_latch_->Reset();
1183}
1184
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001185void WebRtcSession::OnIdentityReady(rtc::SSLIdentity* identity) {
wu@webrtc.org91053e72013-08-10 07:18:04 +00001186 SetIdentity(identity);
1187}
1188
1189bool WebRtcSession::waiting_for_identity() const {
1190 return webrtc_session_desc_factory_->waiting_for_identity();
1191}
1192
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001193void WebRtcSession::SetIceConnectionState(
1194 PeerConnectionInterface::IceConnectionState state) {
1195 if (ice_connection_state_ == state) {
1196 return;
1197 }
1198
1199 // ASSERT that the requested transition is allowed. Note that
1200 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1201 // within PeerConnection). This switch statement should compile away when
1202 // ASSERTs are disabled.
1203 switch (ice_connection_state_) {
1204 case PeerConnectionInterface::kIceConnectionNew:
1205 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1206 break;
1207 case PeerConnectionInterface::kIceConnectionChecking:
1208 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1209 state == PeerConnectionInterface::kIceConnectionConnected);
1210 break;
1211 case PeerConnectionInterface::kIceConnectionConnected:
1212 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1213 state == PeerConnectionInterface::kIceConnectionChecking ||
1214 state == PeerConnectionInterface::kIceConnectionCompleted);
1215 break;
1216 case PeerConnectionInterface::kIceConnectionCompleted:
1217 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1218 state == PeerConnectionInterface::kIceConnectionDisconnected);
1219 break;
1220 case PeerConnectionInterface::kIceConnectionFailed:
1221 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1222 break;
1223 case PeerConnectionInterface::kIceConnectionDisconnected:
1224 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1225 state == PeerConnectionInterface::kIceConnectionConnected ||
1226 state == PeerConnectionInterface::kIceConnectionCompleted ||
1227 state == PeerConnectionInterface::kIceConnectionFailed);
1228 break;
1229 case PeerConnectionInterface::kIceConnectionClosed:
1230 ASSERT(false);
1231 break;
1232 default:
1233 ASSERT(false);
1234 break;
1235 }
1236
1237 ice_connection_state_ = state;
1238 if (ice_observer_) {
1239 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1240 }
1241}
1242
1243void WebRtcSession::OnTransportRequestSignaling(
1244 cricket::Transport* transport) {
1245 ASSERT(signaling_thread()->IsCurrent());
1246 transport->OnSignalingReady();
1247 if (ice_observer_) {
1248 ice_observer_->OnIceGatheringChange(
1249 PeerConnectionInterface::kIceGatheringGathering);
1250 }
1251}
1252
1253void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1254 ASSERT(signaling_thread()->IsCurrent());
1255 // start monitoring for the write state of the transport.
1256 OnTransportWritable(transport);
1257}
1258
1259void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1260 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001261 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001262 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001263 } else if (transport->HasChannels()) {
1264 // If the current state is Connected or Completed, then there were writable
1265 // channels but now there are not, so the next state must be Disconnected.
1266 if (ice_connection_state_ ==
1267 PeerConnectionInterface::kIceConnectionConnected ||
1268 ice_connection_state_ ==
1269 PeerConnectionInterface::kIceConnectionCompleted) {
1270 SetIceConnectionState(
1271 PeerConnectionInterface::kIceConnectionDisconnected);
1272 }
1273 }
1274}
1275
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001276void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1277 ASSERT(signaling_thread()->IsCurrent());
1278 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1279}
1280
1281void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1282 ASSERT(signaling_thread()->IsCurrent());
1283 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1284}
1285
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286void WebRtcSession::OnTransportProxyCandidatesReady(
1287 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1288 ASSERT(signaling_thread()->IsCurrent());
1289 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1290}
1291
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001292void WebRtcSession::OnCandidatesAllocationDone() {
1293 ASSERT(signaling_thread()->IsCurrent());
1294 if (ice_observer_) {
1295 ice_observer_->OnIceGatheringChange(
1296 PeerConnectionInterface::kIceGatheringComplete);
1297 ice_observer_->OnIceComplete();
1298 }
1299}
1300
1301// Enabling voice and video channel.
1302void WebRtcSession::EnableChannels() {
1303 if (voice_channel_ && !voice_channel_->enabled())
1304 voice_channel_->Enable(true);
1305
1306 if (video_channel_ && !video_channel_->enabled())
1307 video_channel_->Enable(true);
1308
1309 if (data_channel_.get() && !data_channel_->enabled())
1310 data_channel_->Enable(true);
1311}
1312
1313void WebRtcSession::ProcessNewLocalCandidate(
1314 const std::string& content_name,
1315 const cricket::Candidates& candidates) {
1316 int sdp_mline_index;
1317 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1318 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1319 << content_name << " not found";
1320 return;
1321 }
1322
1323 for (cricket::Candidates::const_iterator citer = candidates.begin();
1324 citer != candidates.end(); ++citer) {
1325 // Use content_name as the candidate media id.
1326 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1327 if (ice_observer_) {
1328 ice_observer_->OnIceCandidate(&candidate);
1329 }
1330 if (local_desc_) {
1331 local_desc_->AddCandidate(&candidate);
1332 }
1333 }
1334}
1335
1336// Returns the media index for a local ice candidate given the content name.
1337bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1338 int* sdp_mline_index) {
1339 if (!BaseSession::local_description() || !sdp_mline_index)
1340 return false;
1341
1342 bool content_found = false;
1343 const ContentInfos& contents = BaseSession::local_description()->contents();
1344 for (size_t index = 0; index < contents.size(); ++index) {
1345 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001346 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 content_found = true;
1348 break;
1349 }
1350 }
1351 return content_found;
1352}
1353
1354bool WebRtcSession::UseCandidatesInSessionDescription(
1355 const SessionDescriptionInterface* remote_desc) {
1356 if (!remote_desc)
1357 return true;
1358 bool ret = true;
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001359
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1361 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1362 for (size_t n = 0; n < candidates->count(); ++n) {
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001363 const IceCandidateInterface* candidate = candidates->at(n);
1364 bool valid = false;
1365 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
1366 if (valid) {
1367 LOG(LS_INFO) << "UseCandidatesInSessionDescription: Candidate saved.";
1368 saved_candidates_.push_back(
1369 new JsepIceCandidate(candidate->sdp_mid(),
1370 candidate->sdp_mline_index(),
1371 candidate->candidate()));
1372 }
1373 continue;
1374 }
1375
1376 ret = UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001377 if (!ret)
1378 break;
1379 }
1380 }
1381 return ret;
1382}
1383
1384bool WebRtcSession::UseCandidate(
1385 const IceCandidateInterface* candidate) {
1386
1387 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1388 size_t remote_content_size =
1389 BaseSession::remote_description()->contents().size();
1390 if (mediacontent_index >= remote_content_size) {
1391 LOG(LS_ERROR)
1392 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1393 return false;
1394 }
1395
1396 cricket::ContentInfo content =
1397 BaseSession::remote_description()->contents()[mediacontent_index];
1398 std::vector<cricket::Candidate> candidates;
1399 candidates.push_back(candidate->candidate());
1400 // Invoking BaseSession method to handle remote candidates.
1401 std::string error;
1402 if (OnRemoteCandidates(content.name, candidates, &error)) {
1403 // Candidates successfully submitted for checking.
1404 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1405 ice_connection_state_ ==
1406 PeerConnectionInterface::kIceConnectionDisconnected) {
1407 // If state is New, then the session has just gotten its first remote ICE
1408 // candidates, so go to Checking.
1409 // If state is Disconnected, the session is re-using old candidates or
1410 // receiving additional ones, so go to Checking.
1411 // If state is Connected, stay Connected.
1412 // TODO(bemasc): If state is Connected, and the new candidates are for a
1413 // newly added transport, then the state actually _should_ move to
1414 // checking. Add a way to distinguish that case.
1415 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1416 }
1417 // TODO(bemasc): If state is Completed, go back to Connected.
1418 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001419 if (!error.empty()) {
1420 LOG(LS_WARNING) << error;
1421 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422 }
1423 return true;
1424}
1425
1426void WebRtcSession::RemoveUnusedChannelsAndTransports(
1427 const SessionDescription* desc) {
1428 const cricket::ContentInfo* voice_info =
1429 cricket::GetFirstAudioContent(desc);
1430 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1431 mediastream_signaling_->OnAudioChannelClose();
1432 SignalVoiceChannelDestroyed();
1433 const std::string content_name = voice_channel_->content_name();
1434 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1435 DestroyTransportProxy(content_name);
1436 }
1437
1438 const cricket::ContentInfo* video_info =
1439 cricket::GetFirstVideoContent(desc);
1440 if ((!video_info || video_info->rejected) && video_channel_) {
1441 mediastream_signaling_->OnVideoChannelClose();
1442 SignalVideoChannelDestroyed();
1443 const std::string content_name = video_channel_->content_name();
1444 channel_manager_->DestroyVideoChannel(video_channel_.release());
1445 DestroyTransportProxy(content_name);
1446 }
1447
1448 const cricket::ContentInfo* data_info =
1449 cricket::GetFirstDataContent(desc);
1450 if ((!data_info || data_info->rejected) && data_channel_) {
1451 mediastream_signaling_->OnDataChannelClose();
1452 SignalDataChannelDestroyed();
1453 const std::string content_name = data_channel_->content_name();
1454 channel_manager_->DestroyDataChannel(data_channel_.release());
1455 DestroyTransportProxy(content_name);
1456 }
1457}
1458
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001459// TODO(mallinath) - Add a correct error code if the channels are not creatued
1460// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1462 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001463 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1464 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465 port_allocator()->set_flags(port_allocator()->flags() &
1466 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1467 }
1468
1469 // Creating the media channels and transport proxies.
1470 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1471 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001472 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 LOG(LS_ERROR) << "Failed to create voice channel.";
1474 return false;
1475 }
1476 }
1477
1478 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1479 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001480 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001481 LOG(LS_ERROR) << "Failed to create video channel.";
1482 return false;
1483 }
1484 }
1485
1486 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1487 if (data_channel_type_ != cricket::DCT_NONE &&
1488 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001489 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490 LOG(LS_ERROR) << "Failed to create data channel.";
1491 return false;
1492 }
1493 }
1494
1495 return true;
1496}
1497
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001498bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001500 this, content->name, true));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001501 if (!voice_channel_.get())
1502 return false;
1503
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001504 voice_channel_->SetChannelOptions(audio_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001505 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001506}
1507
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001508bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001510 this, content->name, true, voice_channel_.get()));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001511 if (!video_channel_.get())
1512 return false;
1513
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001514 video_channel_->SetChannelOptions(video_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::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001519 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001520 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001521 this, content->name, !sctp, data_channel_type_));
wu@webrtc.org91053e72013-08-10 07:18:04 +00001522 if (!data_channel_.get()) {
1523 return false;
1524 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001525 if (sctp) {
1526 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001527 data_channel_->SignalDataReceived.connect(
1528 this, &WebRtcSession::OnDataChannelMessageReceived);
buildbot@webrtc.org1d66be22014-05-29 22:54:24 +00001529 data_channel_->SignalStreamClosedRemotely.connect(
1530 mediastream_signaling_,
1531 &MediaStreamSignaling::OnRemoteSctpDataChannelClosed);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001532 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001533 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001534}
1535
1536void WebRtcSession::CopySavedCandidates(
1537 SessionDescriptionInterface* dest_desc) {
1538 if (!dest_desc) {
1539 ASSERT(false);
1540 return;
1541 }
1542 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1543 dest_desc->AddCandidate(saved_candidates_[i]);
1544 delete saved_candidates_[i];
1545 }
1546 saved_candidates_.clear();
1547}
1548
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001549void WebRtcSession::OnDataChannelMessageReceived(
1550 cricket::DataChannel* channel,
1551 const cricket::ReceiveDataParams& params,
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001552 const rtc::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001553 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001554 if (params.type == cricket::DMT_CONTROL &&
1555 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1556 // Received CONTROL on unused sid, process as an OPEN message.
1557 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001558 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001559 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560}
1561
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001562// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001563bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001564 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1565 if (!bundle_enabled)
1566 return true;
1567
1568 const cricket::ContentGroup* bundle_group =
1569 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1570 ASSERT(bundle_group != NULL);
1571
1572 const cricket::ContentInfos& contents = desc->contents();
1573 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1574 citer != contents.end(); ++citer) {
1575 const cricket::ContentInfo* content = (&*citer);
1576 ASSERT(content != NULL);
1577 if (bundle_group->HasContentName(content->name) &&
1578 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1579 if (!HasRtcpMuxEnabled(content))
1580 return false;
1581 }
1582 }
1583 // RTCP-MUX is enabled in all the contents.
1584 return true;
1585}
1586
1587bool WebRtcSession::HasRtcpMuxEnabled(
1588 const cricket::ContentInfo* content) {
1589 const cricket::MediaContentDescription* description =
1590 static_cast<cricket::MediaContentDescription*>(content->description);
1591 return description->rtcp_mux();
1592}
1593
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001594bool WebRtcSession::ValidateSessionDescription(
1595 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001596 cricket::ContentSource source, std::string* err_desc) {
1597 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001598 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001599 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001600 }
1601
1602 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001603 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001604 }
1605
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001606 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001607 Action action = GetAction(sdesc->type());
1608 if (source == cricket::CS_LOCAL) {
1609 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001610 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001611 } else {
1612 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001613 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001614 }
1615
1616 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001617 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001618 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1619 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001620 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001621 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001622 }
1623
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001624 // Verify ice-ufrag and ice-pwd.
1625 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001626 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001627 }
1628
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001629 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001630 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001631 }
1632
1633 // Verify m-lines in Answer when compared against Offer.
1634 if (action == kAnswer) {
1635 const cricket::SessionDescription* offer_desc =
1636 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1637 local_description()->description();
1638 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001639 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001640 }
1641 }
1642
1643 return true;
1644}
1645
1646bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1647 return ((action == kOffer && state() == STATE_INIT) ||
1648 // update local offer
1649 (action == kOffer && state() == STATE_SENTINITIATE) ||
1650 // update the current ongoing session.
1651 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1652 (action == kOffer && state() == STATE_SENTACCEPT) ||
1653 (action == kOffer && state() == STATE_INPROGRESS) ||
1654 // accept remote offer
1655 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1656 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1657 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1658 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1659}
1660
1661bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1662 return ((action == kOffer && state() == STATE_INIT) ||
1663 // update remote offer
1664 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1665 // update the current ongoing session
1666 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1667 (action == kOffer && state() == STATE_SENTACCEPT) ||
1668 (action == kOffer && state() == STATE_INPROGRESS) ||
1669 // accept local offer
1670 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1671 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1672 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1673 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1674}
1675
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001676std::string WebRtcSession::GetSessionErrorMsg() {
1677 std::ostringstream desc;
1678 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1679 desc << kSessionErrorDesc << error_desc() << ".";
1680 return desc.str();
1681}
1682
jiayl@webrtc.orge10d28c2014-07-17 17:07:49 +00001683// We need to check the local/remote description for the Transport instead of
1684// the session, because a new Transport added during renegotiation may have
1685// them unset while the session has them set from the previous negotiation.
1686// Not doing so may trigger the auto generation of transport description and
1687// mess up DTLS identity information, ICE credential, etc.
1688bool WebRtcSession::ReadyToUseRemoteCandidate(
1689 const IceCandidateInterface* candidate,
1690 const SessionDescriptionInterface* remote_desc,
1691 bool* valid) {
1692 *valid = true;;
1693 cricket::TransportProxy* transport_proxy = NULL;
1694
1695 const SessionDescriptionInterface* current_remote_desc =
1696 remote_desc ? remote_desc : remote_description();
1697
1698 if (!current_remote_desc)
1699 return false;
1700
1701 size_t mediacontent_index =
1702 static_cast<size_t>(candidate->sdp_mline_index());
1703 size_t remote_content_size =
1704 current_remote_desc->description()->contents().size();
1705 if (mediacontent_index >= remote_content_size) {
1706 LOG(LS_ERROR)
1707 << "ReadyToUseRemoteCandidate: Invalid candidate media index.";
1708
1709 *valid = false;
1710 return false;
1711 }
1712
1713 cricket::ContentInfo content =
1714 current_remote_desc->description()->contents()[mediacontent_index];
1715 transport_proxy = GetTransportProxy(content.name);
1716
1717 return transport_proxy && transport_proxy->local_description_set() &&
1718 transport_proxy->remote_description_set();
1719}
1720
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721} // namespace webrtc