blob: 2d040291a645b6175508a9955aa29495fb3ba5ff [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 }
89 }
90 return true;
91}
92
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093// Checks that each non-rejected content has SDES crypto keys or a DTLS
94// fingerprint. Mismatches, such as replying with a DTLS fingerprint to SDES
95// keys, will be caught in Transport negotiation, and backstopped by Channel's
96// |secure_required| check.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000097static bool VerifyCrypto(const SessionDescription* desc,
98 bool dtls_enabled,
99 std::string* error) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100 const ContentInfos& contents = desc->contents();
101 for (size_t index = 0; index < contents.size(); ++index) {
102 const ContentInfo* cinfo = &contents[index];
103 if (cinfo->rejected) {
104 continue;
105 }
106
107 // If the content isn't rejected, crypto must be present.
108 const MediaContentDescription* media =
109 static_cast<const MediaContentDescription*>(cinfo->description);
110 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
111 if (!media || !tinfo) {
112 // Something is not right.
113 LOG(LS_ERROR) << kInvalidSdp;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000114 *error = kInvalidSdp;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115 return false;
116 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000117 if (dtls_enabled) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000118 if (!tinfo->description.identity_fingerprint) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000119 LOG(LS_WARNING) <<
120 "Session description must have DTLS fingerprint if DTLS enabled.";
121 *error = kSdpWithoutDtlsFingerprint;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000122 return false;
123 }
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000124 } else {
125 if (media->cryptos().empty()) {
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000126 LOG(LS_WARNING) <<
127 "Session description must have SDES when DTLS disabled.";
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000128 *error = kSdpWithoutSdesCrypto;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000129 return false;
130 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131 }
132 }
133
134 return true;
135}
136
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +0000137// Checks that each non-rejected content has ice-ufrag and ice-pwd set.
138static bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
139 const ContentInfos& contents = desc->contents();
140 for (size_t index = 0; index < contents.size(); ++index) {
141 const ContentInfo* cinfo = &contents[index];
142 if (cinfo->rejected) {
143 continue;
144 }
145
146 // If the content isn't rejected, ice-ufrag and ice-pwd must be present.
147 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
148 if (!tinfo) {
149 // Something is not right.
150 LOG(LS_ERROR) << kInvalidSdp;
151 return false;
152 }
153 if (tinfo->description.ice_ufrag.empty() ||
154 tinfo->description.ice_pwd.empty()) {
155 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
156 return false;
157 }
158 }
159 return true;
160}
161
wu@webrtc.org91053e72013-08-10 07:18:04 +0000162// Forces |sdesc->crypto_required| to the appropriate state based on the
163// current security policy, to ensure a failure occurs if there is an error
164// in crypto negotiation.
165// Called when processing the local session description.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000166static void UpdateSessionDescriptionSecurePolicy(cricket::CryptoType type,
167 SessionDescription* sdesc) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000168 if (!sdesc) {
169 return;
170 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171
wu@webrtc.org91053e72013-08-10 07:18:04 +0000172 // Updating the |crypto_required_| in MediaContentDescription to the
173 // appropriate state based on the current security policy.
174 for (cricket::ContentInfos::iterator iter = sdesc->contents().begin();
175 iter != sdesc->contents().end(); ++iter) {
176 if (cricket::IsMediaContent(&*iter)) {
177 MediaContentDescription* mdesc =
178 static_cast<MediaContentDescription*> (iter->description);
179 if (mdesc) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000180 mdesc->set_crypto_required(type);
wu@webrtc.org91053e72013-08-10 07:18:04 +0000181 }
182 }
183 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000184}
185
186static bool GetAudioSsrcByTrackId(
187 const SessionDescription* session_description,
188 const std::string& track_id, uint32 *ssrc) {
189 const cricket::ContentInfo* audio_info =
190 cricket::GetFirstAudioContent(session_description);
191 if (!audio_info) {
192 LOG(LS_ERROR) << "Audio not used in this call";
193 return false;
194 }
195
196 const cricket::MediaContentDescription* audio_content =
197 static_cast<const cricket::MediaContentDescription*>(
198 audio_info->description);
199 cricket::StreamParams stream;
200 if (!cricket::GetStreamByIds(audio_content->streams(), "", track_id,
201 &stream)) {
202 return false;
203 }
204 *ssrc = stream.first_ssrc();
205 return true;
206}
207
208static bool GetTrackIdBySsrc(const SessionDescription* session_description,
209 uint32 ssrc, std::string* track_id) {
210 ASSERT(track_id != NULL);
211
212 cricket::StreamParams stream_out;
213 const cricket::ContentInfo* audio_info =
214 cricket::GetFirstAudioContent(session_description);
215 if (!audio_info) {
216 return false;
217 }
218 const cricket::MediaContentDescription* audio_content =
219 static_cast<const cricket::MediaContentDescription*>(
220 audio_info->description);
221
222 if (cricket::GetStreamBySsrc(audio_content->streams(), ssrc, &stream_out)) {
223 *track_id = stream_out.id;
224 return true;
225 }
226
227 const cricket::ContentInfo* video_info =
228 cricket::GetFirstVideoContent(session_description);
229 if (!video_info) {
230 return false;
231 }
232 const cricket::MediaContentDescription* video_content =
233 static_cast<const cricket::MediaContentDescription*>(
234 video_info->description);
235
236 if (cricket::GetStreamBySsrc(video_content->streams(), ssrc, &stream_out)) {
237 *track_id = stream_out.id;
238 return true;
239 }
240 return false;
241}
242
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000243static bool BadSdp(const std::string& source,
244 const std::string& type,
245 const std::string& reason,
246 std::string* err_desc) {
247 std::ostringstream desc;
248 desc << "Failed to set " << source << " " << type << " sdp: " << reason;
249
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000250 if (err_desc) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000251 *err_desc = desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000252 }
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000253 LOG(LS_ERROR) << desc.str();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000254 return false;
255}
256
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257static bool BadSdp(cricket::ContentSource source,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000258 const std::string& type,
259 const std::string& reason,
260 std::string* err_desc) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261 if (source == cricket::CS_LOCAL) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000262 return BadSdp("local", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000263 } else {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000264 return BadSdp("remote", type, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000265 }
266}
267
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000268static bool BadLocalSdp(const std::string& type,
269 const std::string& reason,
270 std::string* err_desc) {
271 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
272}
273
274static bool BadRemoteSdp(const std::string& type,
275 const std::string& reason,
276 std::string* err_desc) {
277 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
278}
279
280static bool BadOfferSdp(cricket::ContentSource source,
281 const std::string& reason,
282 std::string* err_desc) {
283 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
284}
285
286static bool BadPranswerSdp(cricket::ContentSource source,
287 const std::string& reason,
288 std::string* err_desc) {
289 return BadSdp(source, SessionDescriptionInterface::kPrAnswer,
290 reason, err_desc);
291}
292
293static bool BadAnswerSdp(cricket::ContentSource source,
294 const std::string& reason,
295 std::string* err_desc) {
296 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000297}
298
299#define GET_STRING_OF_STATE(state) \
300 case cricket::BaseSession::state: \
301 result = #state; \
302 break;
303
304static std::string GetStateString(cricket::BaseSession::State state) {
305 std::string result;
306 switch (state) {
307 GET_STRING_OF_STATE(STATE_INIT)
308 GET_STRING_OF_STATE(STATE_SENTINITIATE)
309 GET_STRING_OF_STATE(STATE_RECEIVEDINITIATE)
310 GET_STRING_OF_STATE(STATE_SENTPRACCEPT)
311 GET_STRING_OF_STATE(STATE_SENTACCEPT)
312 GET_STRING_OF_STATE(STATE_RECEIVEDPRACCEPT)
313 GET_STRING_OF_STATE(STATE_RECEIVEDACCEPT)
314 GET_STRING_OF_STATE(STATE_SENTMODIFY)
315 GET_STRING_OF_STATE(STATE_RECEIVEDMODIFY)
316 GET_STRING_OF_STATE(STATE_SENTREJECT)
317 GET_STRING_OF_STATE(STATE_RECEIVEDREJECT)
318 GET_STRING_OF_STATE(STATE_SENTREDIRECT)
319 GET_STRING_OF_STATE(STATE_SENTTERMINATE)
320 GET_STRING_OF_STATE(STATE_RECEIVEDTERMINATE)
321 GET_STRING_OF_STATE(STATE_INPROGRESS)
322 GET_STRING_OF_STATE(STATE_DEINIT)
323 default:
324 ASSERT(false);
325 break;
326 }
327 return result;
328}
329
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000330#define GET_STRING_OF_ERROR_CODE(err) \
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000331 case cricket::BaseSession::err: \
332 result = #err; \
333 break;
334
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000335static std::string GetErrorCodeString(cricket::BaseSession::Error err) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000336 std::string result;
337 switch (err) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000338 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
339 GET_STRING_OF_ERROR_CODE(ERROR_TIME)
340 GET_STRING_OF_ERROR_CODE(ERROR_RESPONSE)
341 GET_STRING_OF_ERROR_CODE(ERROR_NETWORK)
342 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
343 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000344 default:
345 ASSERT(false);
346 break;
347 }
348 return result;
349}
350
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000351static std::string MakeErrorString(const std::string& error,
352 const std::string& desc) {
353 std::ostringstream ret;
354 ret << error << " " << desc;
355 return ret.str();
356}
357
358static std::string MakeTdErrorString(const std::string& desc) {
359 return MakeErrorString(kPushDownTDFailed, desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000360}
361
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000362// Set |option| to the highest-priority value of |key| in the optional
363// constraints if the key is found and has a valid value.
364static void SetOptionFromOptionalConstraint(
365 const MediaConstraintsInterface* constraints,
366 const std::string& key, cricket::Settable<int>* option) {
367 if (!constraints) {
368 return;
369 }
370 std::string string_value;
371 int value;
372 if (constraints->GetOptional().FindFirst(key, &string_value)) {
373 if (talk_base::FromString(string_value, &value)) {
374 option->Set(value);
375 }
376 }
377}
378
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000379// Help class used to remember if a a remote peer has requested ice restart by
380// by sending a description with new ice ufrag and password.
381class IceRestartAnswerLatch {
382 public:
383 IceRestartAnswerLatch() : ice_restart_(false) { }
384
wu@webrtc.org91053e72013-08-10 07:18:04 +0000385 // Returns true if CheckForRemoteIceRestart has been called with a new session
386 // description where ice password and ufrag has changed since last time
387 // Reset() was called.
388 bool Get() const {
389 return ice_restart_;
390 }
391
392 void Reset() {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000393 if (ice_restart_) {
394 ice_restart_ = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000395 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000396 }
397
398 void CheckForRemoteIceRestart(
399 const SessionDescriptionInterface* old_desc,
400 const SessionDescriptionInterface* new_desc) {
401 if (!old_desc || new_desc->type() != SessionDescriptionInterface::kOffer) {
402 return;
403 }
404 const SessionDescription* new_sd = new_desc->description();
405 const SessionDescription* old_sd = old_desc->description();
406 const ContentInfos& contents = new_sd->contents();
407 for (size_t index = 0; index < contents.size(); ++index) {
408 const ContentInfo* cinfo = &contents[index];
409 if (cinfo->rejected) {
410 continue;
411 }
412 // If the content isn't rejected, check if ufrag and password has
413 // changed.
414 const cricket::TransportDescription* new_transport_desc =
415 new_sd->GetTransportDescriptionByName(cinfo->name);
416 const cricket::TransportDescription* old_transport_desc =
417 old_sd->GetTransportDescriptionByName(cinfo->name);
418 if (!new_transport_desc || !old_transport_desc) {
419 // No transport description exist. This is not an ice restart.
420 continue;
421 }
422 if (new_transport_desc->ice_pwd != old_transport_desc->ice_pwd &&
423 new_transport_desc->ice_ufrag != old_transport_desc->ice_ufrag) {
424 LOG(LS_INFO) << "Remote peer request ice restart.";
425 ice_restart_ = true;
426 break;
427 }
428 }
429 }
430
431 private:
432 bool ice_restart_;
433};
434
wu@webrtc.org91053e72013-08-10 07:18:04 +0000435WebRtcSession::WebRtcSession(
436 cricket::ChannelManager* channel_manager,
437 talk_base::Thread* signaling_thread,
438 talk_base::Thread* worker_thread,
439 cricket::PortAllocator* port_allocator,
440 MediaStreamSignaling* mediastream_signaling)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000441 : cricket::BaseSession(signaling_thread, worker_thread, port_allocator,
442 talk_base::ToString(talk_base::CreateRandomId64() &
443 LLONG_MAX),
444 cricket::NS_JINGLE_RTP, false),
445 // RFC 3264: The numeric value of the session id and version in the
446 // o line MUST be representable with a "64 bit signed integer".
447 // Due to this constraint session id |sid_| is max limited to LLONG_MAX.
448 channel_manager_(channel_manager),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000449 mediastream_signaling_(mediastream_signaling),
450 ice_observer_(NULL),
451 ice_connection_state_(PeerConnectionInterface::kIceConnectionNew),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000452 older_version_remote_peer_(false),
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000453 dtls_enabled_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000454 data_channel_type_(cricket::DCT_NONE),
455 ice_restart_latch_(new IceRestartAnswerLatch) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000456}
457
458WebRtcSession::~WebRtcSession() {
459 if (voice_channel_.get()) {
460 SignalVoiceChannelDestroyed();
461 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
462 }
463 if (video_channel_.get()) {
464 SignalVideoChannelDestroyed();
465 channel_manager_->DestroyVideoChannel(video_channel_.release());
466 }
467 if (data_channel_.get()) {
468 SignalDataChannelDestroyed();
469 channel_manager_->DestroyDataChannel(data_channel_.release());
470 }
471 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
472 delete saved_candidates_[i];
473 }
474 delete identity();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000475}
476
wu@webrtc.org91053e72013-08-10 07:18:04 +0000477bool WebRtcSession::Initialize(
wu@webrtc.org97077a32013-10-25 21:18:33 +0000478 const PeerConnectionFactoryInterface::Options& options,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000479 const MediaConstraintsInterface* constraints,
480 DTLSIdentityServiceInterface* dtls_identity_service) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000481 // TODO(perkj): Take |constraints| into consideration. Return false if not all
482 // mandatory constraints can be fulfilled. Note that |constraints|
483 // can be null.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000484 bool value;
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000485
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000486 if (options.disable_encryption) {
487 dtls_enabled_ = false;
488 } else {
489 // Enable DTLS by default if |dtls_identity_service| is valid.
490 dtls_enabled_ = (dtls_identity_service != NULL);
491 // |constraints| can override the default |dtls_enabled_| value.
492 if (FindConstraint(
493 constraints,
494 MediaConstraintsInterface::kEnableDtlsSrtp,
495 &value, NULL)) {
496 dtls_enabled_ = value;
497 }
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000498 }
499
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000500 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000501 // It takes precendence over the disable_sctp_data_channels
502 // PeerConnectionFactoryInterface::Options.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000503 if (FindConstraint(
504 constraints, MediaConstraintsInterface::kEnableRtpDataChannels,
505 &value, NULL) && value) {
506 LOG(LS_INFO) << "Allowing RTP data engine.";
507 data_channel_type_ = cricket::DCT_RTP;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000508 } else {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000509 // DTLS has to be enabled to use SCTP.
wu@webrtc.org97077a32013-10-25 21:18:33 +0000510 if (!options.disable_sctp_data_channels && dtls_enabled_) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000511 LOG(LS_INFO) << "Allowing SCTP data engine.";
512 data_channel_type_ = cricket::DCT_SCTP;
513 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000514 }
515 if (data_channel_type_ != cricket::DCT_NONE) {
516 mediastream_signaling_->SetDataChannelFactory(this);
517 }
518
wu@webrtc.orgde305012013-10-31 15:40:38 +0000519 // Find DSCP constraint.
520 if (FindConstraint(
521 constraints,
522 MediaConstraintsInterface::kEnableDscp,
523 &value, NULL)) {
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +0000524 audio_options_.dscp.Set(value);
525 video_options_.dscp.Set(value);
526 }
527
528 // Find Suspend Below Min Bitrate constraint.
529 if (FindConstraint(
530 constraints,
531 MediaConstraintsInterface::kEnableVideoSuspendBelowMinBitrate,
532 &value,
533 NULL)) {
534 video_options_.suspend_below_min_bitrate.Set(value);
wu@webrtc.orgde305012013-10-31 15:40:38 +0000535 }
536
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000537 if (FindConstraint(
538 constraints,
539 MediaConstraintsInterface::kSkipEncodingUnusedStreams,
540 &value,
541 NULL)) {
542 video_options_.skip_encoding_unused_streams.Set(value);
543 }
544
henrike@webrtc.orgb0ecc1c2014-03-26 22:44:28 +0000545 SetOptionFromOptionalConstraint(constraints,
546 MediaConstraintsInterface::kScreencastMinBitrate,
547 &video_options_.screencast_min_bitrate);
548
549 // Find constraints for cpu overuse detection.
550 SetOptionFromOptionalConstraint(constraints,
551 MediaConstraintsInterface::kCpuUnderuseThreshold,
552 &video_options_.cpu_underuse_threshold);
553 SetOptionFromOptionalConstraint(constraints,
554 MediaConstraintsInterface::kCpuOveruseThreshold,
555 &video_options_.cpu_overuse_threshold);
556
557 if (FindConstraint(
558 constraints,
559 MediaConstraintsInterface::kCpuOveruseDetection,
560 &value,
561 NULL)) {
562 video_options_.cpu_overuse_detection.Set(value);
563 }
564 if (FindConstraint(
565 constraints,
566 MediaConstraintsInterface::kCpuOveruseEncodeUsage,
567 &value,
568 NULL)) {
569 video_options_.cpu_overuse_encode_usage.Set(value);
henrike@webrtc.orgdce3feb2014-03-26 01:17:30 +0000570 }
571
572 // Find improved wifi bwe constraint.
573 if (FindConstraint(
574 constraints,
575 MediaConstraintsInterface::kImprovedWifiBwe,
576 &value,
577 NULL)) {
578 video_options_.use_improved_wifi_bandwidth_estimator.Set(value);
579 }
580
wu@webrtc.orgcfe5e9c2014-03-27 17:03:58 +0000581 if (FindConstraint(
582 constraints,
583 MediaConstraintsInterface::kHighStartBitrate,
584 &value,
585 NULL)) {
586 video_options_.video_start_bitrate.Set(cricket::kHighStartBitrate);
587 }
588
589 if (FindConstraint(
590 constraints,
591 MediaConstraintsInterface::kVeryHighBitrate,
592 &value,
593 NULL)) {
594 video_options_.video_highest_bitrate.Set(
595 cricket::VideoOptions::VERY_HIGH);
596 } else if (FindConstraint(
597 constraints,
598 MediaConstraintsInterface::kHighBitrate,
599 &value,
600 NULL)) {
601 video_options_.video_highest_bitrate.Set(
602 cricket::VideoOptions::HIGH);
603 }
604
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605 const cricket::VideoCodec default_codec(
606 JsepSessionDescription::kDefaultVideoCodecId,
607 JsepSessionDescription::kDefaultVideoCodecName,
608 JsepSessionDescription::kMaxVideoCodecWidth,
609 JsepSessionDescription::kMaxVideoCodecHeight,
610 JsepSessionDescription::kDefaultVideoCodecFramerate,
611 JsepSessionDescription::kDefaultVideoCodecPreference);
612 channel_manager_->SetDefaultVideoEncoderConfig(
613 cricket::VideoEncoderConfig(default_codec));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000614
615 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
616 signaling_thread(),
617 channel_manager_,
618 mediastream_signaling_,
619 dtls_identity_service,
620 this,
621 id(),
622 data_channel_type_,
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000623 dtls_enabled_));
wu@webrtc.org91053e72013-08-10 07:18:04 +0000624
625 webrtc_session_desc_factory_->SignalIdentityReady.connect(
626 this, &WebRtcSession::OnIdentityReady);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000627
wu@webrtc.org97077a32013-10-25 21:18:33 +0000628 if (options.disable_encryption) {
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000629 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
mallinath@webrtc.org7e809c32013-09-30 18:59:08 +0000630 }
631
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000632 return true;
633}
634
635void WebRtcSession::Terminate() {
636 SetState(STATE_RECEIVEDTERMINATE);
637 RemoveUnusedChannelsAndTransports(NULL);
638 ASSERT(voice_channel_.get() == NULL);
639 ASSERT(video_channel_.get() == NULL);
640 ASSERT(data_channel_.get() == NULL);
641}
642
643bool WebRtcSession::StartCandidatesAllocation() {
644 // SpeculativelyConnectTransportChannels, will call ConnectChannels method
645 // from TransportProxy to start gathering ice candidates.
646 SpeculativelyConnectAllTransportChannels();
647 if (!saved_candidates_.empty()) {
648 // If there are saved candidates which arrived before local description is
649 // set, copy those to remote description.
650 CopySavedCandidates(remote_desc_.get());
651 }
652 // Push remote candidates present in remote description to transport channels.
653 UseCandidatesInSessionDescription(remote_desc_.get());
654 return true;
655}
656
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000657void WebRtcSession::SetSdesPolicy(cricket::SecurePolicy secure_policy) {
658 webrtc_session_desc_factory_->SetSdesPolicy(secure_policy);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659}
660
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000661cricket::SecurePolicy WebRtcSession::SdesPolicy() const {
662 return webrtc_session_desc_factory_->SdesPolicy();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000663}
664
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000665bool WebRtcSession::GetSslRole(talk_base::SSLRole* role) {
666 if (local_description() == NULL || remote_description() == NULL) {
667 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get "
668 << "SSL Role of the session.";
669 return false;
670 }
671
672 // TODO(mallinath) - Return role of each transport, as role may differ from
673 // one another.
674 // In current implementaion we just return the role of first transport in the
675 // transport map.
676 for (cricket::TransportMap::const_iterator iter = transport_proxies().begin();
677 iter != transport_proxies().end(); ++iter) {
678 if (iter->second->impl()) {
679 return iter->second->impl()->GetSslRole(role);
680 }
681 }
682 return false;
683}
684
wu@webrtc.org91053e72013-08-10 07:18:04 +0000685void WebRtcSession::CreateOffer(CreateSessionDescriptionObserver* observer,
686 const MediaConstraintsInterface* constraints) {
687 webrtc_session_desc_factory_->CreateOffer(observer, constraints);
688}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689
wu@webrtc.org91053e72013-08-10 07:18:04 +0000690void WebRtcSession::CreateAnswer(CreateSessionDescriptionObserver* observer,
691 const MediaConstraintsInterface* constraints) {
692 webrtc_session_desc_factory_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000693}
694
695bool WebRtcSession::SetLocalDescription(SessionDescriptionInterface* desc,
696 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000697 // Takes the ownership of |desc| regardless of the result.
698 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
699
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000700 // Validate SDP.
701 if (!ValidateSessionDescription(desc, cricket::CS_LOCAL, err_desc)) {
702 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000703 }
704
705 // Update the initiator flag if this session is the initiator.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000706 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000707 if (state() == STATE_INIT && action == kOffer) {
708 set_initiator(true);
709 }
710
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000711 cricket::SecurePolicy sdes_policy =
712 webrtc_session_desc_factory_->SdesPolicy();
713 cricket::CryptoType crypto_required = dtls_enabled_ ?
714 cricket::CT_DTLS : (sdes_policy == cricket::SEC_REQUIRED ?
715 cricket::CT_SDES : cricket::CT_NONE);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716 // Update the MediaContentDescription crypto settings as per the policy set.
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +0000717 UpdateSessionDescriptionSecurePolicy(crypto_required, desc->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718
719 set_local_description(desc->description()->Copy());
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000720 local_desc_.reset(desc_temp.release());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000721
722 // Transport and Media channels will be created only when offer is set.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000723 if (action == kOffer && !CreateChannels(local_desc_->description())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724 // TODO(mallinath) - Handle CreateChannel failure, as new local description
725 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000726 return BadLocalSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 }
728
729 // Remove channel and transport proxies, if MediaContentDescription is
730 // rejected.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000731 RemoveUnusedChannelsAndTransports(local_desc_->description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000733 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000734 return false;
735 }
736 // Kick starting the ice candidates allocation.
737 StartCandidatesAllocation();
738
739 // Update state and SSRC of local MediaStreams and DataChannels based on the
740 // local session description.
741 mediastream_signaling_->OnLocalDescriptionChanged(local_desc_.get());
742
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000743 talk_base::SSLRole role;
744 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
745 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
746 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000748 return BadLocalSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749 }
750 return true;
751}
752
753bool WebRtcSession::SetRemoteDescription(SessionDescriptionInterface* desc,
754 std::string* err_desc) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000755 // Takes the ownership of |desc| regardless of the result.
756 talk_base::scoped_ptr<SessionDescriptionInterface> desc_temp(desc);
757
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000758 // Validate SDP.
759 if (!ValidateSessionDescription(desc, cricket::CS_REMOTE, err_desc)) {
760 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761 }
762
763 // Transport and Media channels will be created only when offer is set.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +0000764 Action action = GetAction(desc->type());
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765 if (action == kOffer && !CreateChannels(desc->description())) {
766 // TODO(mallinath) - Handle CreateChannel failure, as new local description
767 // is applied. Restore back to old description.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000768 return BadRemoteSdp(desc->type(), kCreateChannelFailed, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769 }
770
771 // Remove channel and transport proxies, if MediaContentDescription is
772 // rejected.
773 RemoveUnusedChannelsAndTransports(desc->description());
774
775 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
776 // is called.
777 set_remote_description(desc->description()->Copy());
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000778 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779 return false;
780 }
781
782 // Update remote MediaStreams.
783 mediastream_signaling_->OnRemoteDescriptionChanged(desc);
784 if (local_description() && !UseCandidatesInSessionDescription(desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000785 return BadRemoteSdp(desc->type(), kInvalidCandidates, err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000786 }
787
788 // Copy all saved candidates.
789 CopySavedCandidates(desc);
790 // We retain all received candidates.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000791 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
792 remote_desc_.get(), desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793 // Check if this new SessionDescription contains new ice ufrag and password
794 // that indicates the remote peer requests ice restart.
795 ice_restart_latch_->CheckForRemoteIceRestart(remote_desc_.get(),
796 desc);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +0000797 remote_desc_.reset(desc_temp.release());
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000798
799 talk_base::SSLRole role;
800 if (data_channel_type_ == cricket::DCT_SCTP && GetSslRole(&role)) {
801 mediastream_signaling_->OnDtlsRoleReadyForSctp(role);
802 }
803
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000805 return BadRemoteSdp(desc->type(), GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 }
807 return true;
808}
809
810bool WebRtcSession::UpdateSessionState(
811 Action action, cricket::ContentSource source,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812 std::string* err_desc) {
813 // If there's already a pending error then no state transition should happen.
814 // But all call-sites should be verifying this before calling us!
815 ASSERT(error() == cricket::BaseSession::ERROR_NONE);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000816 std::string td_err;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817 if (action == kOffer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000818 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
819 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000820 }
821 SetState(source == cricket::CS_LOCAL ?
822 STATE_SENTINITIATE : STATE_RECEIVEDINITIATE);
823 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000824 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 }
826 } else if (action == kPrAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000827 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
828 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829 }
830 EnableChannels();
831 SetState(source == cricket::CS_LOCAL ?
832 STATE_SENTPRACCEPT : STATE_RECEIVEDPRACCEPT);
833 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000834 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835 }
836 } else if (action == kAnswer) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000837 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
838 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839 }
840 MaybeEnableMuxingSupport();
841 EnableChannels();
842 SetState(source == cricket::CS_LOCAL ?
843 STATE_SENTACCEPT : STATE_RECEIVEDACCEPT);
844 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000845 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 }
847 }
848 return true;
849}
850
851WebRtcSession::Action WebRtcSession::GetAction(const std::string& type) {
852 if (type == SessionDescriptionInterface::kOffer) {
853 return WebRtcSession::kOffer;
854 } else if (type == SessionDescriptionInterface::kPrAnswer) {
855 return WebRtcSession::kPrAnswer;
856 } else if (type == SessionDescriptionInterface::kAnswer) {
857 return WebRtcSession::kAnswer;
858 }
859 ASSERT(false && "unknown action type");
860 return WebRtcSession::kOffer;
861}
862
863bool WebRtcSession::ProcessIceMessage(const IceCandidateInterface* candidate) {
864 if (state() == STATE_INIT) {
865 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
866 << "without any offer (local or remote) "
867 << "session description.";
868 return false;
869 }
870
871 if (!candidate) {
872 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL";
873 return false;
874 }
875
876 if (!local_description() || !remote_description()) {
877 LOG(LS_INFO) << "ProcessIceMessage: Remote description not set, "
878 << "save the candidate for later use.";
879 saved_candidates_.push_back(
880 new JsepIceCandidate(candidate->sdp_mid(), candidate->sdp_mline_index(),
881 candidate->candidate()));
882 return true;
883 }
884
885 // Add this candidate to the remote session description.
886 if (!remote_desc_->AddCandidate(candidate)) {
887 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used";
888 return false;
889 }
890
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +0000891 return UseCandidate(candidate);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000892}
893
894bool WebRtcSession::GetTrackIdBySsrc(uint32 ssrc, std::string* id) {
895 if (GetLocalTrackId(ssrc, id)) {
896 if (GetRemoteTrackId(ssrc, id)) {
897 LOG(LS_WARNING) << "SSRC " << ssrc
898 << " exists in both local and remote descriptions";
899 return true; // We return the remote track id.
900 }
901 return true;
902 } else {
903 return GetRemoteTrackId(ssrc, id);
904 }
905}
906
907bool WebRtcSession::GetLocalTrackId(uint32 ssrc, std::string* track_id) {
908 if (!BaseSession::local_description())
909 return false;
910 return webrtc::GetTrackIdBySsrc(
911 BaseSession::local_description(), ssrc, track_id);
912}
913
914bool WebRtcSession::GetRemoteTrackId(uint32 ssrc, std::string* track_id) {
915 if (!BaseSession::remote_description())
916 return false;
917 return webrtc::GetTrackIdBySsrc(
918 BaseSession::remote_description(), ssrc, track_id);
919}
920
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000921std::string WebRtcSession::BadStateErrMsg(State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922 std::ostringstream desc;
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +0000923 desc << "Called in wrong state: " << GetStateString(state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924 return desc.str();
925}
926
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000927void WebRtcSession::SetAudioPlayout(uint32 ssrc, bool enable,
928 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929 ASSERT(signaling_thread()->IsCurrent());
930 if (!voice_channel_) {
931 LOG(LS_ERROR) << "SetAudioPlayout: No audio channel exists.";
932 return;
933 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000934 if (!voice_channel_->SetRemoteRenderer(ssrc, renderer)) {
935 // SetRenderer() can fail if the ssrc does not match any playout channel.
936 LOG(LS_ERROR) << "SetAudioPlayout: ssrc is incorrect: " << ssrc;
937 return;
938 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939 if (!voice_channel_->SetOutputScaling(ssrc, enable ? 1 : 0, enable ? 1 : 0)) {
940 // Allow that SetOutputScaling fail if |enable| is false but assert
941 // otherwise. This in the normal case when the underlying media channel has
942 // already been deleted.
943 ASSERT(enable == false);
944 }
945}
946
947void WebRtcSession::SetAudioSend(uint32 ssrc, bool enable,
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000948 const cricket::AudioOptions& options,
949 cricket::AudioRenderer* renderer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 ASSERT(signaling_thread()->IsCurrent());
951 if (!voice_channel_) {
952 LOG(LS_ERROR) << "SetAudioSend: No audio channel exists.";
953 return;
954 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000955 if (!voice_channel_->SetLocalRenderer(ssrc, renderer)) {
956 // SetRenderer() can fail if the ssrc does not match any send channel.
957 LOG(LS_ERROR) << "SetAudioSend: ssrc is incorrect: " << ssrc;
958 return;
959 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960 if (!voice_channel_->MuteStream(ssrc, !enable)) {
961 // Allow that MuteStream fail if |enable| is false but assert otherwise.
962 // This in the normal case when the underlying media channel has already
963 // been deleted.
964 ASSERT(enable == false);
965 return;
966 }
967 if (enable)
968 voice_channel_->SetChannelOptions(options);
969}
970
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000971void WebRtcSession::SetAudioPlayoutVolume(uint32 ssrc, double volume) {
972 ASSERT(signaling_thread()->IsCurrent());
973 ASSERT(volume >= 0 && volume <= 10);
974 if (!voice_channel_) {
975 LOG(LS_ERROR) << "SetAudioPlayoutVolume: No audio channel exists.";
976 return;
977 }
978
979 if (!voice_channel_->SetOutputScaling(ssrc, volume, volume))
980 ASSERT(false);
981}
982
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000983bool WebRtcSession::SetCaptureDevice(uint32 ssrc,
984 cricket::VideoCapturer* camera) {
985 ASSERT(signaling_thread()->IsCurrent());
986
987 if (!video_channel_.get()) {
988 // |video_channel_| doesnt't exist. Probably because the remote end doesnt't
989 // support video.
990 LOG(LS_WARNING) << "Video not used in this call.";
991 return false;
992 }
993 if (!video_channel_->SetCapturer(ssrc, camera)) {
994 // Allow that SetCapturer fail if |camera| is NULL but assert otherwise.
995 // This in the normal case when the underlying media channel has already
996 // been deleted.
997 ASSERT(camera == NULL);
998 return false;
999 }
1000 return true;
1001}
1002
1003void WebRtcSession::SetVideoPlayout(uint32 ssrc,
1004 bool enable,
1005 cricket::VideoRenderer* renderer) {
1006 ASSERT(signaling_thread()->IsCurrent());
1007 if (!video_channel_) {
1008 LOG(LS_WARNING) << "SetVideoPlayout: No video channel exists.";
1009 return;
1010 }
1011 if (!video_channel_->SetRenderer(ssrc, enable ? renderer : NULL)) {
1012 // Allow that SetRenderer fail if |renderer| is NULL but assert otherwise.
1013 // This in the normal case when the underlying media channel has already
1014 // been deleted.
1015 ASSERT(renderer == NULL);
1016 }
1017}
1018
1019void WebRtcSession::SetVideoSend(uint32 ssrc, bool enable,
1020 const cricket::VideoOptions* options) {
1021 ASSERT(signaling_thread()->IsCurrent());
1022 if (!video_channel_) {
1023 LOG(LS_WARNING) << "SetVideoSend: No video channel exists.";
1024 return;
1025 }
1026 if (!video_channel_->MuteStream(ssrc, !enable)) {
1027 // Allow that MuteStream fail if |enable| is false but assert otherwise.
1028 // This in the normal case when the underlying media channel has already
1029 // been deleted.
1030 ASSERT(enable == false);
1031 return;
1032 }
1033 if (enable && options)
1034 video_channel_->SetChannelOptions(*options);
1035}
1036
1037bool WebRtcSession::CanInsertDtmf(const std::string& track_id) {
1038 ASSERT(signaling_thread()->IsCurrent());
1039 if (!voice_channel_) {
1040 LOG(LS_ERROR) << "CanInsertDtmf: No audio channel exists.";
1041 return false;
1042 }
1043 uint32 send_ssrc = 0;
1044 // The Dtmf is negotiated per channel not ssrc, so we only check if the ssrc
1045 // exists.
1046 if (!GetAudioSsrcByTrackId(BaseSession::local_description(), track_id,
1047 &send_ssrc)) {
1048 LOG(LS_ERROR) << "CanInsertDtmf: Track does not exist: " << track_id;
1049 return false;
1050 }
1051 return voice_channel_->CanInsertDtmf();
1052}
1053
1054bool WebRtcSession::InsertDtmf(const std::string& track_id,
1055 int code, int duration) {
1056 ASSERT(signaling_thread()->IsCurrent());
1057 if (!voice_channel_) {
1058 LOG(LS_ERROR) << "InsertDtmf: No audio channel exists.";
1059 return false;
1060 }
1061 uint32 send_ssrc = 0;
1062 if (!VERIFY(GetAudioSsrcByTrackId(BaseSession::local_description(),
1063 track_id, &send_ssrc))) {
1064 LOG(LS_ERROR) << "InsertDtmf: Track does not exist: " << track_id;
1065 return false;
1066 }
1067 if (!voice_channel_->InsertDtmf(send_ssrc, code, duration,
1068 cricket::DF_SEND)) {
1069 LOG(LS_ERROR) << "Failed to insert DTMF to channel.";
1070 return false;
1071 }
1072 return true;
1073}
1074
1075sigslot::signal0<>* WebRtcSession::GetOnDestroyedSignal() {
1076 return &SignalVoiceChannelDestroyed;
1077}
1078
wu@webrtc.org78187522013-10-07 23:32:02 +00001079bool WebRtcSession::SendData(const cricket::SendDataParams& params,
1080 const talk_base::Buffer& payload,
1081 cricket::SendDataResult* result) {
1082 if (!data_channel_.get()) {
1083 LOG(LS_ERROR) << "SendData called when data_channel_ is NULL.";
1084 return false;
1085 }
1086 return data_channel_->SendData(params, payload, result);
1087}
1088
1089bool WebRtcSession::ConnectDataChannel(DataChannel* webrtc_data_channel) {
1090 if (!data_channel_.get()) {
1091 LOG(LS_ERROR) << "ConnectDataChannel called when data_channel_ is NULL.";
1092 return false;
1093 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001094 data_channel_->SignalReadyToSendData.connect(webrtc_data_channel,
1095 &DataChannel::OnChannelReady);
1096 data_channel_->SignalDataReceived.connect(webrtc_data_channel,
1097 &DataChannel::OnDataReceived);
wu@webrtc.org78187522013-10-07 23:32:02 +00001098 return true;
1099}
1100
1101void WebRtcSession::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001102 if (!data_channel_.get()) {
1103 LOG(LS_ERROR) << "DisconnectDataChannel called when data_channel_ is NULL.";
1104 return;
1105 }
wu@webrtc.org78187522013-10-07 23:32:02 +00001106 data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
1107 data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
1108}
1109
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001110void WebRtcSession::AddSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001111 if (!data_channel_.get()) {
1112 LOG(LS_ERROR) << "AddDataChannelStreams called when data_channel_ is NULL.";
1113 return;
1114 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001115 data_channel_->AddRecvStream(cricket::StreamParams::CreateLegacy(sid));
1116 data_channel_->AddSendStream(cricket::StreamParams::CreateLegacy(sid));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001117}
1118
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001119void WebRtcSession::RemoveSctpDataStream(uint32 sid) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001120 if (!data_channel_.get()) {
1121 LOG(LS_ERROR) << "RemoveDataChannelStreams called when data_channel_ is "
1122 << "NULL.";
1123 return;
1124 }
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00001125 data_channel_->RemoveRecvStream(sid);
1126 data_channel_->RemoveSendStream(sid);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001127}
1128
wu@webrtc.org07a6fbe2013-11-04 18:41:34 +00001129bool WebRtcSession::ReadyToSendData() const {
1130 return data_channel_.get() && data_channel_->ready_to_send_data();
1131}
1132
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133talk_base::scoped_refptr<DataChannel> WebRtcSession::CreateDataChannel(
wu@webrtc.org78187522013-10-07 23:32:02 +00001134 const std::string& label,
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001135 const InternalDataChannelInit* config) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001136 if (state() == STATE_RECEIVEDTERMINATE) {
1137 return NULL;
1138 }
1139 if (data_channel_type_ == cricket::DCT_NONE) {
1140 LOG(LS_ERROR) << "CreateDataChannel: Data is not supported in this call.";
1141 return NULL;
1142 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001143 InternalDataChannelInit new_config =
1144 config ? (*config) : InternalDataChannelInit();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001145 if (data_channel_type_ == cricket::DCT_SCTP) {
1146 if (new_config.id < 0) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001147 talk_base::SSLRole role;
1148 if (GetSslRole(&role) &&
1149 !mediastream_signaling_->AllocateSctpSid(role, &new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001150 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
1151 return NULL;
1152 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001153 } else if (!mediastream_signaling_->IsSctpSidAvailable(new_config.id)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
1155 << "because the id is already in use or out of range.";
1156 return NULL;
1157 }
1158 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001159
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001160 talk_base::scoped_refptr<DataChannel> channel(DataChannel::Create(
1161 this, data_channel_type_, label, new_config));
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001162 if (channel && !mediastream_signaling_->AddDataChannel(channel))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 return NULL;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001164
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 return channel;
1166}
1167
1168cricket::DataChannelType WebRtcSession::data_channel_type() const {
1169 return data_channel_type_;
1170}
1171
wu@webrtc.org91053e72013-08-10 07:18:04 +00001172bool WebRtcSession::IceRestartPending() const {
1173 return ice_restart_latch_->Get();
1174}
1175
1176void WebRtcSession::ResetIceRestartLatch() {
1177 ice_restart_latch_->Reset();
1178}
1179
1180void WebRtcSession::OnIdentityReady(talk_base::SSLIdentity* identity) {
1181 SetIdentity(identity);
1182}
1183
1184bool WebRtcSession::waiting_for_identity() const {
1185 return webrtc_session_desc_factory_->waiting_for_identity();
1186}
1187
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188void WebRtcSession::SetIceConnectionState(
1189 PeerConnectionInterface::IceConnectionState state) {
1190 if (ice_connection_state_ == state) {
1191 return;
1192 }
1193
1194 // ASSERT that the requested transition is allowed. Note that
1195 // WebRtcSession does not implement "kIceConnectionClosed" (that is handled
1196 // within PeerConnection). This switch statement should compile away when
1197 // ASSERTs are disabled.
1198 switch (ice_connection_state_) {
1199 case PeerConnectionInterface::kIceConnectionNew:
1200 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking);
1201 break;
1202 case PeerConnectionInterface::kIceConnectionChecking:
1203 ASSERT(state == PeerConnectionInterface::kIceConnectionFailed ||
1204 state == PeerConnectionInterface::kIceConnectionConnected);
1205 break;
1206 case PeerConnectionInterface::kIceConnectionConnected:
1207 ASSERT(state == PeerConnectionInterface::kIceConnectionDisconnected ||
1208 state == PeerConnectionInterface::kIceConnectionChecking ||
1209 state == PeerConnectionInterface::kIceConnectionCompleted);
1210 break;
1211 case PeerConnectionInterface::kIceConnectionCompleted:
1212 ASSERT(state == PeerConnectionInterface::kIceConnectionConnected ||
1213 state == PeerConnectionInterface::kIceConnectionDisconnected);
1214 break;
1215 case PeerConnectionInterface::kIceConnectionFailed:
1216 ASSERT(state == PeerConnectionInterface::kIceConnectionNew);
1217 break;
1218 case PeerConnectionInterface::kIceConnectionDisconnected:
1219 ASSERT(state == PeerConnectionInterface::kIceConnectionChecking ||
1220 state == PeerConnectionInterface::kIceConnectionConnected ||
1221 state == PeerConnectionInterface::kIceConnectionCompleted ||
1222 state == PeerConnectionInterface::kIceConnectionFailed);
1223 break;
1224 case PeerConnectionInterface::kIceConnectionClosed:
1225 ASSERT(false);
1226 break;
1227 default:
1228 ASSERT(false);
1229 break;
1230 }
1231
1232 ice_connection_state_ = state;
1233 if (ice_observer_) {
1234 ice_observer_->OnIceConnectionChange(ice_connection_state_);
1235 }
1236}
1237
1238void WebRtcSession::OnTransportRequestSignaling(
1239 cricket::Transport* transport) {
1240 ASSERT(signaling_thread()->IsCurrent());
1241 transport->OnSignalingReady();
1242 if (ice_observer_) {
1243 ice_observer_->OnIceGatheringChange(
1244 PeerConnectionInterface::kIceGatheringGathering);
1245 }
1246}
1247
1248void WebRtcSession::OnTransportConnecting(cricket::Transport* transport) {
1249 ASSERT(signaling_thread()->IsCurrent());
1250 // start monitoring for the write state of the transport.
1251 OnTransportWritable(transport);
1252}
1253
1254void WebRtcSession::OnTransportWritable(cricket::Transport* transport) {
1255 ASSERT(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 if (transport->all_channels_writable()) {
henrike@webrtc.org05376342014-03-10 15:53:12 +00001257 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 } else if (transport->HasChannels()) {
1259 // If the current state is Connected or Completed, then there were writable
1260 // channels but now there are not, so the next state must be Disconnected.
1261 if (ice_connection_state_ ==
1262 PeerConnectionInterface::kIceConnectionConnected ||
1263 ice_connection_state_ ==
1264 PeerConnectionInterface::kIceConnectionCompleted) {
1265 SetIceConnectionState(
1266 PeerConnectionInterface::kIceConnectionDisconnected);
1267 }
1268 }
1269}
1270
mallinath@webrtc.org385857d2014-02-14 00:56:12 +00001271void WebRtcSession::OnTransportCompleted(cricket::Transport* transport) {
1272 ASSERT(signaling_thread()->IsCurrent());
1273 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
1274}
1275
1276void WebRtcSession::OnTransportFailed(cricket::Transport* transport) {
1277 ASSERT(signaling_thread()->IsCurrent());
1278 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
1279}
1280
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281void WebRtcSession::OnTransportProxyCandidatesReady(
1282 cricket::TransportProxy* proxy, const cricket::Candidates& candidates) {
1283 ASSERT(signaling_thread()->IsCurrent());
1284 ProcessNewLocalCandidate(proxy->content_name(), candidates);
1285}
1286
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287void WebRtcSession::OnCandidatesAllocationDone() {
1288 ASSERT(signaling_thread()->IsCurrent());
1289 if (ice_observer_) {
1290 ice_observer_->OnIceGatheringChange(
1291 PeerConnectionInterface::kIceGatheringComplete);
1292 ice_observer_->OnIceComplete();
1293 }
1294}
1295
1296// Enabling voice and video channel.
1297void WebRtcSession::EnableChannels() {
1298 if (voice_channel_ && !voice_channel_->enabled())
1299 voice_channel_->Enable(true);
1300
1301 if (video_channel_ && !video_channel_->enabled())
1302 video_channel_->Enable(true);
1303
1304 if (data_channel_.get() && !data_channel_->enabled())
1305 data_channel_->Enable(true);
1306}
1307
1308void WebRtcSession::ProcessNewLocalCandidate(
1309 const std::string& content_name,
1310 const cricket::Candidates& candidates) {
1311 int sdp_mline_index;
1312 if (!GetLocalCandidateMediaIndex(content_name, &sdp_mline_index)) {
1313 LOG(LS_ERROR) << "ProcessNewLocalCandidate: content name "
1314 << content_name << " not found";
1315 return;
1316 }
1317
1318 for (cricket::Candidates::const_iterator citer = candidates.begin();
1319 citer != candidates.end(); ++citer) {
1320 // Use content_name as the candidate media id.
1321 JsepIceCandidate candidate(content_name, sdp_mline_index, *citer);
1322 if (ice_observer_) {
1323 ice_observer_->OnIceCandidate(&candidate);
1324 }
1325 if (local_desc_) {
1326 local_desc_->AddCandidate(&candidate);
1327 }
1328 }
1329}
1330
1331// Returns the media index for a local ice candidate given the content name.
1332bool WebRtcSession::GetLocalCandidateMediaIndex(const std::string& content_name,
1333 int* sdp_mline_index) {
1334 if (!BaseSession::local_description() || !sdp_mline_index)
1335 return false;
1336
1337 bool content_found = false;
1338 const ContentInfos& contents = BaseSession::local_description()->contents();
1339 for (size_t index = 0; index < contents.size(); ++index) {
1340 if (contents[index].name == content_name) {
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00001341 *sdp_mline_index = static_cast<int>(index);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342 content_found = true;
1343 break;
1344 }
1345 }
1346 return content_found;
1347}
1348
1349bool WebRtcSession::UseCandidatesInSessionDescription(
1350 const SessionDescriptionInterface* remote_desc) {
1351 if (!remote_desc)
1352 return true;
1353 bool ret = true;
1354 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
1355 const IceCandidateCollection* candidates = remote_desc->candidates(m);
1356 for (size_t n = 0; n < candidates->count(); ++n) {
1357 ret = UseCandidate(candidates->at(n));
1358 if (!ret)
1359 break;
1360 }
1361 }
1362 return ret;
1363}
1364
1365bool WebRtcSession::UseCandidate(
1366 const IceCandidateInterface* candidate) {
1367
1368 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
1369 size_t remote_content_size =
1370 BaseSession::remote_description()->contents().size();
1371 if (mediacontent_index >= remote_content_size) {
1372 LOG(LS_ERROR)
1373 << "UseRemoteCandidateInSession: Invalid candidate media index.";
1374 return false;
1375 }
1376
1377 cricket::ContentInfo content =
1378 BaseSession::remote_description()->contents()[mediacontent_index];
1379 std::vector<cricket::Candidate> candidates;
1380 candidates.push_back(candidate->candidate());
1381 // Invoking BaseSession method to handle remote candidates.
1382 std::string error;
1383 if (OnRemoteCandidates(content.name, candidates, &error)) {
1384 // Candidates successfully submitted for checking.
1385 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
1386 ice_connection_state_ ==
1387 PeerConnectionInterface::kIceConnectionDisconnected) {
1388 // If state is New, then the session has just gotten its first remote ICE
1389 // candidates, so go to Checking.
1390 // If state is Disconnected, the session is re-using old candidates or
1391 // receiving additional ones, so go to Checking.
1392 // If state is Connected, stay Connected.
1393 // TODO(bemasc): If state is Connected, and the new candidates are for a
1394 // newly added transport, then the state actually _should_ move to
1395 // checking. Add a way to distinguish that case.
1396 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1397 }
1398 // TODO(bemasc): If state is Completed, go back to Connected.
1399 } else {
fischman@webrtc.org4f2bd682014-03-28 18:13:34 +00001400 if (!error.empty()) {
1401 LOG(LS_WARNING) << error;
1402 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403 }
1404 return true;
1405}
1406
1407void WebRtcSession::RemoveUnusedChannelsAndTransports(
1408 const SessionDescription* desc) {
1409 const cricket::ContentInfo* voice_info =
1410 cricket::GetFirstAudioContent(desc);
1411 if ((!voice_info || voice_info->rejected) && voice_channel_) {
1412 mediastream_signaling_->OnAudioChannelClose();
1413 SignalVoiceChannelDestroyed();
1414 const std::string content_name = voice_channel_->content_name();
1415 channel_manager_->DestroyVoiceChannel(voice_channel_.release());
1416 DestroyTransportProxy(content_name);
1417 }
1418
1419 const cricket::ContentInfo* video_info =
1420 cricket::GetFirstVideoContent(desc);
1421 if ((!video_info || video_info->rejected) && video_channel_) {
1422 mediastream_signaling_->OnVideoChannelClose();
1423 SignalVideoChannelDestroyed();
1424 const std::string content_name = video_channel_->content_name();
1425 channel_manager_->DestroyVideoChannel(video_channel_.release());
1426 DestroyTransportProxy(content_name);
1427 }
1428
1429 const cricket::ContentInfo* data_info =
1430 cricket::GetFirstDataContent(desc);
1431 if ((!data_info || data_info->rejected) && data_channel_) {
1432 mediastream_signaling_->OnDataChannelClose();
1433 SignalDataChannelDestroyed();
1434 const std::string content_name = data_channel_->content_name();
1435 channel_manager_->DestroyDataChannel(data_channel_.release());
1436 DestroyTransportProxy(content_name);
1437 }
1438}
1439
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001440// TODO(mallinath) - Add a correct error code if the channels are not creatued
1441// due to BUNDLE is enabled but rtcp-mux is disabled.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442bool WebRtcSession::CreateChannels(const SessionDescription* desc) {
1443 // Disabling the BUNDLE flag in PortAllocator if offer disabled it.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001444 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1445 if (state() == STATE_INIT && !bundle_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446 port_allocator()->set_flags(port_allocator()->flags() &
1447 ~cricket::PORTALLOCATOR_ENABLE_BUNDLE);
1448 }
1449
1450 // Creating the media channels and transport proxies.
1451 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
1452 if (voice && !voice->rejected && !voice_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001453 if (!CreateVoiceChannel(voice)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454 LOG(LS_ERROR) << "Failed to create voice channel.";
1455 return false;
1456 }
1457 }
1458
1459 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
1460 if (video && !video->rejected && !video_channel_) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001461 if (!CreateVideoChannel(video)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462 LOG(LS_ERROR) << "Failed to create video channel.";
1463 return false;
1464 }
1465 }
1466
1467 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
1468 if (data_channel_type_ != cricket::DCT_NONE &&
1469 data && !data->rejected && !data_channel_.get()) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001470 if (!CreateDataChannel(data)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 LOG(LS_ERROR) << "Failed to create data channel.";
1472 return false;
1473 }
1474 }
1475
1476 return true;
1477}
1478
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001479bool WebRtcSession::CreateVoiceChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 voice_channel_.reset(channel_manager_->CreateVoiceChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001481 this, content->name, true));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001482 if (!voice_channel_.get())
1483 return false;
1484
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001485 voice_channel_->SetChannelOptions(audio_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001486 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487}
1488
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001489bool WebRtcSession::CreateVideoChannel(const cricket::ContentInfo* content) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490 video_channel_.reset(channel_manager_->CreateVideoChannel(
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001491 this, content->name, true, voice_channel_.get()));
wu@webrtc.orgde305012013-10-31 15:40:38 +00001492 if (!video_channel_.get())
1493 return false;
1494
henrike@webrtc.org6e3dbc22014-03-25 17:09:47 +00001495 video_channel_->SetChannelOptions(video_options_);
wu@webrtc.orgde305012013-10-31 15:40:38 +00001496 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497}
1498
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001499bool WebRtcSession::CreateDataChannel(const cricket::ContentInfo* content) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001500 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001501 data_channel_.reset(channel_manager_->CreateDataChannel(
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001502 this, content->name, !sctp, data_channel_type_));
wu@webrtc.org91053e72013-08-10 07:18:04 +00001503 if (!data_channel_.get()) {
1504 return false;
1505 }
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001506 if (sctp) {
1507 mediastream_signaling_->OnDataTransportCreatedForSctp();
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001508 data_channel_->SignalDataReceived.connect(
1509 this, &WebRtcSession::OnDataChannelMessageReceived);
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001510 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001511 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512}
1513
1514void WebRtcSession::CopySavedCandidates(
1515 SessionDescriptionInterface* dest_desc) {
1516 if (!dest_desc) {
1517 ASSERT(false);
1518 return;
1519 }
1520 for (size_t i = 0; i < saved_candidates_.size(); ++i) {
1521 dest_desc->AddCandidate(saved_candidates_[i]);
1522 delete saved_candidates_[i];
1523 }
1524 saved_candidates_.clear();
1525}
1526
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001527void WebRtcSession::OnDataChannelMessageReceived(
1528 cricket::DataChannel* channel,
1529 const cricket::ReceiveDataParams& params,
1530 const talk_base::Buffer& payload) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001531 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001532 if (params.type == cricket::DMT_CONTROL &&
1533 mediastream_signaling_->IsSctpSidAvailable(params.ssrc)) {
1534 // Received CONTROL on unused sid, process as an OPEN message.
1535 mediastream_signaling_->AddDataChannelFromOpenMessage(params, payload);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001536 }
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001537 // otherwise ignore the message.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001538}
1539
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001540// Returns false if bundle is enabled and rtcp_mux is disabled.
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001541bool WebRtcSession::ValidateBundleSettings(const SessionDescription* desc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001542 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
1543 if (!bundle_enabled)
1544 return true;
1545
1546 const cricket::ContentGroup* bundle_group =
1547 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
1548 ASSERT(bundle_group != NULL);
1549
1550 const cricket::ContentInfos& contents = desc->contents();
1551 for (cricket::ContentInfos::const_iterator citer = contents.begin();
1552 citer != contents.end(); ++citer) {
1553 const cricket::ContentInfo* content = (&*citer);
1554 ASSERT(content != NULL);
1555 if (bundle_group->HasContentName(content->name) &&
1556 !content->rejected && content->type == cricket::NS_JINGLE_RTP) {
1557 if (!HasRtcpMuxEnabled(content))
1558 return false;
1559 }
1560 }
1561 // RTCP-MUX is enabled in all the contents.
1562 return true;
1563}
1564
1565bool WebRtcSession::HasRtcpMuxEnabled(
1566 const cricket::ContentInfo* content) {
1567 const cricket::MediaContentDescription* description =
1568 static_cast<cricket::MediaContentDescription*>(content->description);
1569 return description->rtcp_mux();
1570}
1571
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001572bool WebRtcSession::ValidateSessionDescription(
1573 const SessionDescriptionInterface* sdesc,
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001574 cricket::ContentSource source, std::string* err_desc) {
1575 std::string type;
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001576 if (error() != cricket::BaseSession::ERROR_NONE) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001577 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001578 }
1579
1580 if (!sdesc || !sdesc->description()) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001581 return BadSdp(source, type, kInvalidSdp, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001582 }
1583
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001584 type = sdesc->type();
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001585 Action action = GetAction(sdesc->type());
1586 if (source == cricket::CS_LOCAL) {
1587 if (!ExpectSetLocalDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001588 return BadLocalSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001589 } else {
1590 if (!ExpectSetRemoteDescription(action))
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001591 return BadRemoteSdp(type, BadStateErrMsg(state()), err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001592 }
1593
1594 // Verify crypto settings.
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001595 std::string crypto_error;
henrike@webrtc.orgb90991d2014-03-04 19:54:57 +00001596 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
1597 dtls_enabled_) &&
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00001598 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001599 return BadSdp(source, type, crypto_error, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001600 }
1601
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001602 // Verify ice-ufrag and ice-pwd.
1603 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001604 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001605 }
1606
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001607 if (!ValidateBundleSettings(sdesc->description())) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001608 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001609 }
1610
1611 // Verify m-lines in Answer when compared against Offer.
1612 if (action == kAnswer) {
1613 const cricket::SessionDescription* offer_desc =
1614 (source == cricket::CS_LOCAL) ? remote_description()->description() :
1615 local_description()->description();
1616 if (!VerifyMediaDescriptions(sdesc->description(), offer_desc)) {
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001617 return BadAnswerSdp(source, kMlineMismatch, err_desc);
sergeyu@chromium.org0be6aa02013-08-23 23:21:25 +00001618 }
1619 }
1620
1621 return true;
1622}
1623
1624bool WebRtcSession::ExpectSetLocalDescription(Action action) {
1625 return ((action == kOffer && state() == STATE_INIT) ||
1626 // update local offer
1627 (action == kOffer && state() == STATE_SENTINITIATE) ||
1628 // update the current ongoing session.
1629 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1630 (action == kOffer && state() == STATE_SENTACCEPT) ||
1631 (action == kOffer && state() == STATE_INPROGRESS) ||
1632 // accept remote offer
1633 (action == kAnswer && state() == STATE_RECEIVEDINITIATE) ||
1634 (action == kAnswer && state() == STATE_SENTPRACCEPT) ||
1635 (action == kPrAnswer && state() == STATE_RECEIVEDINITIATE) ||
1636 (action == kPrAnswer && state() == STATE_SENTPRACCEPT));
1637}
1638
1639bool WebRtcSession::ExpectSetRemoteDescription(Action action) {
1640 return ((action == kOffer && state() == STATE_INIT) ||
1641 // update remote offer
1642 (action == kOffer && state() == STATE_RECEIVEDINITIATE) ||
1643 // update the current ongoing session
1644 (action == kOffer && state() == STATE_RECEIVEDACCEPT) ||
1645 (action == kOffer && state() == STATE_SENTACCEPT) ||
1646 (action == kOffer && state() == STATE_INPROGRESS) ||
1647 // accept local offer
1648 (action == kAnswer && state() == STATE_SENTINITIATE) ||
1649 (action == kAnswer && state() == STATE_RECEIVEDPRACCEPT) ||
1650 (action == kPrAnswer && state() == STATE_SENTINITIATE) ||
1651 (action == kPrAnswer && state() == STATE_RECEIVEDPRACCEPT));
1652}
1653
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00001654std::string WebRtcSession::GetSessionErrorMsg() {
1655 std::ostringstream desc;
1656 desc << kSessionError << GetErrorCodeString(error()) << ". ";
1657 desc << kSessionErrorDesc << error_desc() << ".";
1658 return desc.str();
1659}
1660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001661} // namespace webrtc