2 * Copyright (C) 2011 Ericsson AB. All rights reserved.
3 * Copyright (C) 2012 Google Inc. All rights reserved.
4 * Copyright (C) 2013-2018 Apple Inc. All rights reserved.
5 * Copyright (C) 2013 Nokia Corporation and/or its subsidiary(-ies).
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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.
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.
35 #include "UserMediaRequest.h"
37 #if ENABLE(MEDIA_STREAM)
41 #include "JSMediaStream.h"
42 #include "JSOverconstrainedError.h"
44 #include "MediaConstraints.h"
45 #include "RealtimeMediaSourceCenter.h"
46 #include "SchemeRegistry.h"
48 #include "UserMediaController.h"
52 RefPtr<UserMediaRequest> UserMediaRequest::create(Document& document, MediaStreamRequest&& request, DOMPromiseDeferred<IDLInterface<MediaStream>>&& promise)
54 auto result = adoptRef(new UserMediaRequest(document, WTFMove(request), WTFMove(promise)));
55 result->suspendIfNeeded();
59 UserMediaRequest::UserMediaRequest(Document& document, MediaStreamRequest&& request, DOMPromiseDeferred<IDLInterface<MediaStream>>&& promise)
60 : ActiveDOMObject(&document)
61 , m_promise(WTFMove(promise))
62 , m_request(WTFMove(request))
66 UserMediaRequest::~UserMediaRequest() = default;
68 SecurityOrigin* UserMediaRequest::userMediaDocumentOrigin() const
70 if (!m_scriptExecutionContext)
72 return m_scriptExecutionContext->securityOrigin();
75 SecurityOrigin* UserMediaRequest::topLevelDocumentOrigin() const
77 if (!m_scriptExecutionContext)
79 return &m_scriptExecutionContext->topOrigin();
82 static bool hasInvalidGetDisplayMediaConstraint(const MediaConstraints& constraints)
84 // https://w3c.github.io/mediacapture-screen-share/#navigator-additions
85 // 1. Let constraints be the method's first argument.
86 // 2. For each member present in constraints whose value, value, is a dictionary, run the following steps:
87 // 1. If value contains a member named advanced, return a promise rejected with a newly created TypeError.
88 // 2. If value contains a member which in turn is a dictionary containing a member named either min or
89 // exact, return a promise rejected with a newly created TypeError.
90 if (!constraints.isValid)
93 if (!constraints.advancedConstraints.isEmpty())
97 constraints.mandatoryConstraints.filter([&invalid] (const MediaConstraint& constraint) mutable {
98 switch (constraint.constraintType()) {
99 case MediaConstraintType::Width:
100 case MediaConstraintType::Height: {
101 auto& intConstraint = downcast<IntConstraint>(constraint);
103 invalid = intConstraint.getExact(value) || intConstraint.getMin(value);
107 case MediaConstraintType::AspectRatio:
108 case MediaConstraintType::FrameRate: {
109 auto& doubleConstraint = downcast<DoubleConstraint>(constraint);
111 invalid = doubleConstraint.getExact(value) || doubleConstraint.getMin(value);
115 case MediaConstraintType::DisplaySurface:
116 case MediaConstraintType::LogicalSurface: {
117 auto& boolConstraint = downcast<BooleanConstraint>(constraint);
119 invalid = boolConstraint.getExact(value);
123 case MediaConstraintType::FacingMode:
124 case MediaConstraintType::DeviceId:
125 case MediaConstraintType::GroupId: {
126 auto& stringConstraint = downcast<StringConstraint>(constraint);
127 Vector<String> values;
128 invalid = stringConstraint.getExact(values);
132 case MediaConstraintType::SampleRate:
133 case MediaConstraintType::SampleSize:
134 case MediaConstraintType::Volume:
135 case MediaConstraintType::EchoCancellation:
139 case MediaConstraintType::Unknown:
140 ASSERT_NOT_REACHED();
150 void UserMediaRequest::start()
152 ASSERT(m_scriptExecutionContext);
153 if (!m_scriptExecutionContext) {
154 deny(MediaAccessDenialReason::UserMediaDisabled);
158 if (m_request.type == MediaStreamRequest::Type::DisplayMedia) {
159 if (hasInvalidGetDisplayMediaConstraint(m_request.videoConstraints)) {
160 deny(MediaAccessDenialReason::IllegalConstraint);
165 // https://w3c.github.io/mediacapture-main/getusermedia.html#dom-mediadevices-getusermedia()
166 // 1. Let constraints be the method's first argument.
167 // 2. Let requestedMediaTypes be the set of media types in constraints with either a dictionary
168 // value or a value of "true".
169 // 3. If requestedMediaTypes is the empty set, return a promise rejected with a TypeError. The word
170 // "optional" occurs in the WebIDL due to WebIDL rules, but the argument must be supplied in order
171 // for the call to succeed.
172 if (!m_request.audioConstraints.isValid && !m_request.videoConstraints.isValid) {
173 deny(MediaAccessDenialReason::NoConstraints);
177 // 4. If the current settings object's responsible document is NOT allowed to use the feature indicated by
178 // attribute name allowusermedia, return a promise rejected with a DOMException object whose name
179 // attribute has the value SecurityError.
180 auto& document = downcast<Document>(*m_scriptExecutionContext);
181 auto* controller = UserMediaController::from(document.page());
183 deny(MediaAccessDenialReason::UserMediaDisabled);
187 // 6.3 Optionally, e.g., based on a previously-established user preference, for security reasons,
188 // or due to platform limitations, jump to the step labeled Permission Failure below.
190 // 6.10 Permission Failure: Reject p with a new DOMException object whose name attribute has
191 // the value NotAllowedError.
193 OptionSet<UserMediaController::CaptureType> types;
194 UserMediaController::BlockedCaller caller;
195 if (m_request.type == MediaStreamRequest::Type::DisplayMedia) {
196 types.add(UserMediaController::CaptureType::Display);
197 caller = UserMediaController::BlockedCaller::GetDisplayMedia;
199 if (m_request.audioConstraints.isValid)
200 types.add(UserMediaController::CaptureType::Microphone);
201 if (m_request.videoConstraints.isValid)
202 types.add(UserMediaController::CaptureType::Camera);
203 caller = UserMediaController::BlockedCaller::GetUserMedia;
205 auto access = controller->canCallGetUserMedia(document, types);
206 if (access != UserMediaController::GetUserMediaAccess::CanCall) {
207 deny(MediaAccessDenialReason::PermissionDenied);
208 controller->logGetUserMediaDenial(document, access, caller);
212 controller->requestUserMediaAccess(*this);
215 void UserMediaRequest::allow(CaptureDevice&& audioDevice, CaptureDevice&& videoDevice, String&& deviceIdentifierHashSalt)
217 RELEASE_LOG(MediaStream, "UserMediaRequest::allow %s %s", audioDevice ? audioDevice.persistentId().utf8().data() : "", videoDevice ? videoDevice.persistentId().utf8().data() : "");
219 auto callback = [this, protector = makePendingActivity(*this)](RefPtr<MediaStreamPrivate>&& privateStream) mutable {
220 if (!m_scriptExecutionContext)
223 if (!privateStream) {
224 RELEASE_LOG(MediaStream, "UserMediaRequest::allow failed to create media stream!");
225 deny(MediaAccessDenialReason::HardwareError);
228 privateStream->monitorOrientation(downcast<Document>(m_scriptExecutionContext)->orientationNotifier());
230 auto stream = MediaStream::create(*m_scriptExecutionContext, privateStream.releaseNonNull());
231 if (stream->getTracks().isEmpty()) {
232 deny(MediaAccessDenialReason::HardwareError);
236 m_pendingActivationMediaStream = PendingActivationMediaStream::create(WTFMove(protector), *this, WTFMove(stream));
239 auto& document = downcast<Document>(*scriptExecutionContext());
240 document.setDeviceIDHashSalt(deviceIdentifierHashSalt);
242 RealtimeMediaSourceCenter::singleton().createMediaStream(WTFMove(callback), WTFMove(deviceIdentifierHashSalt), WTFMove(audioDevice), WTFMove(videoDevice), m_request);
244 if (!m_scriptExecutionContext)
248 if (auto* page = document.page())
249 page->rtcController().disableICECandidateFilteringForDocument(document);
253 void UserMediaRequest::deny(MediaAccessDenialReason reason, const String& message)
255 if (!m_scriptExecutionContext)
260 case MediaAccessDenialReason::IllegalConstraint:
261 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - invalid constraints");
264 case MediaAccessDenialReason::NoConstraints:
265 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - no constraints");
268 case MediaAccessDenialReason::UserMediaDisabled:
269 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - user media disabled");
270 code = SecurityError;
272 case MediaAccessDenialReason::NoCaptureDevices:
273 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - no capture devices");
274 code = NotFoundError;
276 case MediaAccessDenialReason::InvalidConstraint:
277 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - invalid constraint - %s", message.utf8().data());
278 m_promise.rejectType<IDLInterface<OverconstrainedError>>(OverconstrainedError::create(message, "Invalid constraint"_s).get());
280 case MediaAccessDenialReason::HardwareError:
281 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - hardware error");
282 code = NotReadableError;
284 case MediaAccessDenialReason::OtherFailure:
285 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - other failure");
288 case MediaAccessDenialReason::PermissionDenied:
289 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - permission denied");
290 code = NotAllowedError;
292 case MediaAccessDenialReason::InvalidAccess:
293 RELEASE_LOG(MediaStream, "UserMediaRequest::deny - invalid access");
294 code = InvalidAccessError;
298 if (!message.isEmpty())
299 m_promise.reject(code, message);
301 m_promise.reject(code);
304 void UserMediaRequest::stop()
306 // Protecting 'this' since nulling m_pendingActivationMediaStream might destroy it.
307 Ref<UserMediaRequest> protectedThis(*this);
309 m_pendingActivationMediaStream = nullptr;
311 auto& document = downcast<Document>(*m_scriptExecutionContext);
312 if (auto* controller = UserMediaController::from(document.page()))
313 controller->cancelUserMediaAccessRequest(*this);
316 const char* UserMediaRequest::activeDOMObjectName() const
318 return "UserMediaRequest";
321 bool UserMediaRequest::canSuspendForDocumentSuspension() const
323 return !hasPendingActivity();
326 Document* UserMediaRequest::document() const
328 return downcast<Document>(m_scriptExecutionContext);
331 UserMediaRequest::PendingActivationMediaStream::PendingActivationMediaStream(Ref<PendingActivity<UserMediaRequest>>&& protectingUserMediaRequest, UserMediaRequest& userMediaRequest, Ref<MediaStream>&& stream)
332 : m_protectingUserMediaRequest(WTFMove(protectingUserMediaRequest))
333 , m_userMediaRequest(userMediaRequest)
334 , m_mediaStream(WTFMove(stream))
336 m_mediaStream->privateStream().addObserver(*this);
337 m_mediaStream->startProducingData();
340 UserMediaRequest::PendingActivationMediaStream::~PendingActivationMediaStream()
342 m_mediaStream->privateStream().removeObserver(*this);
345 void UserMediaRequest::PendingActivationMediaStream::characteristicsChanged()
347 if (!m_userMediaRequest.m_pendingActivationMediaStream)
350 for (auto& track : m_mediaStream->privateStream().tracks()) {
351 if (track->source().captureDidFail()) {
352 m_userMediaRequest.mediaStreamDidFail(track->source().type());
357 if (m_mediaStream->privateStream().hasVideo() || m_mediaStream->privateStream().hasAudio()) {
358 m_userMediaRequest.mediaStreamIsReady(WTFMove(m_mediaStream));
363 void UserMediaRequest::mediaStreamIsReady(Ref<MediaStream>&& stream)
365 RELEASE_LOG(MediaStream, "UserMediaRequest::mediaStreamIsReady");
366 stream->document()->setHasCaptureMediaStreamTrack();
367 m_promise.resolve(WTFMove(stream));
368 // We are in an observer iterator loop, we do not want to change the observers within this loop.
369 callOnMainThread([stream = WTFMove(m_pendingActivationMediaStream)] { });
372 void UserMediaRequest::mediaStreamDidFail(RealtimeMediaSource::Type type)
374 RELEASE_LOG(MediaStream, "UserMediaRequest::mediaStreamDidFail");
375 const char* typeDescription = "";
377 case RealtimeMediaSource::Type::Audio:
378 typeDescription = "audio";
380 case RealtimeMediaSource::Type::Video:
381 typeDescription = "video";
383 case RealtimeMediaSource::Type::None:
384 typeDescription = "unknown";
387 m_promise.reject(NotReadableError, makeString("Failed starting capture of a "_s, typeDescription, " track"_s));
388 // We are in an observer iterator loop, we do not want to change the observers within this loop.
389 callOnMainThread([stream = WTFMove(m_pendingActivationMediaStream)] { });
392 } // namespace WebCore
394 #endif // ENABLE(MEDIA_STREAM)