1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // VideoCaptureDevice is the abstract base class for realizing video capture
6 // device support in Chromium. It provides the interface for OS dependent
8 // The class is created and functions are invoked on a thread owned by
9 // VideoCaptureManager. Capturing is done on other threads, depending on the OS
10 // specific implementation.
12 #ifndef MEDIA_CAPTURE_VIDEO_VIDEO_CAPTURE_DEVICE_H_
13 #define MEDIA_CAPTURE_VIDEO_VIDEO_CAPTURE_DEVICE_H_
21 #include "base/files/file.h"
22 #include "base/functional/callback.h"
23 #include "base/memory/unsafe_shared_memory_region.h"
24 #include "base/task/single_thread_task_runner.h"
25 #include "base/time/time.h"
26 #include "base/token.h"
27 #include "build/build_config.h"
28 #include "media/base/video_frame.h"
29 #include "media/capture/capture_export.h"
30 #include "media/capture/mojom/image_capture.mojom.h"
31 #include "media/capture/mojom/video_capture_types.mojom.h"
32 #include "media/capture/video/video_capture_buffer_handle.h"
33 #include "media/capture/video/video_capture_device_descriptor.h"
34 #include "media/capture/video/video_capture_feedback.h"
35 #include "media/capture/video_capture_types.h"
36 #include "ui/gfx/gpu_memory_buffer.h"
44 class CAPTURE_EXPORT VideoFrameConsumerFeedbackObserver {
46 virtual ~VideoFrameConsumerFeedbackObserver() {}
48 // During processing of a video frame, consumers may report back their
49 // utilization level to the source device. The device may use this information
50 // to adjust the rate of data it pushes out. Values are interpreted as
52 // Less than 0.0 is meaningless and should be ignored. 1.0 indicates a
53 // maximum sustainable utilization. Greater than 1.0 indicates the consumer
54 // is likely to stall or drop frames if the data volume is not reduced.
56 // Example: In a system that encodes and transmits video frames over the
57 // network, this value can be used to indicate whether sufficient CPU
58 // is available for encoding and/or sufficient bandwidth is available for
59 // transmission over the network. The maximum of the two utilization
60 // measurements would be used as feedback.
61 virtual void OnUtilizationReport(media::VideoCaptureFeedback feedback) {}
64 struct CAPTURE_EXPORT CapturedExternalVideoBuffer {
65 CapturedExternalVideoBuffer(gfx::GpuMemoryBufferHandle handle,
66 VideoCaptureFormat format,
67 gfx::ColorSpace color_space);
68 CapturedExternalVideoBuffer(CapturedExternalVideoBuffer&& other);
69 ~CapturedExternalVideoBuffer();
71 CapturedExternalVideoBuffer& operator=(CapturedExternalVideoBuffer&& other);
73 gfx::GpuMemoryBufferHandle handle;
74 VideoCaptureFormat format;
75 gfx::ColorSpace color_space;
78 class CAPTURE_EXPORT VideoCaptureDevice
79 : public VideoFrameConsumerFeedbackObserver {
82 // Interface defining the methods that clients of VideoCapture must have. It
83 // is actually two-in-one: clients may implement OnIncomingCapturedData() or
84 // ReserveOutputBuffer() + OnIncomingCapturedVideoFrame(), or all of them.
85 // All methods may be called as soon as AllocateAndStart() of the
86 // corresponding VideoCaptureDevice is invoked. The methods for buffer
87 // reservation and frame delivery may be called from arbitrary threads but
88 // are guaranteed to be called non-concurrently. The status reporting methods
89 // (OnStarted, OnLog, OnError) may be called concurrently.
90 class CAPTURE_EXPORT Client {
92 // Struct bundling several parameters being passed between a
93 // VideoCaptureDevice and its VideoCaptureDevice::Client.
94 struct CAPTURE_EXPORT Buffer {
96 // Destructor-only interface for encapsulating scoped access permission to
98 class CAPTURE_EXPORT ScopedAccessPermission {
100 virtual ~ScopedAccessPermission() {}
103 class CAPTURE_EXPORT HandleProvider {
105 virtual ~HandleProvider() {}
107 // Duplicate as an writable (unsafe) shared memory region.
108 virtual base::UnsafeSharedMemoryRegion DuplicateAsUnsafeRegion() = 0;
110 // Access a |VideoCaptureBufferHandle| for local, writable memory.
111 virtual std::unique_ptr<VideoCaptureBufferHandle>
112 GetHandleForInProcessAccess() = 0;
114 // Clone a |GpuMemoryBufferHandle| for IPC.
115 virtual gfx::GpuMemoryBufferHandle GetGpuMemoryBufferHandle() = 0;
119 Buffer(int buffer_id,
120 int frame_feedback_id,
121 std::unique_ptr<HandleProvider> handle_provider,
122 std::unique_ptr<ScopedAccessPermission> access_permission);
124 Buffer(Buffer&& other);
125 Buffer& operator=(Buffer&& other);
128 int frame_feedback_id;
129 std::unique_ptr<HandleProvider> handle_provider;
130 std::unique_ptr<ScopedAccessPermission> access_permission;
132 // Some buffer types may be preemptively mapped in the capturer if
133 // requested by the consumer.
134 // This is used to notify the client that a shared memory region
135 // associated with the buffer is valid.
136 bool is_premapped = false;
139 // Result code for calls to ReserveOutputBuffer()
140 enum class ReserveResult {
142 kMaxBufferCountExceeded,
148 // The configuration of the VideoCaptureDevice has changed.
149 virtual void OnCaptureConfigurationChanged() = 0;
151 // Captured a new video frame, data for which is pointed to by |data|.
153 // The format of the frame is described by |frame_format|, and is assumed to
154 // be tightly packed. This method will try to reserve an output buffer and
155 // copy from |data| into the output buffer. If no output buffer is
156 // available, the frame will be silently dropped. |reference_time| is
157 // system clock time when we detect the capture happens, it is used for
158 // Audio/Video sync, not an exact presentation time for playout, because it
159 // could contain noise. |timestamp| measures the ideal time span between the
160 // first frame in the stream and the current frame; however, the time source
161 // is determined by the platform's device driver and is often not the system
162 // clock, or even has a drift with respect to system clock.
163 // |frame_feedback_id| is an identifier that allows clients to refer back to
164 // this particular frame when reporting consumer feedback via
165 // OnConsumerReportingUtilization(). This identifier is needed because
166 // frames are consumed asynchronously and multiple frames can be "in flight"
168 virtual void OnIncomingCapturedData(const uint8_t* data,
170 const VideoCaptureFormat& frame_format,
171 const gfx::ColorSpace& color_space,
172 int clockwise_rotation,
174 base::TimeTicks reference_time,
175 base::TimeDelta timestamp,
176 int frame_feedback_id) = 0;
177 // Convenience wrapper that passes in 0 as |frame_feedback_id|.
178 void OnIncomingCapturedData(const uint8_t* data,
180 const VideoCaptureFormat& frame_format,
181 const gfx::ColorSpace& color_space,
182 int clockwise_rotation,
184 base::TimeTicks reference_time,
185 base::TimeDelta timestamp);
187 // Captured a new video frame, data for which is stored in the
188 // GpuMemoryBuffer pointed to by |buffer|. The format of the frame is
189 // described by |frame_format|. Since the memory buffer pointed to by
190 // |buffer| may be allocated with some size/address alignment requirement,
191 // this method takes into consideration the size and offset of each plane in
192 // |buffer| when creating the content of the output buffer.
193 // |clockwise_rotation|, |reference_time|, |timestamp|, and
194 // |frame_feedback_id| serve the same purposes as in OnIncomingCapturedData.
195 virtual void OnIncomingCapturedGfxBuffer(
196 gfx::GpuMemoryBuffer* buffer,
197 const VideoCaptureFormat& frame_format,
198 int clockwise_rotation,
199 base::TimeTicks reference_time,
200 base::TimeDelta timestamp,
201 int frame_feedback_id) = 0;
202 // Convenience wrapper that passes in 0 as |frame_feedback_id|.
203 void OnIncomingCapturedGfxBuffer(gfx::GpuMemoryBuffer* buffer,
204 const VideoCaptureFormat& frame_format,
205 int clockwise_rotation,
206 base::TimeTicks reference_time,
207 base::TimeDelta timestamp);
209 // Captured a new video frame. The data for this frame is in
210 // |buffer.handle|, which is owned by the platform-specific capture device.
211 // It is the responsibility of the implementation to prevent the buffer in
212 // |buffer.handle| from being reused by the external capturer. In practice,
213 // this is used only on macOS, the external capturer maintains a
214 // CVPixelBufferPool, and gfx::ScopedInUseIOSurface is used to prevent reuse
215 // of buffers until all consumers have consumed them. |visible_rect|
216 // specifies the region in the memory pointed to by |buffer.handle| that
217 // contains the captured content.
218 virtual void OnIncomingCapturedExternalBuffer(
219 CapturedExternalVideoBuffer buffer,
220 std::vector<CapturedExternalVideoBuffer> scaled_buffers,
221 base::TimeTicks reference_time,
222 base::TimeDelta timestamp,
223 gfx::Rect visible_rect) = 0;
225 // Reserve an output buffer into which contents can be captured directly.
226 // The returned |buffer| will always be allocated with a memory size
227 // suitable for holding a packed video frame with pixels of |format| format,
228 // of |dimensions| frame dimensions. It is permissible for |dimensions| to
229 // be zero; in which case the returned Buffer does not guarantee memory
230 // backing, but functions as a reservation for external input for the
231 // purposes of buffer throttling.
233 // The buffer stays reserved for use by the caller as long as it
234 // holds on to the contained |buffer_read_write_permission|.
235 [[nodiscard]] virtual ReserveResult ReserveOutputBuffer(
236 const gfx::Size& dimensions,
237 VideoPixelFormat format,
238 int frame_feedback_id,
241 // Provides VCD::Client with a populated Buffer containing the content of
242 // the next video frame. The |buffer| must originate from an earlier call to
243 // ReserveOutputBuffer().
244 // See OnIncomingCapturedData for details of |reference_time| and
246 virtual void OnIncomingCapturedBuffer(Buffer buffer,
247 const VideoCaptureFormat& format,
248 base::TimeTicks reference_time,
249 base::TimeDelta timestamp) = 0;
251 // Extended version of OnIncomingCapturedBuffer() allowing clients to
252 // pass a custom |visible_rect| and |additional_metadata|.
253 virtual void OnIncomingCapturedBufferExt(
255 const VideoCaptureFormat& format,
256 const gfx::ColorSpace& color_space,
257 base::TimeTicks reference_time,
258 base::TimeDelta timestamp,
259 gfx::Rect visible_rect,
260 const VideoFrameMetadata& additional_metadata) = 0;
262 // An error has occurred that cannot be handled and VideoCaptureDevice must
263 // be StopAndDeAllocate()-ed. |reason| is a text description of the error.
264 virtual void OnError(VideoCaptureError error,
265 const base::Location& from_here,
266 const std::string& reason) = 0;
268 virtual void OnFrameDropped(VideoCaptureFrameDropReason reason) = 0;
270 // VideoCaptureDevice requests the |message| to be logged.
271 virtual void OnLog(const std::string& message) {}
273 // Returns the current buffer pool utilization, in the range 0.0 (no buffers
274 // are in use by producers or consumers) to 1.0 (all buffers are in use).
275 virtual double GetBufferPoolUtilization() const = 0;
277 // VideoCaptureDevice reports it's successfully started.
278 virtual void OnStarted() = 0;
281 ~VideoCaptureDevice() override;
283 // Prepares the video capturer for use. StopAndDeAllocate() must be called
284 // before the object is deleted.
285 virtual void AllocateAndStart(const VideoCaptureParams& params,
286 std::unique_ptr<Client> client) = 0;
288 // In cases where the video capturer self-pauses (e.g., a screen capturer
289 // where the screen's content has not changed in a while), consumers may call
290 // this to request a "refresh frame" be delivered to the Client. This is used
291 // in a number of circumstances, such as:
293 // 1. An additional consumer of video frames is starting up and requires a
294 // first frame (as opposed to not receiving a frame for an indeterminate
296 // 2. A few repeats of the same frame would allow a lossy video encoder to
297 // improve the video quality of unchanging content.
299 // The default implementation is a no-op. VideoCaptureDevice implementations
300 // are not required to honor this request, especially if they do not
301 // self-pause and/or if honoring the request would cause them to exceed their
302 // configured maximum frame rate. Any VideoCaptureDevice that does self-pause,
303 // however, should provide an implementation of this method that makes
304 // reasonable attempts to honor these requests.
306 // Note: This should only be called after AllocateAndStart() and before
307 // StopAndDeAllocate(). Otherwise, its behavior is undefined.
308 virtual void RequestRefreshFrame() {}
310 // Optionally suspends frame delivery. The VideoCaptureDevice may or may not
311 // honor this request. Thus, the caller cannot assume frame delivery will
312 // actually stop. Even if frame delivery is suspended, this might not take
313 // effect immediately.
315 // The purpose of this is to quickly place the device into a state where it's
316 // resource utilization is minimized while there are no frame consumers; and
317 // then quickly resume once a frame consumer is present.
319 // Note: This should only be called after AllocateAndStart() and before
320 // StopAndDeAllocate(). Otherwise, its behavior is undefined.
321 virtual void MaybeSuspend() {}
323 // Resumes frame delivery, if it was suspended. If frame delivery was not
324 // suspended, this is a no-op, and frame delivery will continue.
326 // Note: This should only be called after AllocateAndStart() and before
327 // StopAndDeAllocate(). Otherwise, its behavior is undefined.
328 virtual void Resume() {}
330 // Start/stop cropping.
332 // Non-empty |crop_id| sets (or changes) the crop-target.
333 // Empty |crop_id| reverts the capture to its original, uncropped state.
335 // |crop_version| must be incremented by at least one for each call.
336 // By including it in frame's metadata, Viz informs Blink what was the
337 // latest invocation of cropTo() before a given frame was produced.
339 // The callback reports success/failure. It is called on an unspecified
340 // thread, it's the caller's responsibility to wrap it (i.e. via BindPostTask)
343 const base::Token& crop_id,
344 uint32_t crop_version,
345 base::OnceCallback<void(media::mojom::CropRequestResult)> callback);
347 // Deallocates the video capturer, possibly asynchronously.
349 // This call requires the device to do the following things, eventually: put
350 // hardware into a state where other applications could use it, free the
351 // memory associated with capture, and delete the |client| pointer passed into
354 // If deallocation is done asynchronously, then the device implementation must
355 // ensure that a subsequent AllocateAndStart() operation targeting the same ID
356 // would be sequenced through the same task runner, so that deallocation
358 virtual void StopAndDeAllocate() = 0;
360 // Retrieve the photo capabilities and settings of the device (e.g. zoom
361 // levels etc). On success, invokes |callback|. On failure, drops callback
362 // without invoking it.
363 using GetPhotoStateCallback = base::OnceCallback<void(mojom::PhotoStatePtr)>;
364 virtual void GetPhotoState(GetPhotoStateCallback callback);
366 // On success, invokes |callback| with value |true|. On failure, drops
367 // callback without invoking it.
368 using SetPhotoOptionsCallback = base::OnceCallback<void(bool)>;
369 virtual void SetPhotoOptions(mojom::PhotoSettingsPtr settings,
370 SetPhotoOptionsCallback callback);
372 // Asynchronously takes a photo, possibly reconfiguring the capture objects
373 // and/or interrupting the capture flow. Runs |callback|, if the photo was
374 // successfully taken. On failure, drops callback without invoking it.
375 // Note that |callback| may be runned on a thread different than the thread
376 // where TakePhoto() was called.
377 using TakePhotoCallback = base::OnceCallback<void(mojom::BlobPtr blob)>;
378 virtual void TakePhoto(TakePhotoCallback callback);
380 // Gets the power line frequency, either from the params if specified by the
381 // user or from the current system time zone.
382 static PowerLineFrequency GetPowerLineFrequency(
383 const VideoCaptureParams& params);
386 // Gets the power line frequency from the current system time zone if this is
387 // defined, otherwise returns 0.
388 static PowerLineFrequency GetPowerLineFrequencyForLocation();
391 VideoCaptureFrameDropReason ConvertReservationFailureToFrameDropReason(
392 VideoCaptureDevice::Client::ReserveResult reserve_result);
396 #endif // MEDIA_CAPTURE_VIDEO_VIDEO_CAPTURE_DEVICE_H_