Deprecate ActiveDOMObject::canSuspendForDocumentSuspension()
[WebKit-https.git] / Source / WebCore / Modules / mediastream / MediaDevices.cpp
1 /*
2  * Copyright (C) 2015 Ericsson AB. All rights reserved.
3  * Copyright (C) 2015-2019 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
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
14  *    distribution.
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.
18  *
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.
30  */
31
32 #include "config.h"
33 #include "MediaDevices.h"
34
35 #if ENABLE(MEDIA_STREAM)
36
37 #include "Document.h"
38 #include "Event.h"
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>
48
49 namespace WebCore {
50
51 WTF_MAKE_ISO_ALLOCATED_IMPL(MediaDevices);
52
53 inline MediaDevices::MediaDevices(Document& document)
54     : ActiveDOMObject(document)
55     , m_scheduledEventTimer(*this, &MediaDevices::scheduledEventTimerFired)
56     , m_eventNames(eventNames())
57 {
58     suspendIfNeeded();
59
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");
64
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;
68     }
69 }
70
71 MediaDevices::~MediaDevices() = default;
72
73 void MediaDevices::stop()
74 {
75     if (m_deviceChangeToken) {
76         auto* controller = UserMediaController::from(document()->page());
77         controller->removeDeviceChangeObserver(m_deviceChangeToken);
78     }
79     m_devices.clear();
80     m_scheduledEventTimer.stop();
81 }
82
83 Ref<MediaDevices> MediaDevices::create(Document& document)
84 {
85     return adoptRef(*new MediaDevices(document));
86 }
87
88 Document* MediaDevices::document() const
89 {
90     return downcast<Document>(scriptExecutionContext());
91 }
92
93 static MediaConstraints createMediaConstraints(const Variant<bool, MediaTrackConstraints>& constraints)
94 {
95     return WTF::switchOn(constraints,
96         [&] (bool isValid) {
97             MediaConstraints constraints;
98             constraints.isValid = isValid;
99             return constraints;
100         },
101         [&] (const MediaTrackConstraints& trackConstraints) {
102             return createMediaConstraints(trackConstraints);
103         }
104     );
105 }
106
107 void MediaDevices::getUserMedia(const StreamConstraints& constraints, Promise&& promise) const
108 {
109     auto* document = this->document();
110     if (!document)
111         return;
112
113     auto audioConstraints = createMediaConstraints(constraints.audio);
114     auto videoConstraints = createMediaConstraints(constraints.video);
115     if (videoConstraints.isValid)
116         videoConstraints.setDefaultVideoConstraints();
117
118     auto request = UserMediaRequest::create(*document, { MediaStreamRequest::Type::UserMedia, WTFMove(audioConstraints), WTFMove(videoConstraints) }, WTFMove(promise));
119     request->start();
120 }
121
122 void MediaDevices::getDisplayMedia(const StreamConstraints& constraints, Promise&& promise) const
123 {
124     auto* document = this->document();
125     if (!document)
126         return;
127
128     if (!m_disableGetDisplayMediaUserGestureConstraint && !UserGestureIndicator::processingUserGesture()) {
129         promise.reject(Exception { InvalidAccessError, "getDisplayMedia must be called from a user gesture handler."_s });
130         return;
131     }
132
133     auto request = UserMediaRequest::create(*document, { MediaStreamRequest::Type::DisplayMedia, { }, createMediaConstraints(constraints.video) }, WTFMove(promise));
134     request->start();
135 }
136
137 void MediaDevices::refreshDevices(const Vector<CaptureDevice>& newDevices)
138 {
139     Vector<Ref<MediaDeviceInfo>> devices;
140     for (auto& newDevice : newDevices) {
141         if (!m_canAccessMicrophone && newDevice.type() == CaptureDevice::DeviceType::Microphone)
142             continue;
143         if (!m_canAccessCamera && newDevice.type() == CaptureDevice::DeviceType::Camera)
144             continue;
145
146         auto index = m_devices.findMatching([&newDevice](auto& oldDevice) {
147             return oldDevice->deviceId() == newDevice.persistentId();
148         });
149         if (index != notFound) {
150             devices.append(m_devices[index].copyRef());
151             continue;
152         }
153
154         auto deviceType = newDevice.type() == CaptureDevice::DeviceType::Microphone ? MediaDeviceInfo::Kind::Audioinput : MediaDeviceInfo::Kind::Videoinput;
155         devices.append(MediaDeviceInfo::create(newDevice.label(), newDevice.persistentId(), newDevice.groupId(), deviceType));
156     }
157     m_devices = WTFMove(devices);
158 }
159
160 void MediaDevices::enumerateDevices(EnumerateDevicesPromise&& promise)
161 {
162     auto* document = this->document();
163     if (!document)
164         return;
165
166     auto* controller = UserMediaController::from(document->page());
167     if (!controller) {
168         promise.resolve({ });
169         return;
170     }
171     if (!m_canAccessCamera && !m_canAccessMicrophone) {
172         controller->logGetUserMediaDenial(*document, UserMediaController::GetUserMediaAccess::BlockedByFeaturePolicy, UserMediaController::BlockedCaller::EnumerateDevices);
173         promise.resolve({ });
174         return;
175     }
176
177     controller->enumerateMediaDevices(*document, [this, weakThis = makeWeakPtr(this), promise = WTFMove(promise)](const auto& newDevices, const auto& deviceIDHashSalt) mutable {
178         if (!weakThis || isContextStopped())
179             return;
180
181         this->document()->setDeviceIDHashSalt(deviceIDHashSalt);
182         refreshDevices(newDevices);
183         promise.resolve(m_devices);
184     });
185 }
186
187 MediaTrackSupportedConstraints MediaDevices::getSupportedConstraints()
188 {
189     auto& supported = RealtimeMediaSourceCenter::singleton().supportedConstraints();
190     MediaTrackSupportedConstraints result;
191     result.width = supported.supportsWidth();
192     result.height = supported.supportsHeight();
193     result.aspectRatio = supported.supportsAspectRatio();
194     result.frameRate = supported.supportsFrameRate();
195     result.facingMode = supported.supportsFacingMode();
196     result.volume = supported.supportsVolume();
197     result.sampleRate = supported.supportsSampleRate();
198     result.sampleSize = supported.supportsSampleSize();
199     result.echoCancellation = supported.supportsEchoCancellation();
200     result.deviceId = supported.supportsDeviceId();
201     result.groupId = supported.supportsGroupId();
202
203     return result;
204 }
205
206 void MediaDevices::scheduledEventTimerFired()
207 {
208     ASSERT(!isContextStopped());
209     dispatchEvent(Event::create(eventNames().devicechangeEvent, Event::CanBubble::No, Event::IsCancelable::No));
210 }
211
212 bool MediaDevices::hasPendingActivity() const
213 {
214     return !isContextStopped() && hasEventListeners(m_eventNames.devicechangeEvent);
215 }
216
217 const char* MediaDevices::activeDOMObjectName() const
218 {
219     return "MediaDevices";
220 }
221
222 void MediaDevices::listenForDeviceChanges()
223 {
224     if (m_listeningForDeviceChanges || (!m_canAccessCamera && !m_canAccessMicrophone))
225         return;
226
227     m_listeningForDeviceChanges = true;
228
229     auto* document = this->document();
230     auto* controller = document ? UserMediaController::from(document->page()) : nullptr;
231     if (!controller)
232         return;
233
234     m_deviceChangeToken = controller->addDeviceChangeObserver([weakThis = makeWeakPtr(*this), this]() {
235         if (!weakThis || isContextStopped() || m_scheduledEventTimer.isActive())
236             return;
237
238         m_scheduledEventTimer.startOneShot(Seconds(randomNumber() / 2));
239     });
240 }
241
242 bool MediaDevices::addEventListener(const AtomString& eventType, Ref<EventListener>&& listener, const AddEventListenerOptions& options)
243 {
244     if (eventType == eventNames().devicechangeEvent)
245         listenForDeviceChanges();
246
247     return EventTargetWithInlineData::addEventListener(eventType, WTFMove(listener), options);
248 }
249
250 } // namespace WebCore
251
252 #endif // ENABLE(MEDIA_STREAM)