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