blob: 62276f08c3d769e5992917ba54ff9e06788fe2f6 [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"
44#include "talk/media/base/constants.h"
45#include "talk/media/base/videocapturer.h"
46#include "talk/session/media/channel.h"
47#include "talk/session/media/channelmanager.h"
48#include "talk/session/media/mediasession.h"
49
50using cricket::ContentInfo;
51using cricket::ContentInfos;
52using cricket::MediaContentDescription;
53using cricket::SessionDescription;
54using cricket::TransportInfo;
55
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056namespace webrtc {
57
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058// Error messages
henrike@webrtc.org1e09a712013-07-26 19:17:59 +000059const char kBundleWithoutRtcpMux[] = "RTCP-MUX must be enabled when BUNDLE "
60 "is enabled.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000061const char kCreateChannelFailed[] = "Failed to create channels.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000062const char kInvalidCandidates[] = "Description contains invalid candidates.";
63const char kInvalidSdp[] = "Invalid session description.";
64const char kMlineMismatch[] =
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000065 "Offer and answer descriptions m-lines are not matching. Rejecting answer.";
66const char kPushDownTDFailed[] =
67 "Failed to push down transport description:";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000068const char kSdpWithoutDtlsFingerprint[] =
69 "Called with SDP without DTLS fingerprint.";
70const char kSdpWithoutSdesCrypto[] =
71 "Called with SDP without SDES crypto.";
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +000072const char kSdpWithoutIceUfragPwd[] =
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +000073 "Called with SDP without ice-ufrag and ice-pwd.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074const char kSessionError[] = "Session error code: ";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +000075const char kSessionErrorDesc[] = "Session error description: ";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000076
77// Compares |answer| against |offer|. Comparision is done
78// for number of m-lines in answer against offer. If matches true will be
79// returned otherwise false.
80static bool VerifyMediaDescriptions(
81 const SessionDescription* answer, const SessionDescription* offer) {
82 if (offer->contents().size() != answer->contents().size())
83 return false;
84
85 for (size_t i = 0; i < offer->contents().size(); ++i) {
86 if ((offer->contents()[i].name) != answer->contents()[i].name) {
87 return false;
88 }
wu@webrtc.org4e393072014-04-07 17:04:35 +000089 const MediaContentDescription* offer_mdesc =
90 static_cast<const MediaContentDescription*>(
91 offer->contents()[i].description);
92 const MediaContentDescription* answer_mdesc =
93 static_cast<const MediaContentDescription*>(
94 answer->contents()[i].description);
95 if (offer_mdesc->type() != answer_mdesc->type()) {
96 return false;
97 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098 }
99 return true;
100}
101
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102// Checks that each non-rejected content has SDES crypto keys or a DTLS
103// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
104// keys, will be caught in Transport negotiation, and backstopped by Channel's
105// |secure_required| check.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000106static bool VerifyCrypto(const SessionDescription* desc,
107 bool dtls_enabled,
108 std::string* error) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 const ContentInfos& contents = desc->contents();
110 for (size_t index = 0; index < contents.size(); ++index) {
111 const ContentInfo* cinfo = &contents[index];
112 if (cinfo->rejected) {
113 continue;
114 }
115
116 // If the content isn't rejected, crypto must be present.
117 const MediaContentDescription* media =
118 static_cast<const MediaContentDescription*>(cinfo->description);
119 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
120 if (!media || !tinfo) {
121 // Something is not right.
122 LOG(LS_ERROR) << kInvalidSdp;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000123 *error = kInvalidSdp;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000124 return false;
125 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000126 if (dtls_enabled) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000127 if (!tinfo->description.identity_fingerprint) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000128 LOG(LS_WARNING) <<
129 "Session description must have DTLS fingerprint if DTLS enabled.";
130 *error = kSdpWithoutDtlsFingerprint;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000131 return false;
132 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000133 } else {
134 if (media->cryptos().empty()) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000135 LOG(LS_WARNING) <<
136 "Session description must have SDES when DTLS disabled.";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000137 *error = kSdpWithoutSdesCrypto;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000138 return false;
139 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000140 }
141 }
142
143 return true;
144}
145
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +0000146// Checks that each non-rejected content has ice-ufrag and ice-pwd set.
147static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
148 const ContentInfos& contents = desc->contents();
149 for (size_t index = 0; index < contents.size(); ++index) {
150 const ContentInfo* cinfo = &contents[index];
151 if (cinfo->rejected) {
152 continue;
153 }
154
155 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
156 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
157 if (!tinfo) {
158 // Something is not right.
159 LOG(LS_ERROR) << kInvalidSdp;
160 return false;
161 }
162 if (tinfo->description.ice_ufrag.empty() ||
163 tinfo->description.ice_pwd.empty()) {
164 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
165 return false;
166 }
167 }
168 return true;
169}
170
wu@webrtc.org91053e72013-08-10 07:18:04 +0000171// Forces |sdesc->crypto_required| to the appropriate state based on the
172// current security policy, to ensure a failure occurs if there is an error
173// in crypto negotiation.
174// Called when processing the local session description.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000175static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
176 SessionDescription* sdesc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000177 if (!sdesc) {
178 return;
179 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180
wu@webrtc.org91053e72013-08-10 07:18:04 +0000181 // Updating the |crypto_required_| in MediaContentDescription to the
182 // appropriate state based on the current security policy.
183 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
184 iter != sdesc->contents().end(); ++iter) {
185 if (cricket::IsMediaContent(&*iter)) {
186 MediaContentDescription* mdesc =
187 static_cast<MediaContentDescription*> (iter->description);
188 if (mdesc) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000189 mdesc->set_crypto_required(type);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000190 }
191 }
192 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193}
194
195static bool GetAudioSsrcByTrackId(
196 const SessionDescription* session_description,
197 const std::string& track_id, uint32 *ssrc) {
198 const cricket::ContentInfo* audio_info =
199 cricket::GetFirstAudioContent(session_description);
200 if (!audio_info) {
201 LOG(LS_ERROR) << "Audio not used in this call";
202 return false;
203 }
204
205 const cricket::MediaContentDescription* audio_content =
206 static_cast<const cricket::MediaContentDescription*>(
207 audio_info->description);
208 cricket::StreamParams stream;
209 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
210 &stream)) {
211 return false;
212 }
213 *ssrc = stream.first_ssrc();
214 return true;
215}
216
217static bool GetTrackIdBySsrc(const SessionDescription* session_description,
218 uint32 ssrc, std::string* track_id) {
219 ASSERT(track_id != NULL);
220
221 cricket::StreamParams stream_out;
222 const cricket::ContentInfo* audio_info =
223 cricket::GetFirstAudioContent(session_description);
224 if (!audio_info) {
225 return false;
226 }
227 const cricket::MediaContentDescription* audio_content =
228 static_cast<const cricket::MediaContentDescription*>(
229 audio_info->description);
230
231 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
232 *track_id = stream_out.id;
233 return true;
234 }
235
236 const cricket::ContentInfo* video_info =
237 cricket::GetFirstVideoContent(session_description);
238 if (!video_info) {
239 return false;
240 }
241 const cricket::MediaContentDescription* video_content =
242 static_cast<const cricket::MediaContentDescription*>(
243 video_info->description);
244
245 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
246 *track_id = stream_out.id;
247 return true;
248 }
249 return false;
250}
251
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000252static bool BadSdp(const std::string& source,
253 const std::string& type,
254 const std::string& reason,
255 std::string* err_desc) {
256 std::ostringstream desc;
257 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
258
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259 if (err_desc) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000260 *err_desc = desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000262 LOG(LS_ERROR) << desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000263 return false;
264}
265
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266static bool BadSdp(cricket::ContentSource source,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000267 const std::string& type,
268 const std::string& reason,
269 std::string* err_desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270 if (source == cricket::CS_LOCAL) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000271 return BadSdp("local", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 } else {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000273 return BadSdp("remote", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000274 }
275}
276
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000277static bool BadLocalSdp(const std::string& type,
278 const std::string& reason,
279 std::string* err_desc) {
280 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
281}
282
283static bool BadRemoteSdp(const std::string& type,
284 const std::string& reason,
285 std::string* err_desc) {
286 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
287}
288
289static bool BadOfferSdp(cricket::ContentSource source,
290 const std::string& reason,
291 std::string* err_desc) {
292 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
293}
294
295static bool BadPranswerSdp(cricket::ContentSource source,
296 const std::string& reason,
297 std::string* err_desc) {
298 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
299 reason, err_desc);
300}
301
302static bool BadAnswerSdp(cricket::ContentSource source,
303 const std::string& reason,
304 std::string* err_desc) {
305 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000306}
307
308#define GET_STRING_OF_STATE(state) \
309 case cricket::BaseSession::state: \
310 result = #state; \
311 break;
312
313static std::string GetStateString(cricket::BaseSession::State state) {
314 std::string result;
315 switch (state) {
316 GET_STRING_OF_STATE(STATE_INIT)
317 GET_STRING_OF_STATE(STATE_SENTINITIATE)
318 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
319 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
320 GET_STRING_OF_STATE(STATE_SENTACCEPT)
321 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
322 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
323 GET_STRING_OF_STATE(STATE_SENTMODIFY)
324 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
325 GET_STRING_OF_STATE(STATE_SENTREJECT)
326 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
327 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
328 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
329 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
330 GET_STRING_OF_STATE(STATE_INPROGRESS)
331 GET_STRING_OF_STATE(STATE_DEINIT)
332 default:
333 ASSERT(false);
334 break;
335 }
336 return result;
337}
338
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000339#define GET_STRING_OF_ERROR_CODE(err) \
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000340 case cricket::BaseSession::err: \
341 result = #err; \
342 break;
343
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000344static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000345 std::string result;
346 switch (err) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000347 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
348 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
349 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
350 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
351 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
352 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000353 default:
354 ASSERT(false);
355 break;
356 }
357 return result;
358}
359
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000360static std::string MakeErrorString(const std::string& error,
361 const std::string& desc) {
362 std::ostringstream ret;
363 ret << error << " " << desc;
364 return ret.str();
365}
366
367static std::string MakeTdErrorString(const std::string& desc) {
368 return MakeErrorString(kPushDownTDFailed, desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000369}
370
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000371// Set |option| to the highest-priority value of |key| in the optional
372// constraints if the key is found and has a valid value.
373static void SetOptionFromOptionalConstraint(
374 const MediaConstraintsInterface* constraints,
375 const std::string& key, cricket::Settable<int>* option) {
376 if (!constraints) {
377 return;
378 }
379 std::string string_value;
380 int value;
381 if (constraints->GetOptional().FindFirst(key, &string_value)) {
382 if (talk_base::FromString(string_value, &value)) {
383 option->Set(value);
384 }
385 }
386}
387
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388// Help class used to remember if a a remote peer has requested ice restart by
389// by sending a description with new ice ufrag and password.
390class IceRestartAnswerLatch {
391 public:
392 IceRestartAnswerLatch() : ice_restart_(false) { }
393
wu@webrtc.org91053e72013-08-10 07:18:04 +0000394 // Returns true if CheckForRemoteIceRestart has been called with a new session
395 // description where ice password and ufrag has changed since last time
396 // Reset() was called.
397 bool Get() const {
398 return ice_restart_;
399 }
400
401 void Reset() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000402 if (ice_restart_) {
403 ice_restart_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000404 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000405 }
406
407 void CheckForRemoteIceRestart(
408 const SessionDescriptionInterface* old_desc,
409 const SessionDescriptionInterface* new_desc) {
410 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
411 return;
412 }
413 const SessionDescription* new_sd = new_desc->description();
414 const SessionDescription* old_sd = old_desc->description();
415 const ContentInfos& contents = new_sd->contents();
416 for (size_t index = 0; index < contents.size(); ++index) {
417 const ContentInfo* cinfo = &contents[index];
418 if (cinfo->rejected) {
419 continue;
420 }
421 // If the content isn't rejected, check if ufrag and password has
422 // changed.
423 const cricket::TransportDescription* new_transport_desc =
424 new_sd->GetTransportDescriptionByName(cinfo->name);
425 const cricket::TransportDescription* old_transport_desc =
426 old_sd->GetTransportDescriptionByName(cinfo->name);
427 if (!new_transport_desc || !old_transport_desc) {
428 // No transport description exist. This is not an ice restart.
429 continue;
430 }
431 if (new_transport_desc->ice_pwd != old_transport_desc->ice_pwd &&
432 new_transport_desc->ice_ufrag != old_transport_desc->ice_ufrag) {
433 LOG(LS_INFO) << "Remote peer request ice restart.";
434 ice_restart_ = true;
435 break;
436 }
437 }
438 }
439
440 private:
441 bool ice_restart_;
442};
443
wu@webrtc.org91053e72013-08-10 07:18:04 +0000444WebRtcSession::WebRtcSession(
445 cricket::ChannelManager* channel_manager,
446 talk_base::Thread* signaling_thread,
447 talk_base::Thread* worker_thread,
448 cricket::PortAllocator* port_allocator,
449 MediaStreamSignaling* mediastream_signaling)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000450 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
451 talk_base::ToString(talk_base::CreateRandomId64() &
452 LLONG_MAX),
453 cricket::NS_JINGLE_RTP, false),
454 // RFC 3264: The numeric value of the session id and version in the
455 // o line MUST be representable with a "64 bit signed integer".
456 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
457 channel_manager_(channel_manager),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000458 mediastream_signaling_(mediastream_signaling),
459 ice_observer_(NULL),
460 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000461 older_version_remote_peer_(false),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000462 dtls_enabled_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000463 data_channel_type_(cricket::DCT_NONE),
464 ice_restart_latch_(new IceRestartAnswerLatch) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465}
466
467WebRtcSession::~WebRtcSession() {
468 if (voice_channel_.get()) {
469 SignalVoiceChannelDestroyed();
470 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
471 }
472 if (video_channel_.get()) {
473 SignalVideoChannelDestroyed();
474 channel_manager_->DestroyVideoChannel(video_channel_.release());
475 }
476 if (data_channel_.get()) {
477 SignalDataChannelDestroyed();
478 channel_manager_->DestroyDataChannel(data_channel_.release());
479 }
480 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
481 delete saved_candidates_[i];
482 }
483 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000484}
485
wu@webrtc.org91053e72013-08-10 07:18:04 +0000486bool WebRtcSession::Initialize(
wu@webrtc.org97077a32013-10-25 21:18:33 +0000487 const PeerConnectionFactoryInterface::Options& options,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000488 const MediaConstraintsInterface* constraints,
489 DTLSIdentityServiceInterface* dtls_identity_service) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000490 // TODO(perkj): Take |constraints| into consideration. Return false if not all
491 // mandatory constraints can be fulfilled. Note that |constraints|
492 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000493 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000494
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000495 if (options.disable_encryption) {
496 dtls_enabled_ = false;
497 } else {
498 // Enable DTLS by default if |dtls_identity_service| is valid.
499 dtls_enabled_ = (dtls_identity_service != NULL);
500 // |constraints| can override the default |dtls_enabled_| value.
501 if (FindConstraint(
502 constraints,
503 MediaConstraintsInterface::kEnableDtlsSrtp,
504 &value, NULL)) {
505 dtls_enabled_ = value;
506 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000507 }
508
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000509 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000510 // It takes precendence over the disable_sctp_data_channels
511 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000512 if (FindConstraint(
513 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
514 &value, NULL) && value) {
515 LOG(LS_INFO) << "Allowing RTP data engine.";
516 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000517 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000518 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000519 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000520 LOG(LS_INFO) << "Allowing SCTP data engine.";
521 data_channel_type_ = cricket::DCT_SCTP;
522 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000523 }
524 if (data_channel_type_ != cricket::DCT_NONE) {
525 mediastream_signaling_->SetDataChannelFactory(this);
526 }
527
wu@webrtc.orgde305012013-10-31 15:40:38 +0000528 // Find DSCP constraint.
529 if (FindConstraint(
530 constraints,
531 MediaConstraintsInterface::kEnableDscp,
532 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000533 audio_options_.dscp.Set(value);
534 video_options_.dscp.Set(value);
535 }
536
537 // Find Suspend Below Min Bitrate constraint.
538 if (FindConstraint(
539 constraints,
540 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
541 &value,
542 NULL)) {
543 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000544 }
545
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000546 if (FindConstraint(
547 constraints,
548 MediaConstraintsInterface::kSkipEncodingUnusedStreams,
549 &value,
550 NULL)) {
551 video_options_.skip_encoding_unused_streams.Set(value);
552 }
553
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000554 SetOptionFromOptionalConstraint(constraints,
555 MediaConstraintsInterface::kScreencastMinBitrate,
556 &video_options_.screencast_min_bitrate);
557
558 // Find constraints for cpu overuse detection.
559 SetOptionFromOptionalConstraint(constraints,
560 MediaConstraintsInterface::kCpuUnderuseThreshold,
561 &video_options_.cpu_underuse_threshold);
562 SetOptionFromOptionalConstraint(constraints,
563 MediaConstraintsInterface::kCpuOveruseThreshold,
564 &video_options_.cpu_overuse_threshold);
565
566 if (FindConstraint(
567 constraints,
568 MediaConstraintsInterface::kCpuOveruseDetection,
569 &value,
570 NULL)) {
571 video_options_.cpu_overuse_detection.Set(value);
572 }
573 if (FindConstraint(
574 constraints,
575 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
576 &value,
577 NULL)) {
578 video_options_.cpu_overuse_encode_usage.Set(value);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000579 }
580
581 // Find improved wifi bwe constraint.
582 if (FindConstraint(
583 constraints,
584 MediaConstraintsInterface::kImprovedWifiBwe,
585 &value,
586 NULL)) {
587 video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
588 }
589
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000590 if (FindConstraint(
591 constraints,
592 MediaConstraintsInterface::kHighStartBitrate,
593 &value,
594 NULL)) {
595 video_options_.video_start_bitrate.Set(cricket::kHighStartBitrate);
596 }
597
598 if (FindConstraint(
599 constraints,
600 MediaConstraintsInterface::kVeryHighBitrate,
601 &value,
602 NULL)) {
603 video_options_.video_highest_bitrate.Set(
604 cricket::VideoOptions::VERY_HIGH);
605 } else if (FindConstraint(
606 constraints,
607 MediaConstraintsInterface::kHighBitrate,
608 &value,
609 NULL)) {
610 video_options_.video_highest_bitrate.Set(
611 cricket::VideoOptions::HIGH);
612 }
613
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000614 const cricket::VideoCodec default_codec(
615 JsepSessionDescription::kDefaultVideoCodecId,
616 JsepSessionDescription::kDefaultVideoCodecName,
617 JsepSessionDescription::kMaxVideoCodecWidth,
618 JsepSessionDescription::kMaxVideoCodecHeight,
619 JsepSessionDescription::kDefaultVideoCodecFramerate,
620 JsepSessionDescription::kDefaultVideoCodecPreference);
621 channel_manager_->SetDefaultVideoEncoderConfig(
622 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000623
624 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
625 signaling_thread(),
626 channel_manager_,
627 mediastream_signaling_,
628 dtls_identity_service,
629 this,
630 id(),
631 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000632 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000633
634 webrtc_session_desc_factory_->SignalIdentityReady.connect(
635 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000636
wu@webrtc.org97077a32013-10-25 21:18:33 +0000637 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000638 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000639 }
640
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000641 return true;
642}
643
644void WebRtcSession::Terminate() {
645 SetState(STATE_RECEIVEDTERMINATE);
646 RemoveUnusedChannelsAndTransports(NULL);
647 ASSERT(voice_channel_.get() == NULL);
648 ASSERT(video_channel_.get() == NULL);
649 ASSERT(data_channel_.get() == NULL);
650}
651
652bool WebRtcSession::StartCandidatesAllocation() {
653 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
654 // from TransportProxy to start gathering ice candidates.
655 SpeculativelyConnectAllTransportChannels();
656 if (!saved_candidates_.empty()) {
657 // If there are saved candidates which arrived before local description is
658 // set, copy those to remote description.
659 CopySavedCandidates(remote_desc_.get());
660 }
661 // Push remote candidates present in remote description to transport channels.
662 UseCandidatesInSessionDescription(remote_desc_.get());
663 return true;
664}
665
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000666void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
667 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000668}
669
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000670cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
671 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000672}
673
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000674bool WebRtcSession::GetSslRole(talk_base::SSLRole* role) {
675 if (local_description() == NULL || remote_description() == NULL) {
676 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
677 << "SSL Role of the session.";
678 return false;
679 }
680
681 // TODO(mallinath) - Return role of each transport, as role may differ from
682 // one another.
683 // In current implementaion we just return the role of first transport in the
684 // transport map.
685 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
686 iter != transport_proxies().end(); ++iter) {
687 if (iter->second->impl()) {
688 return iter->second->impl()->GetSslRole(role);
689 }
690 }
691 return false;
692}
693
wu@webrtc.org91053e72013-08-10 07:18:04 +0000694void WebRtcSession::CreateOffer(CreateSessionDescriptionObserver* observer,
695 const MediaConstraintsInterface* constraints) {
696 webrtc_session_desc_factory_->CreateOffer(observer, constraints);
697}
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.
707 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
708
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
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000752 talk_base::SSLRole role;
753 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.
765 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
766
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
808 talk_base::SSLRole role;
809 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
885 if (!local_description() || !remote_description()) {
886 LOG(LS_INFO) << "ProcessIceMessage: Remote description not set, "
887 << "save the candidate for later use.";
888 saved_candidates_.push_back(
889 new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
890 candidate->candidate()));
891 return true;
892 }
893
894 // Add this candidate to the remote session description.
895 if (!remote_desc_->AddCandidate(candidate)) {
896 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
897 return false;
898 }
899
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000900 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901}
902
903bool WebRtcSession::GetTrackIdBySsrc(uint32 ssrc, std::string* id) {
904 if (GetLocalTrackId(ssrc, id)) {
905 if (GetRemoteTrackId(ssrc, id)) {
906 LOG(LS_WARNING) << "SSRC " << ssrc
907 << " exists in both local and remote descriptions";
908 return true; // We return the remote track id.
909 }
910 return true;
911 } else {
912 return GetRemoteTrackId(ssrc, id);
913 }
914}
915
916bool WebRtcSession::GetLocalTrackId(uint32 ssrc, std::string* track_id) {
917 if (!BaseSession::local_description())
918 return false;
919 return webrtc::GetTrackIdBySsrc(
920 BaseSession::local_description(), ssrc, track_id);
921}
922
923bool WebRtcSession::GetRemoteTrackId(uint32 ssrc, std::string* track_id) {
924 if (!BaseSession::remote_description())
925 return false;
926 return webrtc::GetTrackIdBySsrc(
927 BaseSession::remote_description(), ssrc, track_id);
928}
929
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000930std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000932 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933 return desc.str();
934}
935
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000936void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
937 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 ASSERT(signaling_thread()->IsCurrent());
939 if (!voice_channel_) {
940 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
941 return;
942 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000943 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
944 // SetRenderer() can fail if the ssrc does not match any playout channel.
945 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
946 return;
947 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
949 // Allow that SetOutputScaling fail if |enable| is false but assert
950 // otherwise. This in the normal case when the underlying media channel has
951 // already been deleted.
952 ASSERT(enable == false);
953 }
954}
955
956void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000957 const cricket::AudioOptions& options,
958 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959 ASSERT(signaling_thread()->IsCurrent());
960 if (!voice_channel_) {
961 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
962 return;
963 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000964 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
965 // SetRenderer() can fail if the ssrc does not match any send channel.
966 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
967 return;
968 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 if (!voice_channel_->MuteStream(ssrc, !enable)) {
970 // Allow that MuteStream fail if |enable| is false but assert otherwise.
971 // This in the normal case when the underlying media channel has already
972 // been deleted.
973 ASSERT(enable == false);
974 return;
975 }
976 if (enable)
977 voice_channel_->SetChannelOptions(options);
978}
979
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000980void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
981 ASSERT(signaling_thread()->IsCurrent());
982 ASSERT(volume >= 0 && volume <= 10);
983 if (!voice_channel_) {
984 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
985 return;
986 }
987
988 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
989 ASSERT(false);
990}
991
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
993 cricket::VideoCapturer* camera) {
994 ASSERT(signaling_thread()->IsCurrent());
995
996 if (!video_channel_.get()) {
997 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
998 // support video.
999 LOG(LS_WARNING) << "Video not used in this call.";
1000 return false;
1001 }
1002 if (!video_channel_->SetCapturer(ssrc, camera)) {
1003 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
1004 // This in the normal case when the underlying media channel has already
1005 // been deleted.
1006 ASSERT(camera == NULL);
1007 return false;
1008 }
1009 return true;
1010}
1011
1012void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1013 bool enable,
1014 cricket::VideoRenderer* renderer) {
1015 ASSERT(signaling_thread()->IsCurrent());
1016 if (!video_channel_) {
1017 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1018 return;
1019 }
1020 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1021 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1022 // This in the normal case when the underlying media channel has already
1023 // been deleted.
1024 ASSERT(renderer == NULL);
1025 }
1026}
1027
1028void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1029 const cricket::VideoOptions* options) {
1030 ASSERT(signaling_thread()->IsCurrent());
1031 if (!video_channel_) {
1032 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1033 return;
1034 }
1035 if (!video_channel_->MuteStream(ssrc, !enable)) {
1036 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1037 // This in the normal case when the underlying media channel has already
1038 // been deleted.
1039 ASSERT(enable == false);
1040 return;
1041 }
1042 if (enable && options)
1043 video_channel_->SetChannelOptions(*options);
1044}
1045
1046bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1047 ASSERT(signaling_thread()->IsCurrent());
1048 if (!voice_channel_) {
1049 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1050 return false;
1051 }
1052 uint32 send_ssrc = 0;
1053 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1054 // exists.
1055 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1056 &send_ssrc)) {
1057 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1058 return false;
1059 }
1060 return voice_channel_->CanInsertDtmf();
1061}
1062
1063bool WebRtcSession::InsertDtmf(const std::string& track_id,
1064 int code, int duration) {
1065 ASSERT(signaling_thread()->IsCurrent());
1066 if (!voice_channel_) {
1067 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1068 return false;
1069 }
1070 uint32 send_ssrc = 0;
1071 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1072 track_id, &send_ssrc))) {
1073 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1074 return false;
1075 }
1076 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1077 cricket::DF_SEND)) {
1078 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1079 return false;
1080 }
1081 return true;
1082}
1083
1084sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1085 return &SignalVoiceChannelDestroyed;
1086}
1087
wu@webrtc.org78187522013-10-07 23:32:02 +00001088bool WebRtcSession::SendData(const cricket::SendDataParams& params,
1089 const talk_base::Buffer& payload,
1090 cricket::SendDataResult* result) {
1091 if (!data_channel_.get()) {
1092 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1093 return false;
1094 }
1095 return data_channel_->SendData(params, payload, result);
1096}
1097
1098bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1099 if (!data_channel_.get()) {
1100 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1101 return false;
1102 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001103 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1104 &DataChannel::OnChannelReady);
1105 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1106 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001107 return true;
1108}
1109
1110void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001111 if (!data_channel_.get()) {
1112 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1113 return;
1114 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001115 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1116 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1117}
1118
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001119void WebRtcSession::AddSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001120 if (!data_channel_.get()) {
1121 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1122 return;
1123 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001124 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1125 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001126}
1127
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001128void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001129 if (!data_channel_.get()) {
1130 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1131 << "NULL.";
1132 return;
1133 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001134 data_channel_->RemoveRecvStream(sid);
1135 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001136}
1137
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001138bool WebRtcSession::ReadyToSendData() const {
1139 return data_channel_.get() && data_channel_->ready_to_send_data();
1140}
1141
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001142talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001143 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001144 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001145 if (state() == STATE_RECEIVEDTERMINATE) {
1146 return NULL;
1147 }
1148 if (data_channel_type_ == cricket::DCT_NONE) {
1149 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1150 return NULL;
1151 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001152 InternalDataChannelInit new_config =
1153 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154 if (data_channel_type_ == cricket::DCT_SCTP) {
1155 if (new_config.id < 0) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001156 talk_base::SSLRole role;
1157 if (GetSslRole(&role) &&
1158 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001159 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1160 return NULL;
1161 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001162 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1164 << "because the id is already in use or out of range.";
1165 return NULL;
1166 }
1167 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001168
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001169 talk_base::scoped_refptr<DataChannel> channel(DataChannel::Create(
1170 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001171 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001173
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174 return channel;
1175}
1176
1177cricket::DataChannelType WebRtcSession::data_channel_type() const {
1178 return data_channel_type_;
1179}
1180
wu@webrtc.org91053e72013-08-10 07:18:04 +00001181bool WebRtcSession::IceRestartPending() const {
1182 return ice_restart_latch_->Get();
1183}
1184
1185void WebRtcSession::ResetIceRestartLatch() {
1186 ice_restart_latch_->Reset();
1187}
1188
1189void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
1190 SetIdentity(identity);
1191}
1192
1193bool WebRtcSession::waiting_for_identity() const {
1194 return webrtc_session_desc_factory_->waiting_for_identity();
1195}
1196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197void WebRtcSession::SetIceConnectionState(
1198 PeerConnectionInterface::IceConnectionState state) {
1199 if (ice_connection_state_ == state) {
1200 return;
1201 }
1202
1203 // ASSERT that the requested transition is allowed. Note that
1204 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1205 // within PeerConnection). This switch statement should compile away when
1206 // ASSERTs are disabled.
1207 switch (ice_connection_state_) {
1208 case PeerConnectionInterface::kIceConnectionNew:
1209 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1210 break;
1211 case PeerConnectionInterface::kIceConnectionChecking:
1212 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1213 state == PeerConnectionInterface::kIceConnectionConnected);
1214 break;
1215 case PeerConnectionInterface::kIceConnectionConnected:
1216 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1217 state == PeerConnectionInterface::kIceConnectionChecking ||
1218 state == PeerConnectionInterface::kIceConnectionCompleted);
1219 break;
1220 case PeerConnectionInterface::kIceConnectionCompleted:
1221 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1222 state == PeerConnectionInterface::kIceConnectionDisconnected);
1223 break;
1224 case PeerConnectionInterface::kIceConnectionFailed:
1225 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1226 break;
1227 case PeerConnectionInterface::kIceConnectionDisconnected:
1228 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1229 state == PeerConnectionInterface::kIceConnectionConnected ||
1230 state == PeerConnectionInterface::kIceConnectionCompleted ||
1231 state == PeerConnectionInterface::kIceConnectionFailed);
1232 break;
1233 case PeerConnectionInterface::kIceConnectionClosed:
1234 ASSERT(false);
1235 break;
1236 default:
1237 ASSERT(false);
1238 break;
1239 }
1240
1241 ice_connection_state_ = state;
1242 if (ice_observer_) {
1243 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1244 }
1245}
1246
1247void WebRtcSession::OnTransportRequestSignaling(
1248 cricket::Transport* transport) {
1249 ASSERT(signaling_thread()->IsCurrent());
1250 transport->OnSignalingReady();
1251 if (ice_observer_) {
1252 ice_observer_->OnIceGatheringChange(
1253 PeerConnectionInterface::kIceGatheringGathering);
1254 }
1255}
1256
1257void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1258 ASSERT(signaling_thread()->IsCurrent());
1259 // start monitoring for the write state of the transport.
1260 OnTransportWritable(transport);
1261}
1262
1263void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1264 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001266 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267 } else if (transport->HasChannels()) {
1268 // If the current state is Connected or Completed, then there were writable
1269 // channels but now there are not, so the next state must be Disconnected.
1270 if (ice_connection_state_ ==
1271 PeerConnectionInterface::kIceConnectionConnected ||
1272 ice_connection_state_ ==
1273 PeerConnectionInterface::kIceConnectionCompleted) {
1274 SetIceConnectionState(
1275 PeerConnectionInterface::kIceConnectionDisconnected);
1276 }
1277 }
1278}
1279
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001280void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1281 ASSERT(signaling_thread()->IsCurrent());
1282 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1283}
1284
1285void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1286 ASSERT(signaling_thread()->IsCurrent());
1287 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1288}
1289
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001290void WebRtcSession::OnTransportProxyCandidatesReady(
1291 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1292 ASSERT(signaling_thread()->IsCurrent());
1293 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1294}
1295
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296void WebRtcSession::OnCandidatesAllocationDone() {
1297 ASSERT(signaling_thread()->IsCurrent());
1298 if (ice_observer_) {
1299 ice_observer_->OnIceGatheringChange(
1300 PeerConnectionInterface::kIceGatheringComplete);
1301 ice_observer_->OnIceComplete();
1302 }
1303}
1304
1305// Enabling voice and video channel.
1306void WebRtcSession::EnableChannels() {
1307 if (voice_channel_ && !voice_channel_->enabled())
1308 voice_channel_->Enable(true);
1309
1310 if (video_channel_ && !video_channel_->enabled())
1311 video_channel_->Enable(true);
1312
1313 if (data_channel_.get() && !data_channel_->enabled())
1314 data_channel_->Enable(true);
1315}
1316
1317void WebRtcSession::ProcessNewLocalCandidate(
1318 const std::string& content_name,
1319 const cricket::Candidates& candidates) {
1320 int sdp_mline_index;
1321 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1322 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1323 << content_name << " not found";
1324 return;
1325 }
1326
1327 for (cricket::Candidates::const_iterator citer = candidates.begin();
1328 citer != candidates.end(); ++citer) {
1329 // Use content_name as the candidate media id.
1330 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1331 if (ice_observer_) {
1332 ice_observer_->OnIceCandidate(&candidate);
1333 }
1334 if (local_desc_) {
1335 local_desc_->AddCandidate(&candidate);
1336 }
1337 }
1338}
1339
1340// Returns the media index for a local ice candidate given the content name.
1341bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1342 int* sdp_mline_index) {
1343 if (!BaseSession::local_description() || !sdp_mline_index)
1344 return false;
1345
1346 bool content_found = false;
1347 const ContentInfos& contents = BaseSession::local_description()->contents();
1348 for (size_t index = 0; index < contents.size(); ++index) {
1349 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001350 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 content_found = true;
1352 break;
1353 }
1354 }
1355 return content_found;
1356}
1357
1358bool WebRtcSession::UseCandidatesInSessionDescription(
1359 const SessionDescriptionInterface* remote_desc) {
1360 if (!remote_desc)
1361 return true;
1362 bool ret = true;
1363 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1364 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1365 for (size_t n = 0; n < candidates->count(); ++n) {
1366 ret = UseCandidate(candidates->at(n));
1367 if (!ret)
1368 break;
1369 }
1370 }
1371 return ret;
1372}
1373
1374bool WebRtcSession::UseCandidate(
1375 const IceCandidateInterface* candidate) {
1376
1377 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1378 size_t remote_content_size =
1379 BaseSession::remote_description()->contents().size();
1380 if (mediacontent_index >= remote_content_size) {
1381 LOG(LS_ERROR)
1382 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1383 return false;
1384 }
1385
1386 cricket::ContentInfo content =
1387 BaseSession::remote_description()->contents()[mediacontent_index];
1388 std::vector<cricket::Candidate> candidates;
1389 candidates.push_back(candidate->candidate());
1390 // Invoking BaseSession method to handle remote candidates.
1391 std::string error;
1392 if (OnRemoteCandidates(content.name, candidates, &error)) {
1393 // Candidates successfully submitted for checking.
1394 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1395 ice_connection_state_ ==
1396 PeerConnectionInterface::kIceConnectionDisconnected) {
1397 // If state is New, then the session has just gotten its first remote ICE
1398 // candidates, so go to Checking.
1399 // If state is Disconnected, the session is re-using old candidates or
1400 // receiving additional ones, so go to Checking.
1401 // If state is Connected, stay Connected.
1402 // TODO(bemasc): If state is Connected, and the new candidates are for a
1403 // newly added transport, then the state actually _should_ move to
1404 // checking. Add a way to distinguish that case.
1405 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1406 }
1407 // TODO(bemasc): If state is Completed, go back to Connected.
1408 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001409 if (!error.empty()) {
1410 LOG(LS_WARNING) << error;
1411 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412 }
1413 return true;
1414}
1415
1416void WebRtcSession::RemoveUnusedChannelsAndTransports(
1417 const SessionDescription* desc) {
1418 const cricket::ContentInfo* voice_info =
1419 cricket::GetFirstAudioContent(desc);
1420 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1421 mediastream_signaling_->OnAudioChannelClose();
1422 SignalVoiceChannelDestroyed();
1423 const std::string content_name = voice_channel_->content_name();
1424 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1425 DestroyTransportProxy(content_name);
1426 }
1427
1428 const cricket::ContentInfo* video_info =
1429 cricket::GetFirstVideoContent(desc);
1430 if ((!video_info || video_info->rejected) && video_channel_) {
1431 mediastream_signaling_->OnVideoChannelClose();
1432 SignalVideoChannelDestroyed();
1433 const std::string content_name = video_channel_->content_name();
1434 channel_manager_->DestroyVideoChannel(video_channel_.release());
1435 DestroyTransportProxy(content_name);
1436 }
1437
1438 const cricket::ContentInfo* data_info =
1439 cricket::GetFirstDataContent(desc);
1440 if ((!data_info || data_info->rejected) && data_channel_) {
1441 mediastream_signaling_->OnDataChannelClose();
1442 SignalDataChannelDestroyed();
1443 const std::string content_name = data_channel_->content_name();
1444 channel_manager_->DestroyDataChannel(data_channel_.release());
1445 DestroyTransportProxy(content_name);
1446 }
1447}
1448
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001449// TODO(mallinath) - Add a correct error code if the channels are not creatued
1450// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1452 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001453 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1454 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455 port_allocator()->set_flags(port_allocator()->flags() &
1456 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1457 }
1458
1459 // Creating the media channels and transport proxies.
1460 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1461 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001462 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 LOG(LS_ERROR) << "Failed to create voice channel.";
1464 return false;
1465 }
1466 }
1467
1468 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1469 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001470 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 LOG(LS_ERROR) << "Failed to create video channel.";
1472 return false;
1473 }
1474 }
1475
1476 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1477 if (data_channel_type_ != cricket::DCT_NONE &&
1478 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001479 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 LOG(LS_ERROR) << "Failed to create data channel.";
1481 return false;
1482 }
1483 }
1484
1485 return true;
1486}
1487
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001488bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001490 this, content->name, true));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001491 if (!voice_channel_.get())
1492 return false;
1493
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001494 voice_channel_->SetChannelOptions(audio_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001495 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001496}
1497
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001498bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001500 this, content->name, true, voice_channel_.get()));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001501 if (!video_channel_.get())
1502 return false;
1503
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001504 video_channel_->SetChannelOptions(video_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::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001509 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001510 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001511 this, content->name, !sctp, data_channel_type_));
wu@webrtc.org91053e72013-08-10 07:18:04 +00001512 if (!data_channel_.get()) {
1513 return false;
1514 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001515 if (sctp) {
1516 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001517 data_channel_->SignalDataReceived.connect(
1518 this, &WebRtcSession::OnDataChannelMessageReceived);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001519 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001520 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001521}
1522
1523void WebRtcSession::CopySavedCandidates(
1524 SessionDescriptionInterface* dest_desc) {
1525 if (!dest_desc) {
1526 ASSERT(false);
1527 return;
1528 }
1529 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1530 dest_desc->AddCandidate(saved_candidates_[i]);
1531 delete saved_candidates_[i];
1532 }
1533 saved_candidates_.clear();
1534}
1535
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001536void WebRtcSession::OnDataChannelMessageReceived(
1537 cricket::DataChannel* channel,
1538 const cricket::ReceiveDataParams& params,
1539 const talk_base::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001540 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001541 if (params.type == cricket::DMT_CONTROL &&
1542 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1543 // Received CONTROL on unused sid, process as an OPEN message.
1544 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001546 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547}
1548
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001549// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001550bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001551 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1552 if (!bundle_enabled)
1553 return true;
1554
1555 const cricket::ContentGroup* bundle_group =
1556 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1557 ASSERT(bundle_group != NULL);
1558
1559 const cricket::ContentInfos& contents = desc->contents();
1560 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1561 citer != contents.end(); ++citer) {
1562 const cricket::ContentInfo* content = (&*citer);
1563 ASSERT(content != NULL);
1564 if (bundle_group->HasContentName(content->name) &&
1565 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1566 if (!HasRtcpMuxEnabled(content))
1567 return false;
1568 }
1569 }
1570 // RTCP-MUX is enabled in all the contents.
1571 return true;
1572}
1573
1574bool WebRtcSession::HasRtcpMuxEnabled(
1575 const cricket::ContentInfo* content) {
1576 const cricket::MediaContentDescription* description =
1577 static_cast<cricket::MediaContentDescription*>(content->description);
1578 return description->rtcp_mux();
1579}
1580
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001581bool WebRtcSession::ValidateSessionDescription(
1582 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001583 cricket::ContentSource source, std::string* err_desc) {
1584 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001585 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001586 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001587 }
1588
1589 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001590 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001591 }
1592
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001593 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001594 Action action = GetAction(sdesc->type());
1595 if (source == cricket::CS_LOCAL) {
1596 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001597 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001598 } else {
1599 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001600 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001601 }
1602
1603 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001604 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001605 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1606 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001607 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001608 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001609 }
1610
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001611 // Verify ice-ufrag and ice-pwd.
1612 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001613 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001614 }
1615
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001616 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001617 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001618 }
1619
1620 // Verify m-lines in Answer when compared against Offer.
1621 if (action == kAnswer) {
1622 const cricket::SessionDescription* offer_desc =
1623 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1624 local_description()->description();
1625 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001626 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001627 }
1628 }
1629
1630 return true;
1631}
1632
1633bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1634 return ((action == kOffer && state() == STATE_INIT) ||
1635 // update local offer
1636 (action == kOffer && state() == STATE_SENTINITIATE) ||
1637 // update the current ongoing session.
1638 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1639 (action == kOffer && state() == STATE_SENTACCEPT) ||
1640 (action == kOffer && state() == STATE_INPROGRESS) ||
1641 // accept remote offer
1642 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1643 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1644 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1645 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1646}
1647
1648bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1649 return ((action == kOffer && state() == STATE_INIT) ||
1650 // update remote offer
1651 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1652 // update the current ongoing session
1653 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1654 (action == kOffer && state() == STATE_SENTACCEPT) ||
1655 (action == kOffer && state() == STATE_INPROGRESS) ||
1656 // accept local offer
1657 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1658 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1659 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1660 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1661}
1662
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001663std::string WebRtcSession::GetSessionErrorMsg() {
1664 std::ostringstream desc;
1665 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1666 desc << kSessionErrorDesc << error_desc() << ".";
1667 return desc.str();
1668}
1669
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001670} // namespace webrtc