2 * Copyright (C) 2015 Ericsson AB. All rights reserved.
3 * Copyright (C) 2015-2019 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
15 * 3. Neither the name of Ericsson nor the names of its contributors
16 * may be used to endorse or promote products derived from this
17 * software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "MediaDevices.h"
35 #if ENABLE(MEDIA_STREAM)
39 #include "EventNames.h"
40 #include "JSDOMPromiseDeferred.h"
41 #include "JSMediaDeviceInfo.h"
42 #include "MediaTrackSupportedConstraints.h"
43 #include "RealtimeMediaSourceSettings.h"
44 #include "UserMediaController.h"
45 #include "UserMediaRequest.h"
46 #include <wtf/IsoMallocInlines.h>
47 #include <wtf/RandomNumber.h>
51 WTF_MAKE_ISO_ALLOCATED_IMPL(MediaDevices);
53 inline MediaDevices::MediaDevices(Document& document)
54 : ActiveDOMObject(document)
55 , m_scheduledEventTimer(*this, &MediaDevices::scheduledEventTimerFired)
56 , m_eventNames(eventNames())
60 static_assert(static_cast<size_t>(MediaDevices::DisplayCaptureSurfaceType::Monitor) == static_cast<size_t>(RealtimeMediaSourceSettings::DisplaySurfaceType::Monitor), "MediaDevices::DisplayCaptureSurfaceType::Monitor is not equal to RealtimeMediaSourceSettings::DisplaySurfaceType::Monitor as expected");
61 static_assert(static_cast<size_t>(MediaDevices::DisplayCaptureSurfaceType::Window) == static_cast<size_t>(RealtimeMediaSourceSettings::DisplaySurfaceType::Window), "MediaDevices::DisplayCaptureSurfaceType::Window is not RealtimeMediaSourceSettings::DisplaySurfaceType::Window as expected");
62 static_assert(static_cast<size_t>(MediaDevices::DisplayCaptureSurfaceType::Application) == static_cast<size_t>(RealtimeMediaSourceSettings::DisplaySurfaceType::Application), "MediaDevices::DisplayCaptureSurfaceType::Application is not RealtimeMediaSourceSettings::DisplaySurfaceType::Application as expected");
63 static_assert(static_cast<size_t>(MediaDevices::DisplayCaptureSurfaceType::Browser) == static_cast<size_t>(RealtimeMediaSourceSettings::DisplaySurfaceType::Browser), "MediaDevices::DisplayCaptureSurfaceType::Browser is not RealtimeMediaSourceSettings::DisplaySurfaceType::Browser as expected");
65 if (auto* controller = UserMediaController::from(document.page())) {
66 m_canAccessCamera = controller->canCallGetUserMedia(document, { UserMediaController::CaptureType::Camera }) == UserMediaController::GetUserMediaAccess::CanCall;
67 m_canAccessMicrophone = controller->canCallGetUserMedia(document, { UserMediaController::CaptureType::Microphone }) == UserMediaController::GetUserMediaAccess::CanCall;
71 MediaDevices::~MediaDevices() = default;
73 void MediaDevices::stop()
75 if (m_deviceChangeToken) {
76 auto* controller = UserMediaController::from(document()->page());
77 controller->removeDeviceChangeObserver(m_deviceChangeToken);
80 m_scheduledEventTimer.stop();
83 Ref<MediaDevices> MediaDevices::create(Document& document)
85 return adoptRef(*new MediaDevices(document));
88 Document* MediaDevices::document() const
90 return downcast<Document>(scriptExecutionContext());
93 static MediaConstraints createMediaConstraints(const Variant<bool, MediaTrackConstraints>& constraints)
95 return WTF::switchOn(constraints,
97 MediaConstraints constraints;
98 constraints.isValid = isValid;
101 [&] (const MediaTrackConstraints& trackConstraints) {
102 return createMediaConstraints(trackConstraints);
107 void MediaDevices::getUserMedia(const StreamConstraints& constraints, Promise&& promise) const
109 auto* document = this->document();
110 if (!document || !document->isFullyActive()) {
111 promise.reject(Exception { InvalidStateError, "Document is not fully active"_s });
115 auto audioConstraints = createMediaConstraints(constraints.audio);
116 auto videoConstraints = createMediaConstraints(constraints.video);
117 if (videoConstraints.isValid)
118 videoConstraints.setDefaultVideoConstraints();
120 auto request = UserMediaRequest::create(*document, { MediaStreamRequest::Type::UserMedia, WTFMove(audioConstraints), WTFMove(videoConstraints) }, WTFMove(promise));
124 void MediaDevices::getDisplayMedia(const StreamConstraints& constraints, Promise&& promise) const
126 auto* document = this->document();
130 if (!m_disableGetDisplayMediaUserGestureConstraint && !UserGestureIndicator::processingUserGesture()) {
131 promise.reject(Exception { InvalidAccessError, "getDisplayMedia must be called from a user gesture handler."_s });
135 auto request = UserMediaRequest::create(*document, { MediaStreamRequest::Type::DisplayMedia, { }, createMediaConstraints(constraints.video) }, WTFMove(promise));
139 void MediaDevices::refreshDevices(const Vector<CaptureDevice>& newDevices)
141 Vector<Ref<MediaDeviceInfo>> devices;
142 for (auto& newDevice : newDevices) {
143 if (!m_canAccessMicrophone && newDevice.type() == CaptureDevice::DeviceType::Microphone)
145 if (!m_canAccessCamera && newDevice.type() == CaptureDevice::DeviceType::Camera)
148 auto index = m_devices.findMatching([&newDevice](auto& oldDevice) {
149 return oldDevice->deviceId() == newDevice.persistentId();
151 if (index != notFound) {
152 devices.append(m_devices[index].copyRef());
156 auto deviceType = newDevice.type() == CaptureDevice::DeviceType::Microphone ? MediaDeviceInfo::Kind::Audioinput : MediaDeviceInfo::Kind::Videoinput;
157 devices.append(MediaDeviceInfo::create(newDevice.label(), newDevice.persistentId(), newDevice.groupId(), deviceType));
159 m_devices = WTFMove(devices);
162 void MediaDevices::enumerateDevices(EnumerateDevicesPromise&& promise)
164 auto* document = this->document();
168 auto* controller = UserMediaController::from(document->page());
170 promise.resolve({ });
173 if (!m_canAccessCamera && !m_canAccessMicrophone) {
174 controller->logGetUserMediaDenial(*document, UserMediaController::GetUserMediaAccess::BlockedByFeaturePolicy, UserMediaController::BlockedCaller::EnumerateDevices);
175 promise.resolve({ });
179 controller->enumerateMediaDevices(*document, [this, weakThis = makeWeakPtr(this), promise = WTFMove(promise)](const auto& newDevices, const auto& deviceIDHashSalt) mutable {
180 if (!weakThis || isContextStopped())
183 this->document()->setDeviceIDHashSalt(deviceIDHashSalt);
184 refreshDevices(newDevices);
185 promise.resolve(m_devices);
189 MediaTrackSupportedConstraints MediaDevices::getSupportedConstraints()
191 auto& supported = RealtimeMediaSourceCenter::singleton().supportedConstraints();
192 MediaTrackSupportedConstraints result;
193 result.width = supported.supportsWidth();
194 result.height = supported.supportsHeight();
195 result.aspectRatio = supported.supportsAspectRatio();
196 result.frameRate = supported.supportsFrameRate();
197 result.facingMode = supported.supportsFacingMode();
198 result.volume = supported.supportsVolume();
199 result.sampleRate = supported.supportsSampleRate();
200 result.sampleSize = supported.supportsSampleSize();
201 result.echoCancellation = supported.supportsEchoCancellation();
202 result.deviceId = supported.supportsDeviceId();
203 result.groupId = supported.supportsGroupId();
208 void MediaDevices::scheduledEventTimerFired()
210 ASSERT(!isContextStopped());
211 dispatchEvent(Event::create(eventNames().devicechangeEvent, Event::CanBubble::No, Event::IsCancelable::No));
214 bool MediaDevices::hasPendingActivity() const
216 return !isContextStopped() && hasEventListeners(m_eventNames.devicechangeEvent);
219 const char* MediaDevices::activeDOMObjectName() const
221 return "MediaDevices";
224 void MediaDevices::listenForDeviceChanges()
226 if (m_listeningForDeviceChanges || (!m_canAccessCamera && !m_canAccessMicrophone))
229 m_listeningForDeviceChanges = true;
231 auto* document = this->document();
232 auto* controller = document ? UserMediaController::from(document->page()) : nullptr;
236 m_deviceChangeToken = controller->addDeviceChangeObserver([weakThis = makeWeakPtr(*this), this]() {
237 if (!weakThis || isContextStopped() || m_scheduledEventTimer.isActive())
240 m_scheduledEventTimer.startOneShot(Seconds(randomNumber() / 2));
244 bool MediaDevices::addEventListener(const AtomString& eventType, Ref<EventListener>&& listener, const AddEventListenerOptions& options)
246 if (eventType == eventNames().devicechangeEvent)
247 listenForDeviceChanges();
249 return EventTargetWithInlineData::addEventListener(eventType, WTFMove(listener), options);
252 } // namespace WebCore
254 #endif // ENABLE(MEDIA_STREAM)