Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / modules / mediastream / RTCPeerConnection.cpp
1 /*
2  * Copyright (C) 2012 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer
12  *    in the documentation and/or other materials provided with the
13  *    distribution.
14  * 3. Neither the name of Google Inc. nor the names of its contributors
15  *    may be used to endorse or promote products derived from this
16  *    software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32
33 #include "modules/mediastream/RTCPeerConnection.h"
34
35 #include "bindings/v8/ArrayValue.h"
36 #include "bindings/v8/ExceptionMessages.h"
37 #include "bindings/v8/ExceptionState.h"
38 #include "core/dom/Document.h"
39 #include "core/dom/ExceptionCode.h"
40 #include "core/dom/ExecutionContext.h"
41 #include "core/events/Event.h"
42 #include "core/frame/LocalFrame.h"
43 #include "core/html/VoidCallback.h"
44 #include "core/loader/FrameLoader.h"
45 #include "core/loader/FrameLoaderClient.h"
46 #include "modules/mediastream/MediaConstraintsImpl.h"
47 #include "modules/mediastream/MediaStreamEvent.h"
48 #include "modules/mediastream/RTCDTMFSender.h"
49 #include "modules/mediastream/RTCDataChannel.h"
50 #include "modules/mediastream/RTCDataChannelEvent.h"
51 #include "modules/mediastream/RTCErrorCallback.h"
52 #include "modules/mediastream/RTCIceCandidateEvent.h"
53 #include "modules/mediastream/RTCSessionDescription.h"
54 #include "modules/mediastream/RTCSessionDescriptionCallback.h"
55 #include "modules/mediastream/RTCSessionDescriptionRequestImpl.h"
56 #include "modules/mediastream/RTCStatsCallback.h"
57 #include "modules/mediastream/RTCStatsRequestImpl.h"
58 #include "modules/mediastream/RTCVoidRequestImpl.h"
59 #include "platform/mediastream/RTCConfiguration.h"
60 #include "public/platform/Platform.h"
61 #include "public/platform/WebMediaStream.h"
62 #include "public/platform/WebRTCConfiguration.h"
63 #include "public/platform/WebRTCDataChannelHandler.h"
64 #include "public/platform/WebRTCDataChannelInit.h"
65 #include "public/platform/WebRTCICECandidate.h"
66 #include "public/platform/WebRTCSessionDescription.h"
67 #include "public/platform/WebRTCSessionDescriptionRequest.h"
68 #include "public/platform/WebRTCStatsRequest.h"
69 #include "public/platform/WebRTCVoidRequest.h"
70
71 namespace WebCore {
72
73 namespace {
74
75 static bool throwExceptionIfSignalingStateClosed(RTCPeerConnection::SignalingState state, ExceptionState& exceptionState)
76 {
77     if (state == RTCPeerConnection::SignalingStateClosed) {
78         exceptionState.throwDOMException(InvalidStateError, "The RTCPeerConnection's signalingState is 'closed'.");
79         return true;
80     }
81
82     return false;
83 }
84
85 } // namespace
86
87 PassRefPtr<RTCConfiguration> RTCPeerConnection::parseConfiguration(const Dictionary& configuration, ExceptionState& exceptionState)
88 {
89     if (configuration.isUndefinedOrNull())
90         return nullptr;
91
92     ArrayValue iceServers;
93     bool ok = configuration.get("iceServers", iceServers);
94     if (!ok || iceServers.isUndefinedOrNull()) {
95         exceptionState.throwTypeError("Malformed RTCConfiguration");
96         return nullptr;
97     }
98
99     size_t numberOfServers;
100     ok = iceServers.length(numberOfServers);
101     if (!ok) {
102         exceptionState.throwTypeError("Malformed RTCConfiguration");
103         return nullptr;
104     }
105
106     RefPtr<RTCConfiguration> rtcConfiguration = RTCConfiguration::create();
107
108     for (size_t i = 0; i < numberOfServers; ++i) {
109         Dictionary iceServer;
110         ok = iceServers.get(i, iceServer);
111         if (!ok) {
112             exceptionState.throwTypeError("Malformed RTCIceServer");
113             return nullptr;
114         }
115
116         Vector<String> names;
117         iceServer.getOwnPropertyNames(names);
118
119         Vector<String> urlStrings;
120         if (names.contains("urls")) {
121             if (!iceServer.get("urls", urlStrings) || !urlStrings.size()) {
122                 String urlString;
123                 if (iceServer.get("urls", urlString)) {
124                     urlStrings.append(urlString);
125                 } else {
126                     exceptionState.throwTypeError("Malformed RTCIceServer");
127                     return nullptr;
128                 }
129             }
130         } else if (names.contains("url")) {
131             String urlString;
132             if (iceServer.get("url", urlString)) {
133                 urlStrings.append(urlString);
134             } else {
135                 exceptionState.throwTypeError("Malformed RTCIceServer");
136                 return nullptr;
137             }
138         } else {
139             exceptionState.throwTypeError("Malformed RTCIceServer");
140             return nullptr;
141         }
142
143         String username, credential;
144         iceServer.get("username", username);
145         iceServer.get("credential", credential);
146
147         for (Vector<String>::iterator iter = urlStrings.begin(); iter != urlStrings.end(); ++iter) {
148             KURL url(KURL(), *iter);
149             if (!url.isValid() || !(url.protocolIs("turn") || url.protocolIs("turns") || url.protocolIs("stun"))) {
150                 exceptionState.throwTypeError("Malformed URL");
151                 return nullptr;
152             }
153
154             rtcConfiguration->appendServer(RTCIceServer::create(url, username, credential));
155         }
156     }
157
158     return rtcConfiguration.release();
159 }
160
161 PassRefPtr<RTCPeerConnection> RTCPeerConnection::create(ExecutionContext* context, const Dictionary& rtcConfiguration, const Dictionary& mediaConstraints, ExceptionState& exceptionState)
162 {
163     RefPtr<RTCConfiguration> configuration = parseConfiguration(rtcConfiguration, exceptionState);
164     if (exceptionState.hadException())
165         return nullptr;
166
167     blink::WebMediaConstraints constraints = MediaConstraintsImpl::create(mediaConstraints, exceptionState);
168     if (exceptionState.hadException())
169         return nullptr;
170
171     RefPtr<RTCPeerConnection> peerConnection = adoptRef(new RTCPeerConnection(context, configuration.release(), constraints, exceptionState));
172     peerConnection->suspendIfNeeded();
173     if (exceptionState.hadException())
174         return nullptr;
175
176     return peerConnection.release();
177 }
178
179 RTCPeerConnection::RTCPeerConnection(ExecutionContext* context, PassRefPtr<RTCConfiguration> configuration, blink::WebMediaConstraints constraints, ExceptionState& exceptionState)
180     : ActiveDOMObject(context)
181     , m_signalingState(SignalingStateStable)
182     , m_iceGatheringState(ICEGatheringStateNew)
183     , m_iceConnectionState(ICEConnectionStateNew)
184     , m_dispatchScheduledEventRunner(this, &RTCPeerConnection::dispatchScheduledEvent)
185     , m_stopped(false)
186 {
187     ScriptWrappable::init(this);
188     Document* document = toDocument(executionContext());
189
190     if (!document->frame()) {
191         exceptionState.throwDOMException(NotSupportedError, "PeerConnections may not be created in detached documents.");
192         return;
193     }
194
195     m_peerHandler = adoptPtr(blink::Platform::current()->createRTCPeerConnectionHandler(this));
196     if (!m_peerHandler) {
197         exceptionState.throwDOMException(NotSupportedError, "No PeerConnection handler can be created, perhaps WebRTC is disabled?");
198         return;
199     }
200
201     document->frame()->loader().client()->dispatchWillStartUsingPeerConnectionHandler(m_peerHandler.get());
202
203     if (!m_peerHandler->initialize(configuration, constraints)) {
204         exceptionState.throwDOMException(NotSupportedError, "Failed to initialize native PeerConnection.");
205         return;
206     }
207 }
208
209 RTCPeerConnection::~RTCPeerConnection()
210 {
211     stop();
212 }
213
214 void RTCPeerConnection::createOffer(PassOwnPtr<RTCSessionDescriptionCallback> successCallback, PassOwnPtr<RTCErrorCallback> errorCallback, const Dictionary& mediaConstraints, ExceptionState& exceptionState)
215 {
216     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
217         return;
218
219     ASSERT(successCallback);
220
221     blink::WebMediaConstraints constraints = MediaConstraintsImpl::create(mediaConstraints, exceptionState);
222     if (exceptionState.hadException())
223         return;
224
225     RefPtr<RTCSessionDescriptionRequest> request = RTCSessionDescriptionRequestImpl::create(executionContext(), successCallback, errorCallback);
226     m_peerHandler->createOffer(request.release(), constraints);
227 }
228
229 void RTCPeerConnection::createAnswer(PassOwnPtr<RTCSessionDescriptionCallback> successCallback, PassOwnPtr<RTCErrorCallback> errorCallback, const Dictionary& mediaConstraints, ExceptionState& exceptionState)
230 {
231     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
232         return;
233
234     ASSERT(successCallback);
235
236     blink::WebMediaConstraints constraints = MediaConstraintsImpl::create(mediaConstraints, exceptionState);
237     if (exceptionState.hadException())
238         return;
239
240     RefPtr<RTCSessionDescriptionRequest> request = RTCSessionDescriptionRequestImpl::create(executionContext(), successCallback, errorCallback);
241     m_peerHandler->createAnswer(request.release(), constraints);
242 }
243
244 void RTCPeerConnection::setLocalDescription(PassRefPtr<RTCSessionDescription> prpSessionDescription, PassOwnPtr<VoidCallback> successCallback, PassOwnPtr<RTCErrorCallback> errorCallback, ExceptionState& exceptionState)
245 {
246     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
247         return;
248
249     RefPtr<RTCSessionDescription> sessionDescription = prpSessionDescription;
250     if (!sessionDescription) {
251         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "RTCSessionDescription"));
252         return;
253     }
254
255     RefPtr<RTCVoidRequest> request = RTCVoidRequestImpl::create(executionContext(), successCallback, errorCallback);
256     m_peerHandler->setLocalDescription(request.release(), sessionDescription->webSessionDescription());
257 }
258
259 PassRefPtr<RTCSessionDescription> RTCPeerConnection::localDescription(ExceptionState& exceptionState)
260 {
261     blink::WebRTCSessionDescription webSessionDescription = m_peerHandler->localDescription();
262     if (webSessionDescription.isNull())
263         return nullptr;
264
265     RefPtr<RTCSessionDescription> sessionDescription = RTCSessionDescription::create(webSessionDescription);
266     return sessionDescription.release();
267 }
268
269 void RTCPeerConnection::setRemoteDescription(PassRefPtr<RTCSessionDescription> prpSessionDescription, PassOwnPtr<VoidCallback> successCallback, PassOwnPtr<RTCErrorCallback> errorCallback, ExceptionState& exceptionState)
270 {
271     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
272         return;
273
274     RefPtr<RTCSessionDescription> sessionDescription = prpSessionDescription;
275     if (!sessionDescription) {
276         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "RTCSessionDescription"));
277         return;
278     }
279
280     RefPtr<RTCVoidRequest> request = RTCVoidRequestImpl::create(executionContext(), successCallback, errorCallback);
281     m_peerHandler->setRemoteDescription(request.release(), sessionDescription->webSessionDescription());
282 }
283
284 PassRefPtr<RTCSessionDescription> RTCPeerConnection::remoteDescription(ExceptionState& exceptionState)
285 {
286     blink::WebRTCSessionDescription webSessionDescription = m_peerHandler->remoteDescription();
287     if (webSessionDescription.isNull())
288         return nullptr;
289
290     RefPtr<RTCSessionDescription> desc = RTCSessionDescription::create(webSessionDescription);
291     return desc.release();
292 }
293
294 void RTCPeerConnection::updateIce(const Dictionary& rtcConfiguration, const Dictionary& mediaConstraints, ExceptionState& exceptionState)
295 {
296     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
297         return;
298
299     RefPtr<RTCConfiguration> configuration = parseConfiguration(rtcConfiguration, exceptionState);
300     if (exceptionState.hadException())
301         return;
302
303     blink::WebMediaConstraints constraints = MediaConstraintsImpl::create(mediaConstraints, exceptionState);
304     if (exceptionState.hadException())
305         return;
306
307     bool valid = m_peerHandler->updateICE(configuration.release(), constraints);
308     if (!valid)
309         exceptionState.throwDOMException(SyntaxError, "Could not update the ICE Agent with the given configuration.");
310 }
311
312 void RTCPeerConnection::addIceCandidate(RTCIceCandidate* iceCandidate, ExceptionState& exceptionState)
313 {
314     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
315         return;
316
317     if (!iceCandidate) {
318         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "RTCIceCandidate"));
319         return;
320     }
321
322     bool valid = m_peerHandler->addICECandidate(iceCandidate->webCandidate());
323     if (!valid)
324         exceptionState.throwDOMException(SyntaxError, "The ICE candidate could not be added.");
325 }
326
327 void RTCPeerConnection::addIceCandidate(RTCIceCandidate* iceCandidate, PassOwnPtr<VoidCallback> successCallback, PassOwnPtr<RTCErrorCallback> errorCallback, ExceptionState& exceptionState)
328 {
329     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
330         return;
331
332     if (!iceCandidate) {
333         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "RTCIceCandidate"));
334         return;
335     }
336     ASSERT(successCallback);
337     ASSERT(errorCallback);
338
339     RefPtr<RTCVoidRequest> request = RTCVoidRequestImpl::create(executionContext(), successCallback, errorCallback);
340
341     bool implemented = m_peerHandler->addICECandidate(request.release(), iceCandidate->webCandidate());
342     if (!implemented)
343         exceptionState.throwDOMException(NotSupportedError, "This method is not yet implemented.");
344 }
345
346 String RTCPeerConnection::signalingState() const
347 {
348     switch (m_signalingState) {
349     case SignalingStateStable:
350         return "stable";
351     case SignalingStateHaveLocalOffer:
352         return "have-local-offer";
353     case SignalingStateHaveRemoteOffer:
354         return "have-remote-offer";
355     case SignalingStateHaveLocalPrAnswer:
356         return "have-local-pranswer";
357     case SignalingStateHaveRemotePrAnswer:
358         return "have-remote-pranswer";
359     case SignalingStateClosed:
360         return "closed";
361     }
362
363     ASSERT_NOT_REACHED();
364     return String();
365 }
366
367 String RTCPeerConnection::iceGatheringState() const
368 {
369     switch (m_iceGatheringState) {
370     case ICEGatheringStateNew:
371         return "new";
372     case ICEGatheringStateGathering:
373         return "gathering";
374     case ICEGatheringStateComplete:
375         return "complete";
376     }
377
378     ASSERT_NOT_REACHED();
379     return String();
380 }
381
382 String RTCPeerConnection::iceConnectionState() const
383 {
384     switch (m_iceConnectionState) {
385     case ICEConnectionStateNew:
386         return "new";
387     case ICEConnectionStateChecking:
388         return "checking";
389     case ICEConnectionStateConnected:
390         return "connected";
391     case ICEConnectionStateCompleted:
392         return "completed";
393     case ICEConnectionStateFailed:
394         return "failed";
395     case ICEConnectionStateDisconnected:
396         return "disconnected";
397     case ICEConnectionStateClosed:
398         return "closed";
399     }
400
401     ASSERT_NOT_REACHED();
402     return String();
403 }
404
405 void RTCPeerConnection::addStream(PassRefPtr<MediaStream> prpStream, const Dictionary& mediaConstraints, ExceptionState& exceptionState)
406 {
407     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
408         return;
409
410     RefPtr<MediaStream> stream = prpStream;
411     if (!stream) {
412         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "MediaStream"));
413         return;
414     }
415
416     if (m_localStreams.contains(stream))
417         return;
418
419     blink::WebMediaConstraints constraints = MediaConstraintsImpl::create(mediaConstraints, exceptionState);
420     if (exceptionState.hadException())
421         return;
422
423     m_localStreams.append(stream);
424
425     bool valid = m_peerHandler->addStream(stream->descriptor(), constraints);
426     if (!valid)
427         exceptionState.throwDOMException(SyntaxError, "Unable to add the provided stream.");
428 }
429
430 void RTCPeerConnection::removeStream(PassRefPtr<MediaStream> prpStream, ExceptionState& exceptionState)
431 {
432     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
433         return;
434
435     if (!prpStream) {
436         exceptionState.throwDOMException(TypeMismatchError, ExceptionMessages::argumentNullOrIncorrectType(1, "MediaStream"));
437         return;
438     }
439
440     RefPtr<MediaStream> stream = prpStream;
441
442     size_t pos = m_localStreams.find(stream);
443     if (pos == kNotFound)
444         return;
445
446     m_localStreams.remove(pos);
447
448     m_peerHandler->removeStream(stream->descriptor());
449 }
450
451 MediaStreamVector RTCPeerConnection::getLocalStreams() const
452 {
453     return m_localStreams;
454 }
455
456 MediaStreamVector RTCPeerConnection::getRemoteStreams() const
457 {
458     return m_remoteStreams;
459 }
460
461 MediaStream* RTCPeerConnection::getStreamById(const String& streamId)
462 {
463     for (MediaStreamVector::iterator iter = m_localStreams.begin(); iter != m_localStreams.end(); ++iter) {
464         if ((*iter)->id() == streamId)
465             return iter->get();
466     }
467
468     for (MediaStreamVector::iterator iter = m_remoteStreams.begin(); iter != m_remoteStreams.end(); ++iter) {
469         if ((*iter)->id() == streamId)
470             return iter->get();
471     }
472
473     return 0;
474 }
475
476 void RTCPeerConnection::getStats(PassOwnPtr<RTCStatsCallback> successCallback, PassRefPtr<MediaStreamTrack> selector)
477 {
478     RefPtr<RTCStatsRequest> statsRequest = RTCStatsRequestImpl::create(executionContext(), successCallback, selector);
479     // FIXME: Add passing selector as part of the statsRequest.
480     m_peerHandler->getStats(statsRequest.release());
481 }
482
483 PassRefPtr<RTCDataChannel> RTCPeerConnection::createDataChannel(String label, const Dictionary& options, ExceptionState& exceptionState)
484 {
485     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
486         return nullptr;
487
488     blink::WebRTCDataChannelInit init;
489     options.get("ordered", init.ordered);
490     options.get("negotiated", init.negotiated);
491
492     unsigned short value = 0;
493     if (options.get("id", value))
494         init.id = value;
495     if (options.get("maxRetransmits", value))
496         init.maxRetransmits = value;
497     if (options.get("maxRetransmitTime", value))
498         init.maxRetransmitTime = value;
499
500     String protocolString;
501     options.get("protocol", protocolString);
502     init.protocol = protocolString;
503
504     RefPtr<RTCDataChannel> channel = RTCDataChannel::create(executionContext(), m_peerHandler.get(), label, init, exceptionState);
505     if (exceptionState.hadException())
506         return nullptr;
507     m_dataChannels.append(channel);
508     return channel.release();
509 }
510
511 bool RTCPeerConnection::hasLocalStreamWithTrackId(const String& trackId)
512 {
513     for (MediaStreamVector::iterator iter = m_localStreams.begin(); iter != m_localStreams.end(); ++iter) {
514         if ((*iter)->getTrackById(trackId))
515             return true;
516     }
517     return false;
518 }
519
520 PassRefPtr<RTCDTMFSender> RTCPeerConnection::createDTMFSender(PassRefPtr<MediaStreamTrack> prpTrack, ExceptionState& exceptionState)
521 {
522     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
523         return nullptr;
524
525     if (!prpTrack) {
526         exceptionState.throwTypeError(ExceptionMessages::argumentNullOrIncorrectType(1, "MediaStreamTrack"));
527         return nullptr;
528     }
529
530     RefPtr<MediaStreamTrack> track = prpTrack;
531
532     if (!hasLocalStreamWithTrackId(track->id())) {
533         exceptionState.throwDOMException(SyntaxError, "No local stream is available for the track provided.");
534         return nullptr;
535     }
536
537     RefPtr<RTCDTMFSender> dtmfSender = RTCDTMFSender::create(executionContext(), m_peerHandler.get(), track.release(), exceptionState);
538     if (exceptionState.hadException())
539         return nullptr;
540     return dtmfSender.release();
541 }
542
543 void RTCPeerConnection::close(ExceptionState& exceptionState)
544 {
545     if (throwExceptionIfSignalingStateClosed(m_signalingState, exceptionState))
546         return;
547
548     m_peerHandler->stop();
549
550     changeIceConnectionState(ICEConnectionStateClosed);
551     changeIceGatheringState(ICEGatheringStateComplete);
552     changeSignalingState(SignalingStateClosed);
553 }
554
555 void RTCPeerConnection::negotiationNeeded()
556 {
557     scheduleDispatchEvent(Event::create(EventTypeNames::negotiationneeded));
558 }
559
560 void RTCPeerConnection::didGenerateICECandidate(const blink::WebRTCICECandidate& webCandidate)
561 {
562     ASSERT(executionContext()->isContextThread());
563     if (webCandidate.isNull())
564         scheduleDispatchEvent(RTCIceCandidateEvent::create(false, false, nullptr));
565     else {
566         RefPtr<RTCIceCandidate> iceCandidate = RTCIceCandidate::create(webCandidate);
567         scheduleDispatchEvent(RTCIceCandidateEvent::create(false, false, iceCandidate.release()));
568     }
569 }
570
571 void RTCPeerConnection::didChangeSignalingState(SignalingState newState)
572 {
573     ASSERT(executionContext()->isContextThread());
574     changeSignalingState(newState);
575 }
576
577 void RTCPeerConnection::didChangeICEGatheringState(ICEGatheringState newState)
578 {
579     ASSERT(executionContext()->isContextThread());
580     changeIceGatheringState(newState);
581 }
582
583 void RTCPeerConnection::didChangeICEConnectionState(ICEConnectionState newState)
584 {
585     ASSERT(executionContext()->isContextThread());
586     changeIceConnectionState(newState);
587 }
588
589 void RTCPeerConnection::didAddRemoteStream(const blink::WebMediaStream& remoteStream)
590 {
591     ASSERT(executionContext()->isContextThread());
592
593     if (m_signalingState == SignalingStateClosed)
594         return;
595
596     RefPtr<MediaStream> stream = MediaStream::create(executionContext(), remoteStream);
597     m_remoteStreams.append(stream);
598
599     scheduleDispatchEvent(MediaStreamEvent::create(EventTypeNames::addstream, false, false, stream.release()));
600 }
601
602 void RTCPeerConnection::didRemoveRemoteStream(const blink::WebMediaStream& remoteStream)
603 {
604     ASSERT(executionContext()->isContextThread());
605
606     MediaStreamDescriptor* streamDescriptor = remoteStream;
607     ASSERT(streamDescriptor->client());
608
609     RefPtr<MediaStream> stream = static_cast<MediaStream*>(streamDescriptor->client());
610     stream->streamEnded();
611
612     if (m_signalingState == SignalingStateClosed)
613         return;
614
615     size_t pos = m_remoteStreams.find(stream);
616     ASSERT(pos != kNotFound);
617     m_remoteStreams.remove(pos);
618
619     scheduleDispatchEvent(MediaStreamEvent::create(EventTypeNames::removestream, false, false, stream.release()));
620 }
621
622 void RTCPeerConnection::didAddRemoteDataChannel(blink::WebRTCDataChannelHandler* handler)
623 {
624     ASSERT(executionContext()->isContextThread());
625
626     if (m_signalingState == SignalingStateClosed)
627         return;
628
629     RefPtr<RTCDataChannel> channel = RTCDataChannel::create(executionContext(), adoptPtr(handler));
630     m_dataChannels.append(channel);
631
632     scheduleDispatchEvent(RTCDataChannelEvent::create(EventTypeNames::datachannel, false, false, channel.release()));
633 }
634
635 const AtomicString& RTCPeerConnection::interfaceName() const
636 {
637     return EventTargetNames::RTCPeerConnection;
638 }
639
640 ExecutionContext* RTCPeerConnection::executionContext() const
641 {
642     return ActiveDOMObject::executionContext();
643 }
644
645 void RTCPeerConnection::suspend()
646 {
647     m_dispatchScheduledEventRunner.suspend();
648 }
649
650 void RTCPeerConnection::resume()
651 {
652     m_dispatchScheduledEventRunner.resume();
653 }
654
655 void RTCPeerConnection::stop()
656 {
657     if (m_stopped)
658         return;
659
660     m_stopped = true;
661     m_iceConnectionState = ICEConnectionStateClosed;
662     m_signalingState = SignalingStateClosed;
663
664     Vector<RefPtr<RTCDataChannel> >::iterator i = m_dataChannels.begin();
665     for (; i != m_dataChannels.end(); ++i)
666         (*i)->stop();
667
668     m_dispatchScheduledEventRunner.stop();
669 }
670
671 void RTCPeerConnection::changeSignalingState(SignalingState signalingState)
672 {
673     if (m_signalingState != SignalingStateClosed && m_signalingState != signalingState) {
674         m_signalingState = signalingState;
675         scheduleDispatchEvent(Event::create(EventTypeNames::signalingstatechange));
676     }
677 }
678
679 void RTCPeerConnection::changeIceGatheringState(ICEGatheringState iceGatheringState)
680 {
681     m_iceGatheringState = iceGatheringState;
682 }
683
684 void RTCPeerConnection::changeIceConnectionState(ICEConnectionState iceConnectionState)
685 {
686     if (m_iceConnectionState != ICEConnectionStateClosed && m_iceConnectionState != iceConnectionState) {
687         m_iceConnectionState = iceConnectionState;
688         scheduleDispatchEvent(Event::create(EventTypeNames::iceconnectionstatechange));
689     }
690 }
691
692 void RTCPeerConnection::scheduleDispatchEvent(PassRefPtrWillBeRawPtr<Event> event)
693 {
694     m_scheduledEvents.append(event);
695
696     m_dispatchScheduledEventRunner.runAsync();
697 }
698
699 void RTCPeerConnection::dispatchScheduledEvent()
700 {
701     if (m_stopped)
702         return;
703
704     WillBeHeapVector<RefPtrWillBeMember<Event> > events;
705     events.swap(m_scheduledEvents);
706
707     WillBeHeapVector<RefPtrWillBeMember<Event> >::iterator it = events.begin();
708     for (; it != events.end(); ++it)
709         dispatchEvent((*it).release());
710
711     events.clear();
712 }
713
714 } // namespace WebCore