05974705533a06ded736e87fe9e6806c2e8226b7
[WebKit-https.git] / Source / WebCore / Modules / mediastream / UserMediaRequest.cpp
1 /*
2  * Copyright (C) 2011 Ericsson AB. All rights reserved.
3  * Copyright (C) 2012 Google Inc. All rights reserved.
4  * Copyright (C) 2013 Apple Inc. All rights reserved.
5  * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies).
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer
15  *    in the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of Ericsson nor the names of its contributors
18  *    may be used to endorse or promote products derived from this
19  *    software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include "config.h"
35
36 #if ENABLE(MEDIA_STREAM)
37
38 #include "UserMediaRequest.h"
39
40 #include "Dictionary.h"
41 #include "Document.h"
42 #include "ExceptionCode.h"
43 #include "Frame.h"
44 #include "MediaConstraintsImpl.h"
45 #include "MediaStream.h"
46 #include "MediaStreamPrivate.h"
47 #include "NavigatorUserMediaErrorCallback.h"
48 #include "NavigatorUserMediaSuccessCallback.h"
49 #include "RealtimeMediaSourceCenter.h"
50 #include "SecurityOrigin.h"
51 #include "UserMediaController.h"
52 #include <wtf/MainThread.h>
53
54 namespace WebCore {
55
56 static PassRefPtr<MediaConstraints> parseOptions(const Dictionary& options, const String& mediaType, ExceptionCode& ec)
57 {
58     RefPtr<MediaConstraints> constraints;
59
60     Dictionary constraintsDictionary;
61     bool ok = options.get(mediaType, constraintsDictionary);
62     if (ok && !constraintsDictionary.isUndefinedOrNull())
63         constraints = MediaConstraintsImpl::create(constraintsDictionary, ec);
64     else {
65         bool mediaRequested = false;
66         options.get(mediaType, mediaRequested);
67         if (mediaRequested)
68             constraints = MediaConstraintsImpl::create();
69     }
70
71     return constraints.release();
72 }
73
74 RefPtr<UserMediaRequest> UserMediaRequest::create(ScriptExecutionContext* context, UserMediaController* controller, const Dictionary& options, PassRefPtr<NavigatorUserMediaSuccessCallback> successCallback, PassRefPtr<NavigatorUserMediaErrorCallback> errorCallback, ExceptionCode& ec)
75 {
76     ASSERT(successCallback);
77
78     auto resolveCallback = [successCallback, context](MediaStream& stream) mutable {
79         ASSERT(context);
80
81         RefPtr<MediaStream> mediaStream = &stream;
82         context->postTask([successCallback, mediaStream](ScriptExecutionContext&) {
83             successCallback->handleEvent(mediaStream.get());
84         });
85     };
86     auto rejectCallback = [errorCallback, context](NavigatorUserMediaError& error) mutable {
87         ASSERT(context);
88
89         if (errorCallback) {
90             RefPtr<NavigatorUserMediaError> eventError = &error;
91             context->postTask([errorCallback, eventError](ScriptExecutionContext&) {
92                 errorCallback->handleEvent(eventError.get());
93             });
94         }
95     };
96
97     return UserMediaRequest::create(context, controller, options, WTF::move(resolveCallback), WTF::move(rejectCallback), ec);
98 }
99
100 RefPtr<UserMediaRequest> UserMediaRequest::create(ScriptExecutionContext* context, UserMediaController* controller, const Dictionary& options, MediaDevices::ResolveCallback&& resolveCallback, MediaDevices::RejectCallback&& rejectCallback, ExceptionCode& ec)
101 {
102     ASSERT(resolveCallback && rejectCallback);
103
104     RefPtr<MediaConstraints> audioConstraints = parseOptions(options, AtomicString("audio", AtomicString::ConstructFromLiteral), ec);
105     if (ec)
106         return nullptr;
107
108     RefPtr<MediaConstraints> videoConstraints = parseOptions(options, AtomicString("video", AtomicString::ConstructFromLiteral), ec);
109     if (ec)
110         return nullptr;
111
112     if (!audioConstraints && !videoConstraints)
113         return nullptr;
114
115     return adoptRef(*new UserMediaRequest(context, controller, audioConstraints.release(), videoConstraints.release(), WTF::move(resolveCallback), WTF::move(rejectCallback)));
116 }
117
118 UserMediaRequest::UserMediaRequest(ScriptExecutionContext* context, UserMediaController* controller, PassRefPtr<MediaConstraints> audioConstraints, PassRefPtr<MediaConstraints> videoConstraints, MediaDevices::ResolveCallback&& resolveCallback, MediaDevices::RejectCallback&& rejectCallback)
119     : ContextDestructionObserver(context)
120     , m_audioConstraints(audioConstraints)
121     , m_videoConstraints(videoConstraints)
122     , m_controller(controller)
123     , m_resolveCallback(WTF::move(resolveCallback))
124     , m_rejectCallback(WTF::move(rejectCallback))
125 {
126 }
127
128 UserMediaRequest::~UserMediaRequest()
129 {
130 }
131
132 SecurityOrigin* UserMediaRequest::securityOrigin() const
133 {
134     if (m_scriptExecutionContext)
135         return m_scriptExecutionContext->securityOrigin();
136
137     return nullptr;
138 }
139     
140 void UserMediaRequest::start()
141 {
142     // 1 - make sure the system is capable of supporting the audio and video constraints. We don't want to ask for
143     // user permission if the constraints can not be suported.
144     RealtimeMediaSourceCenter::singleton().validateRequestConstraints(this, m_audioConstraints, m_videoConstraints);
145 }
146
147     
148 void UserMediaRequest::constraintsValidated()
149 {
150     RefPtr<UserMediaRequest> protectedThis(this);
151     callOnMainThread([protectedThis] {
152         // 2 - The constraints are valid, ask the user for access to media.
153         if (UserMediaController* controller = protectedThis->m_controller)
154             controller->requestPermission(*protectedThis.get());
155     });
156 }
157
158 void UserMediaRequest::userMediaAccessGranted()
159 {
160     RefPtr<UserMediaRequest> protectedThis(this);
161     callOnMainThread([protectedThis] {
162         // 3 - the user granted access, ask platform to create the media stream descriptors.
163         RealtimeMediaSourceCenter::singleton().createMediaStream(protectedThis.get(), protectedThis->m_audioConstraints, protectedThis->m_videoConstraints);
164     });
165 }
166
167 void UserMediaRequest::userMediaAccessDenied()
168 {
169     failedToCreateStreamWithPermissionError();
170 }
171
172 void UserMediaRequest::constraintsInvalid(const String& constraintName)
173 {
174     failedToCreateStreamWithConstraintsError(constraintName);
175 }
176
177 void UserMediaRequest::didCreateStream(PassRefPtr<MediaStreamPrivate> privateStream)
178 {
179     if (!m_scriptExecutionContext)
180         return;
181
182     // 4 - Create the MediaStream and pass it to the success callback.
183     RefPtr<MediaStream> stream = MediaStream::create(*m_scriptExecutionContext, privateStream);
184     for (auto& track : stream->getAudioTracks())
185         track->applyConstraints(m_audioConstraints);
186     for (auto& track : stream->getVideoTracks())
187         track->applyConstraints(m_videoConstraints);
188
189     m_resolveCallback(*stream);
190 }
191
192 void UserMediaRequest::failedToCreateStreamWithConstraintsError(const String& constraintName)
193 {
194     ASSERT(!constraintName.isEmpty());
195     if (!m_scriptExecutionContext)
196         return;
197
198     m_rejectCallback(NavigatorUserMediaError::create(NavigatorUserMediaError::constraintNotSatisfiedErrorName(), constraintName).get());
199 }
200
201 void UserMediaRequest::failedToCreateStreamWithPermissionError()
202 {
203     if (!m_scriptExecutionContext)
204         return;
205
206     // FIXME: Replace NavigatorUserMediaError with MediaStreamError (see bug 143335)
207     m_rejectCallback(NavigatorUserMediaError::create(NavigatorUserMediaError::permissionDeniedErrorName(), emptyString()));
208 }
209
210 void UserMediaRequest::contextDestroyed()
211 {
212     Ref<UserMediaRequest> protect(*this);
213
214     if (m_controller) {
215         m_controller->cancelRequest(*this);
216         m_controller = nullptr;
217     }
218
219     ContextDestructionObserver::contextDestroyed();
220 }
221
222 } // namespace WebCore
223
224 #endif // ENABLE(MEDIA_STREAM)