blob: 7fafad711482b24185bb90021733f13c7917d9f3 [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/peerconnection.h"
29
30#include <vector>
31
32#include "talk/app/webrtc/dtmfsender.h"
33#include "talk/app/webrtc/jsepicecandidate.h"
34#include "talk/app/webrtc/jsepsessiondescription.h"
35#include "talk/app/webrtc/mediastreamhandler.h"
36#include "talk/app/webrtc/streamcollection.h"
37#include "talk/base/logging.h"
38#include "talk/base/stringencode.h"
39#include "talk/session/media/channelmanager.h"
40
41namespace {
42
43using webrtc::PeerConnectionInterface;
44
45// The min number of tokens in the ice uri.
46static const size_t kMinIceUriTokens = 2;
47// The min number of tokens must present in Turn host uri.
48// e.g. user@turn.example.org
49static const size_t kTurnHostTokensNum = 2;
50// Number of tokens must be preset when TURN uri has transport param.
51static const size_t kTurnTransportTokensNum = 2;
52// The default stun port.
wu@webrtc.org91053e72013-08-10 07:18:04 +000053static const int kDefaultStunPort = 3478;
54static const int kDefaultStunTlsPort = 5349;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055static const char kTransport[] = "transport";
wu@webrtc.org91053e72013-08-10 07:18:04 +000056static const char kUdpTransportType[] = "udp";
57static const char kTcpTransportType[] = "tcp";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
59// NOTE: Must be in the same order as the ServiceType enum.
60static const char* kValidIceServiceTypes[] = {
61 "stun", "stuns", "turn", "turns", "invalid" };
62
63enum ServiceType {
64 STUN, // Indicates a STUN server.
65 STUNS, // Indicates a STUN server used with a TLS session.
66 TURN, // Indicates a TURN server
67 TURNS, // Indicates a TURN server used with a TLS session.
68 INVALID, // Unknown.
69};
70
71enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000072 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073 MSG_SET_SESSIONDESCRIPTION_FAILED,
74 MSG_GETSTATS,
75 MSG_ICECONNECTIONCHANGE,
76 MSG_ICEGATHERINGCHANGE,
77 MSG_ICECANDIDATE,
78 MSG_ICECOMPLETE,
79};
80
81struct CandidateMsg : public talk_base::MessageData {
82 explicit CandidateMsg(const webrtc::JsepIceCandidate* candidate)
83 : candidate(candidate) {
84 }
85 talk_base::scoped_ptr<const webrtc::JsepIceCandidate> candidate;
86};
87
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088struct SetSessionDescriptionMsg : public talk_base::MessageData {
89 explicit SetSessionDescriptionMsg(
90 webrtc::SetSessionDescriptionObserver* observer)
91 : observer(observer) {
92 }
93
94 talk_base::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
95 std::string error;
96};
97
98struct GetStatsMsg : public talk_base::MessageData {
99 explicit GetStatsMsg(webrtc::StatsObserver* observer)
100 : observer(observer) {
101 }
102 webrtc::StatsReports reports;
103 talk_base::scoped_refptr<webrtc::StatsObserver> observer;
104};
105
106typedef webrtc::PortAllocatorFactoryInterface::StunConfiguration
107 StunConfiguration;
108typedef webrtc::PortAllocatorFactoryInterface::TurnConfiguration
109 TurnConfiguration;
110
111bool ParseIceServers(const PeerConnectionInterface::IceServers& configuration,
112 std::vector<StunConfiguration>* stun_config,
113 std::vector<TurnConfiguration>* turn_config) {
114 // draft-nandakumar-rtcweb-stun-uri-01
115 // stunURI = scheme ":" stun-host [ ":" stun-port ]
116 // scheme = "stun" / "stuns"
117 // stun-host = IP-literal / IPv4address / reg-name
118 // stun-port = *DIGIT
119
120 // draft-petithuguenin-behave-turn-uris-01
121 // turnURI = scheme ":" turn-host [ ":" turn-port ]
122 // [ "?transport=" transport ]
123 // scheme = "turn" / "turns"
124 // transport = "udp" / "tcp" / transport-ext
125 // transport-ext = 1*unreserved
126 // turn-host = IP-literal / IPv4address / reg-name
127 // turn-port = *DIGIT
128
129 // TODO(ronghuawu): Handle IPV6 address
130 for (size_t i = 0; i < configuration.size(); ++i) {
131 webrtc::PeerConnectionInterface::IceServer server = configuration[i];
132 if (server.uri.empty()) {
133 LOG(WARNING) << "Empty uri.";
134 continue;
135 }
136 std::vector<std::string> tokens;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000137 std::string turn_transport_type = kUdpTransportType;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000138 talk_base::tokenize(server.uri, '?', &tokens);
139 std::string uri_without_transport = tokens[0];
140 // Let's look into transport= param, if it exists.
141 if (tokens.size() == kTurnTransportTokensNum) { // ?transport= is present.
142 std::string uri_transport_param = tokens[1];
143 talk_base::tokenize(uri_transport_param, '=', &tokens);
144 if (tokens[0] == kTransport) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000145 // As per above grammar transport param will be consist of lower case
146 // letters.
147 if (tokens[1] != kUdpTransportType && tokens[1] != kTcpTransportType) {
148 LOG(LS_WARNING) << "Transport param should always be udp or tcp.";
149 continue;
150 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000151 turn_transport_type = tokens[1];
152 }
153 }
154
155 tokens.clear();
156 talk_base::tokenize(uri_without_transport, ':', &tokens);
157 if (tokens.size() < kMinIceUriTokens) {
158 LOG(WARNING) << "Invalid uri: " << server.uri;
159 continue;
160 }
161 ServiceType service_type = INVALID;
162 const std::string& type = tokens[0];
163 for (size_t i = 0; i < ARRAY_SIZE(kValidIceServiceTypes); ++i) {
164 if (type.compare(kValidIceServiceTypes[i]) == 0) {
165 service_type = static_cast<ServiceType>(i);
166 break;
167 }
168 }
169 if (service_type == INVALID) {
170 LOG(WARNING) << "Invalid service type: " << type;
171 continue;
172 }
173 std::string address = tokens[1];
wu@webrtc.org91053e72013-08-10 07:18:04 +0000174 int port = kDefaultStunPort;
wu@webrtc.org78187522013-10-07 23:32:02 +0000175 if (service_type == TURNS) {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000176 port = kDefaultStunTlsPort;
wu@webrtc.org78187522013-10-07 23:32:02 +0000177 turn_transport_type = kTcpTransportType;
178 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000179
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180 if (tokens.size() > kMinIceUriTokens) {
181 if (!talk_base::FromString(tokens[2], &port)) {
182 LOG(LS_WARNING) << "Failed to parse port string: " << tokens[2];
183 continue;
184 }
185
186 if (port <= 0 || port > 0xffff) {
187 LOG(WARNING) << "Invalid port: " << port;
188 continue;
189 }
190 }
191
192 switch (service_type) {
193 case STUN:
194 case STUNS:
195 stun_config->push_back(StunConfiguration(address, port));
196 break;
wu@webrtc.org91053e72013-08-10 07:18:04 +0000197 case TURN:
198 case TURNS: {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000199 if (server.username.empty()) {
200 // Turn url example from the spec |url:"turn:user@turn.example.org"|.
201 std::vector<std::string> turn_tokens;
202 talk_base::tokenize(address, '@', &turn_tokens);
203 if (turn_tokens.size() == kTurnHostTokensNum) {
204 server.username = talk_base::s_url_decode(turn_tokens[0]);
205 address = turn_tokens[1];
206 }
207 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000208
209 bool secure = (service_type == TURNS);
210
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000211 turn_config->push_back(TurnConfiguration(address, port,
212 server.username,
213 server.password,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000214 turn_transport_type,
215 secure));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000216 // STUN functionality is part of TURN.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000217 // Note: If there is only TURNS is supplied as part of configuration,
218 // we will have problem in fetching server reflexive candidate, as
219 // currently we don't have support of TCP/TLS in stunport.cc.
220 // In that case we should fetch server reflexive addess from
221 // TURN allocate response.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000222 stun_config->push_back(StunConfiguration(address, port));
223 break;
224 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000225 case INVALID:
226 default:
227 LOG(WARNING) << "Configuration not supported: " << server.uri;
228 return false;
229 }
230 }
231 return true;
232}
233
234// Check if we can send |new_stream| on a PeerConnection.
235// Currently only one audio but multiple video track is supported per
236// PeerConnection.
237bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
238 webrtc::MediaStreamInterface* new_stream) {
239 if (!new_stream || !current_streams)
240 return false;
241 if (current_streams->find(new_stream->label()) != NULL) {
242 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
243 << " is already added.";
244 return false;
245 }
246
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000247 return true;
248}
249
250} // namespace
251
252namespace webrtc {
253
254PeerConnection::PeerConnection(PeerConnectionFactory* factory)
255 : factory_(factory),
256 observer_(NULL),
257 signaling_state_(kStable),
258 ice_state_(kIceNew),
259 ice_connection_state_(kIceConnectionNew),
260 ice_gathering_state_(kIceGatheringNew) {
261}
262
263PeerConnection::~PeerConnection() {
264 if (mediastream_signaling_)
265 mediastream_signaling_->TearDown();
266 if (stream_handler_container_)
267 stream_handler_container_->TearDown();
268}
269
270bool PeerConnection::Initialize(
271 const PeerConnectionInterface::IceServers& configuration,
272 const MediaConstraintsInterface* constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000273 PortAllocatorFactoryInterface* allocator_factory,
274 DTLSIdentityServiceInterface* dtls_identity_service,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275 PeerConnectionObserver* observer) {
276 std::vector<PortAllocatorFactoryInterface::StunConfiguration> stun_config;
277 std::vector<PortAllocatorFactoryInterface::TurnConfiguration> turn_config;
278 if (!ParseIceServers(configuration, &stun_config, &turn_config)) {
279 return false;
280 }
281
282 return DoInitialize(stun_config, turn_config, constraints,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000283 allocator_factory, dtls_identity_service, observer);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000284}
285
286bool PeerConnection::DoInitialize(
287 const StunConfigurations& stun_config,
288 const TurnConfigurations& turn_config,
289 const MediaConstraintsInterface* constraints,
290 webrtc::PortAllocatorFactoryInterface* allocator_factory,
wu@webrtc.org91053e72013-08-10 07:18:04 +0000291 DTLSIdentityServiceInterface* dtls_identity_service,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000292 PeerConnectionObserver* observer) {
293 ASSERT(observer != NULL);
294 if (!observer)
295 return false;
296 observer_ = observer;
297 port_allocator_.reset(
298 allocator_factory->CreatePortAllocator(stun_config, turn_config));
299 // To handle both internal and externally created port allocator, we will
300 // enable BUNDLE here. Also enabling TURN and disable legacy relay service.
301 port_allocator_->set_flags(cricket::PORTALLOCATOR_ENABLE_BUNDLE |
302 cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
303 cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
304 // No step delay is used while allocating ports.
305 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
306
307 mediastream_signaling_.reset(new MediaStreamSignaling(
wu@webrtc.org967bfff2013-09-19 05:49:50 +0000308 factory_->signaling_thread(), this, factory_->channel_manager()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000309
310 session_.reset(new WebRtcSession(factory_->channel_manager(),
311 factory_->signaling_thread(),
312 factory_->worker_thread(),
313 port_allocator_.get(),
314 mediastream_signaling_.get()));
315 stream_handler_container_.reset(new MediaStreamHandlerContainer(
316 session_.get(), session_.get()));
317 stats_.set_session(session_.get());
318
319 // Initialize the WebRtcSession. It creates transport channels etc.
wu@webrtc.org91053e72013-08-10 07:18:04 +0000320 if (!session_->Initialize(constraints, dtls_identity_service))
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000321 return false;
322
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000323 // Register PeerConnection as receiver of local ice candidates.
324 // All the callbacks will be posted to the application from PeerConnection.
325 session_->RegisterIceObserver(this);
326 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
327 return true;
328}
329
330talk_base::scoped_refptr<StreamCollectionInterface>
331PeerConnection::local_streams() {
332 return mediastream_signaling_->local_streams();
333}
334
335talk_base::scoped_refptr<StreamCollectionInterface>
336PeerConnection::remote_streams() {
337 return mediastream_signaling_->remote_streams();
338}
339
340bool PeerConnection::AddStream(MediaStreamInterface* local_stream,
341 const MediaConstraintsInterface* constraints) {
342 if (IsClosed()) {
343 return false;
344 }
345 if (!CanAddLocalMediaStream(mediastream_signaling_->local_streams(),
346 local_stream))
347 return false;
348
349 // TODO(perkj): Implement support for MediaConstraints in AddStream.
350 if (!mediastream_signaling_->AddLocalStream(local_stream)) {
351 return false;
352 }
353 stats_.AddStream(local_stream);
354 observer_->OnRenegotiationNeeded();
355 return true;
356}
357
358void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
fischman@webrtc.org32001ef2013-08-12 23:26:21 +0000359 mediastream_signaling_->RemoveLocalStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000360 if (IsClosed()) {
361 return;
362 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000363 observer_->OnRenegotiationNeeded();
364}
365
366talk_base::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
367 AudioTrackInterface* track) {
368 if (!track) {
369 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
370 return NULL;
371 }
372 if (!mediastream_signaling_->local_streams()->FindAudioTrack(track->id())) {
373 LOG(LS_ERROR) << "CreateDtmfSender is called with a non local audio track.";
374 return NULL;
375 }
376
377 talk_base::scoped_refptr<DtmfSenderInterface> sender(
378 DtmfSender::Create(track, signaling_thread(), session_.get()));
379 if (!sender.get()) {
380 LOG(LS_ERROR) << "CreateDtmfSender failed on DtmfSender::Create.";
381 return NULL;
382 }
383 return DtmfSenderProxy::Create(signaling_thread(), sender.get());
384}
385
386bool PeerConnection::GetStats(StatsObserver* observer,
387 MediaStreamTrackInterface* track) {
388 if (!VERIFY(observer != NULL)) {
389 LOG(LS_ERROR) << "GetStats - observer is NULL.";
390 return false;
391 }
392
393 stats_.UpdateStats();
394 talk_base::scoped_ptr<GetStatsMsg> msg(new GetStatsMsg(observer));
395 if (!stats_.GetStats(track, &(msg->reports))) {
396 return false;
397 }
398 signaling_thread()->Post(this, MSG_GETSTATS, msg.release());
399 return true;
400}
401
402PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
403 return signaling_state_;
404}
405
406PeerConnectionInterface::IceState PeerConnection::ice_state() {
407 return ice_state_;
408}
409
410PeerConnectionInterface::IceConnectionState
411PeerConnection::ice_connection_state() {
412 return ice_connection_state_;
413}
414
415PeerConnectionInterface::IceGatheringState
416PeerConnection::ice_gathering_state() {
417 return ice_gathering_state_;
418}
419
420talk_base::scoped_refptr<DataChannelInterface>
421PeerConnection::CreateDataChannel(
422 const std::string& label,
423 const DataChannelInit* config) {
424 talk_base::scoped_refptr<DataChannelInterface> channel(
425 session_->CreateDataChannel(label, config));
426 if (!channel.get())
427 return NULL;
428
wu@webrtc.org91053e72013-08-10 07:18:04 +0000429 // If we've already passed the underlying channel's setup phase, have the
430 // MediaStreamSignaling update data channels manually.
431 if (session_->data_channel() != NULL &&
432 session_->data_channel_type() == cricket::DCT_SCTP) {
433 mediastream_signaling_->UpdateLocalSctpDataChannels();
434 mediastream_signaling_->UpdateRemoteSctpDataChannels();
435 }
436
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000437 observer_->OnRenegotiationNeeded();
wu@webrtc.org91053e72013-08-10 07:18:04 +0000438
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000439 return DataChannelProxy::Create(signaling_thread(), channel.get());
440}
441
442void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
443 const MediaConstraintsInterface* constraints) {
444 if (!VERIFY(observer != NULL)) {
445 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
446 return;
447 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000448 session_->CreateOffer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000449}
450
451void PeerConnection::CreateAnswer(
452 CreateSessionDescriptionObserver* observer,
453 const MediaConstraintsInterface* constraints) {
454 if (!VERIFY(observer != NULL)) {
455 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
456 return;
457 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000458 session_->CreateAnswer(observer, constraints);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000459}
460
461void PeerConnection::SetLocalDescription(
462 SetSessionDescriptionObserver* observer,
463 SessionDescriptionInterface* desc) {
464 if (!VERIFY(observer != NULL)) {
465 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
466 return;
467 }
468 if (!desc) {
469 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
470 return;
471 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000472 // Update stats here so that we have the most recent stats for tracks and
473 // streams that might be removed by updating the session description.
474 stats_.UpdateStats();
475 std::string error;
476 if (!session_->SetLocalDescription(desc, &error)) {
477 PostSetSessionDescriptionFailure(observer, error);
478 return;
479 }
480 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
481 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
482}
483
484void PeerConnection::SetRemoteDescription(
485 SetSessionDescriptionObserver* observer,
486 SessionDescriptionInterface* desc) {
487 if (!VERIFY(observer != NULL)) {
488 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
489 return;
490 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000491 if (!desc) {
492 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
493 return;
494 }
495 // Update stats here so that we have the most recent stats for tracks and
496 // streams that might be removed by updating the session description.
497 stats_.UpdateStats();
498 std::string error;
499 if (!session_->SetRemoteDescription(desc, &error)) {
500 PostSetSessionDescriptionFailure(observer, error);
501 return;
502 }
503 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
504 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
505}
506
507void PeerConnection::PostSetSessionDescriptionFailure(
508 SetSessionDescriptionObserver* observer,
509 const std::string& error) {
510 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
511 msg->error = error;
512 signaling_thread()->Post(this, MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
513}
514
515bool PeerConnection::UpdateIce(const IceServers& configuration,
516 const MediaConstraintsInterface* constraints) {
517 // TODO(ronghuawu): Implement UpdateIce.
518 LOG(LS_ERROR) << "UpdateIce is not implemented.";
519 return false;
520}
521
522bool PeerConnection::AddIceCandidate(
523 const IceCandidateInterface* ice_candidate) {
524 return session_->ProcessIceMessage(ice_candidate);
525}
526
527const SessionDescriptionInterface* PeerConnection::local_description() const {
528 return session_->local_description();
529}
530
531const SessionDescriptionInterface* PeerConnection::remote_description() const {
532 return session_->remote_description();
533}
534
535void PeerConnection::Close() {
536 // Update stats here so that we have the most recent stats for tracks and
537 // streams before the channels are closed.
538 stats_.UpdateStats();
539
540 session_->Terminate();
541}
542
543void PeerConnection::OnSessionStateChange(cricket::BaseSession* /*session*/,
544 cricket::BaseSession::State state) {
545 switch (state) {
546 case cricket::BaseSession::STATE_INIT:
547 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +0000548 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000549 case cricket::BaseSession::STATE_SENTINITIATE:
550 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
551 break;
552 case cricket::BaseSession::STATE_SENTPRACCEPT:
553 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
554 break;
555 case cricket::BaseSession::STATE_RECEIVEDINITIATE:
556 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
557 break;
558 case cricket::BaseSession::STATE_RECEIVEDPRACCEPT:
559 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
560 break;
561 case cricket::BaseSession::STATE_SENTACCEPT:
562 case cricket::BaseSession::STATE_RECEIVEDACCEPT:
563 ChangeSignalingState(PeerConnectionInterface::kStable);
564 break;
565 case cricket::BaseSession::STATE_RECEIVEDTERMINATE:
566 ChangeSignalingState(PeerConnectionInterface::kClosed);
567 break;
568 default:
569 break;
570 }
571}
572
573void PeerConnection::OnMessage(talk_base::Message* msg) {
574 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000575 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
576 SetSessionDescriptionMsg* param =
577 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
578 param->observer->OnSuccess();
579 delete param;
580 break;
581 }
582 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
583 SetSessionDescriptionMsg* param =
584 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
585 param->observer->OnFailure(param->error);
586 delete param;
587 break;
588 }
589 case MSG_GETSTATS: {
590 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
591 param->observer->OnComplete(param->reports);
592 delete param;
593 break;
594 }
595 case MSG_ICECONNECTIONCHANGE: {
596 observer_->OnIceConnectionChange(ice_connection_state_);
597 break;
598 }
599 case MSG_ICEGATHERINGCHANGE: {
600 observer_->OnIceGatheringChange(ice_gathering_state_);
601 break;
602 }
603 case MSG_ICECANDIDATE: {
604 CandidateMsg* data = static_cast<CandidateMsg*>(msg->pdata);
605 observer_->OnIceCandidate(data->candidate.get());
606 delete data;
607 break;
608 }
609 case MSG_ICECOMPLETE: {
610 observer_->OnIceComplete();
611 break;
612 }
613 default:
614 ASSERT(false && "Not implemented");
615 break;
616 }
617}
618
619void PeerConnection::OnAddRemoteStream(MediaStreamInterface* stream) {
620 stats_.AddStream(stream);
621 observer_->OnAddStream(stream);
622}
623
624void PeerConnection::OnRemoveRemoteStream(MediaStreamInterface* stream) {
625 stream_handler_container_->RemoveRemoteStream(stream);
626 observer_->OnRemoveStream(stream);
627}
628
629void PeerConnection::OnAddDataChannel(DataChannelInterface* data_channel) {
630 observer_->OnDataChannel(DataChannelProxy::Create(signaling_thread(),
631 data_channel));
632}
633
634void PeerConnection::OnAddRemoteAudioTrack(MediaStreamInterface* stream,
635 AudioTrackInterface* audio_track,
636 uint32 ssrc) {
637 stream_handler_container_->AddRemoteAudioTrack(stream, audio_track, ssrc);
638}
639
640void PeerConnection::OnAddRemoteVideoTrack(MediaStreamInterface* stream,
641 VideoTrackInterface* video_track,
642 uint32 ssrc) {
643 stream_handler_container_->AddRemoteVideoTrack(stream, video_track, ssrc);
644}
645
646void PeerConnection::OnRemoveRemoteAudioTrack(
647 MediaStreamInterface* stream,
648 AudioTrackInterface* audio_track) {
649 stream_handler_container_->RemoveRemoteTrack(stream, audio_track);
650}
651
652void PeerConnection::OnRemoveRemoteVideoTrack(
653 MediaStreamInterface* stream,
654 VideoTrackInterface* video_track) {
655 stream_handler_container_->RemoveRemoteTrack(stream, video_track);
656}
657void PeerConnection::OnAddLocalAudioTrack(MediaStreamInterface* stream,
658 AudioTrackInterface* audio_track,
659 uint32 ssrc) {
660 stream_handler_container_->AddLocalAudioTrack(stream, audio_track, ssrc);
661}
662void PeerConnection::OnAddLocalVideoTrack(MediaStreamInterface* stream,
663 VideoTrackInterface* video_track,
664 uint32 ssrc) {
665 stream_handler_container_->AddLocalVideoTrack(stream, video_track, ssrc);
666}
667
668void PeerConnection::OnRemoveLocalAudioTrack(MediaStreamInterface* stream,
669 AudioTrackInterface* audio_track) {
670 stream_handler_container_->RemoveLocalTrack(stream, audio_track);
671}
672
673void PeerConnection::OnRemoveLocalVideoTrack(MediaStreamInterface* stream,
674 VideoTrackInterface* video_track) {
675 stream_handler_container_->RemoveLocalTrack(stream, video_track);
676}
677
678void PeerConnection::OnRemoveLocalStream(MediaStreamInterface* stream) {
679 stream_handler_container_->RemoveLocalStream(stream);
680}
681
682void PeerConnection::OnIceConnectionChange(
683 PeerConnectionInterface::IceConnectionState new_state) {
684 ice_connection_state_ = new_state;
685 signaling_thread()->Post(this, MSG_ICECONNECTIONCHANGE);
686}
687
688void PeerConnection::OnIceGatheringChange(
689 PeerConnectionInterface::IceGatheringState new_state) {
690 if (IsClosed()) {
691 return;
692 }
693 ice_gathering_state_ = new_state;
694 signaling_thread()->Post(this, MSG_ICEGATHERINGCHANGE);
695}
696
697void PeerConnection::OnIceCandidate(const IceCandidateInterface* candidate) {
698 JsepIceCandidate* candidate_copy = NULL;
699 if (candidate) {
700 // TODO(ronghuawu): Make IceCandidateInterface reference counted instead
701 // of making a copy.
702 candidate_copy = new JsepIceCandidate(candidate->sdp_mid(),
703 candidate->sdp_mline_index(),
704 candidate->candidate());
705 }
706 // The Post takes the ownership of the |candidate_copy|.
707 signaling_thread()->Post(this, MSG_ICECANDIDATE,
708 new CandidateMsg(candidate_copy));
709}
710
711void PeerConnection::OnIceComplete() {
712 signaling_thread()->Post(this, MSG_ICECOMPLETE);
713}
714
715void PeerConnection::ChangeSignalingState(
716 PeerConnectionInterface::SignalingState signaling_state) {
717 signaling_state_ = signaling_state;
718 if (signaling_state == kClosed) {
719 ice_connection_state_ = kIceConnectionClosed;
720 observer_->OnIceConnectionChange(ice_connection_state_);
721 if (ice_gathering_state_ != kIceGatheringComplete) {
722 ice_gathering_state_ = kIceGatheringComplete;
723 observer_->OnIceGatheringChange(ice_gathering_state_);
724 }
725 }
726 observer_->OnSignalingChange(signaling_state_);
727 observer_->OnStateChange(PeerConnectionObserver::kSignalingState);
728}
729
730} // namespace webrtc