1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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_
22 #include "base/callback.h"
23 #include "base/files/file.h"
24 #include "base/logging.h"
25 #include "base/memory/ref_counted.h"
26 #include "base/single_thread_task_runner.h"
27 #include "base/time/time.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/video/video_capture_buffer_handle.h"
33 #include "media/capture/video/video_capture_device_descriptor.h"
34 #include "media/capture/video_capture_types.h"
35 #include "ui/gfx/gpu_memory_buffer.h"
43 class CAPTURE_EXPORT VideoFrameConsumerFeedbackObserver {
45 virtual ~VideoFrameConsumerFeedbackObserver() {}
47 // During processing of a video frame, consumers may report back their
48 // utilization level to the source device. The device may use this information
49 // to adjust the rate of data it pushes out. Values are interpreted as
51 // Less than 0.0 is meaningless and should be ignored. 1.0 indicates a
52 // maximum sustainable utilization. Greater than 1.0 indicates the consumer
53 // is likely to stall or drop frames if the data volume is not reduced.
55 // Example: In a system that encodes and transmits video frames over the
56 // network, this value can be used to indicate whether sufficient CPU
57 // is available for encoding and/or sufficient bandwidth is available for
58 // transmission over the network. The maximum of the two utilization
59 // measurements would be used as feedback.
61 // The parameter |frame_feedback_id| must match a |frame_feedback_id|
62 // previously sent out by the VideoCaptureDevice we are giving feedback about.
63 // It is used to indicate which particular frame the reported utilization
65 virtual void OnUtilizationReport(int frame_feedback_id, double utilization) {}
67 static constexpr double kNoUtilizationRecorded = -1.0;
70 class CAPTURE_EXPORT VideoCaptureDevice
71 : public VideoFrameConsumerFeedbackObserver {
74 // Interface defining the methods that clients of VideoCapture must have. It
75 // is actually two-in-one: clients may implement OnIncomingCapturedData() or
76 // ReserveOutputBuffer() + OnIncomingCapturedVideoFrame(), or all of them.
77 // All methods may be called as soon as AllocateAndStart() of the
78 // corresponding VideoCaptureDevice is invoked. The methods for buffer
79 // reservation and frame delivery may be called from arbitrary threads but
80 // are guaranteed to be called non-concurrently. The status reporting methods
81 // (OnStarted, OnLog, OnError) may be called concurrently.
82 class CAPTURE_EXPORT Client {
84 // Struct bundling several parameters being passed between a
85 // VideoCaptureDevice and its VideoCaptureDevice::Client.
86 struct CAPTURE_EXPORT Buffer {
88 // Destructor-only interface for encapsulating scoped access permission to
90 class CAPTURE_EXPORT ScopedAccessPermission {
92 virtual ~ScopedAccessPermission() {}
95 class CAPTURE_EXPORT HandleProvider {
97 virtual ~HandleProvider() {}
98 virtual mojo::ScopedSharedBufferHandle GetHandleForInterProcessTransit(
100 virtual base::SharedMemoryHandle
101 GetNonOwnedSharedMemoryHandleForLegacyIPC() = 0;
102 virtual std::unique_ptr<VideoCaptureBufferHandle>
103 GetHandleForInProcessAccess() = 0;
107 Buffer(int buffer_id,
108 int frame_feedback_id,
109 std::unique_ptr<HandleProvider> handle_provider,
110 std::unique_ptr<ScopedAccessPermission> access_permission);
112 Buffer(Buffer&& other);
113 Buffer& operator=(Buffer&& other);
116 int frame_feedback_id;
117 std::unique_ptr<HandleProvider> handle_provider;
118 std::unique_ptr<ScopedAccessPermission> access_permission;
121 // Result code for calls to ReserveOutputBuffer()
122 enum class ReserveResult {
124 kMaxBufferCountExceeded,
130 // Captured a new video frame, data for which is pointed to by |data|.
132 // The format of the frame is described by |frame_format|, and is assumed to
133 // be tightly packed. This method will try to reserve an output buffer and
134 // copy from |data| into the output buffer. If no output buffer is
135 // available, the frame will be silently dropped. |reference_time| is
136 // system clock time when we detect the capture happens, it is used for
137 // Audio/Video sync, not an exact presentation time for playout, because it
138 // could contain noise. |timestamp| measures the ideal time span between the
139 // first frame in the stream and the current frame; however, the time source
140 // is determined by the platform's device driver and is often not the system
141 // clock, or even has a drift with respect to system clock.
142 // |frame_feedback_id| is an identifier that allows clients to refer back to
143 // this particular frame when reporting consumer feedback via
144 // OnConsumerReportingUtilization(). This identifier is needed because
145 // frames are consumed asynchronously and multiple frames can be "in flight"
147 virtual void OnIncomingCapturedData(const uint8_t* data,
149 const VideoCaptureFormat& frame_format,
150 int clockwise_rotation,
151 base::TimeTicks reference_time,
152 base::TimeDelta timestamp,
153 int frame_feedback_id = 0) = 0;
155 // Captured a new video frame, data for which is stored in the
156 // GpuMemoryBuffer pointed to by |buffer|. The format of the frame is
157 // described by |frame_format|. Since the memory buffer pointed to by
158 // |buffer| may be allocated with some size/address alignment requirement,
159 // this method takes into consideration the size and offset of each plane in
160 // |buffer| when creating the content of the output buffer.
161 // |clockwise_rotation|, |reference_time|, |timestamp|, and
162 // |frame_feedback_id| serve the same purposes as in OnIncomingCapturedData.
163 virtual void OnIncomingCapturedGfxBuffer(
164 gfx::GpuMemoryBuffer* buffer,
165 const VideoCaptureFormat& frame_format,
166 int clockwise_rotation,
167 base::TimeTicks reference_time,
168 base::TimeDelta timestamp,
169 int frame_feedback_id = 0) = 0;
171 // Reserve an output buffer into which contents can be captured directly.
172 // The returned |buffer| will always be allocated with a memory size
173 // suitable for holding a packed video frame with pixels of |format| format,
174 // of |dimensions| frame dimensions. It is permissible for |dimensions| to
175 // be zero; in which case the returned Buffer does not guarantee memory
176 // backing, but functions as a reservation for external input for the
177 // purposes of buffer throttling.
179 // The buffer stays reserved for use by the caller as long as it
180 // holds on to the contained |buffer_read_write_permission|.
181 virtual ReserveResult ReserveOutputBuffer(const gfx::Size& dimensions,
182 VideoPixelFormat format,
183 int frame_feedback_id,
185 WARN_UNUSED_RESULT = 0;
187 // Provides VCD::Client with a populated Buffer containing the content of
188 // the next video frame. The |buffer| must originate from an earlier call to
189 // ReserveOutputBuffer().
190 // See OnIncomingCapturedData for details of |reference_time| and
192 virtual void OnIncomingCapturedBuffer(Buffer buffer,
193 const VideoCaptureFormat& format,
194 base::TimeTicks reference_time,
195 base::TimeDelta timestamp) = 0;
197 // Extended version of OnIncomingCapturedBuffer() allowing clients to
198 // pass a custom |visible_rect| and |additional_metadata|.
199 virtual void OnIncomingCapturedBufferExt(
201 const VideoCaptureFormat& format,
202 base::TimeTicks reference_time,
203 base::TimeDelta timestamp,
204 gfx::Rect visible_rect,
205 const VideoFrameMetadata& additional_metadata) = 0;
207 // An error has occurred that cannot be handled and VideoCaptureDevice must
208 // be StopAndDeAllocate()-ed. |reason| is a text description of the error.
209 virtual void OnError(VideoCaptureError error,
210 const base::Location& from_here,
211 const std::string& reason) = 0;
213 virtual void OnFrameDropped(VideoCaptureFrameDropReason reason) = 0;
215 // VideoCaptureDevice requests the |message| to be logged.
216 virtual void OnLog(const std::string& message) {}
218 // Returns the current buffer pool utilization, in the range 0.0 (no buffers
219 // are in use by producers or consumers) to 1.0 (all buffers are in use).
220 virtual double GetBufferPoolUtilization() const = 0;
222 // VideoCaptureDevice reports it's successfully started.
223 virtual void OnStarted() = 0;
226 ~VideoCaptureDevice() override;
228 // Prepares the video capturer for use. StopAndDeAllocate() must be called
229 // before the object is deleted.
230 virtual void AllocateAndStart(const VideoCaptureParams& params,
231 std::unique_ptr<Client> client) = 0;
233 // In cases where the video capturer self-pauses (e.g., a screen capturer
234 // where the screen's content has not changed in a while), consumers may call
235 // this to request a "refresh frame" be delivered to the Client. This is used
236 // in a number of circumstances, such as:
238 // 1. An additional consumer of video frames is starting up and requires a
239 // first frame (as opposed to not receiving a frame for an indeterminate
241 // 2. A few repeats of the same frame would allow a lossy video encoder to
242 // improve the video quality of unchanging content.
244 // The default implementation is a no-op. VideoCaptureDevice implementations
245 // are not required to honor this request, especially if they do not
246 // self-pause and/or if honoring the request would cause them to exceed their
247 // configured maximum frame rate. Any VideoCaptureDevice that does self-pause,
248 // however, should provide an implementation of this method that makes
249 // reasonable attempts to honor these requests.
251 // Note: This should only be called after AllocateAndStart() and before
252 // StopAndDeAllocate(). Otherwise, its behavior is undefined.
253 virtual void RequestRefreshFrame() {}
255 // Optionally suspends frame delivery. The VideoCaptureDevice may or may not
256 // honor this request. Thus, the caller cannot assume frame delivery will
257 // actually stop. Even if frame delivery is suspended, this might not take
258 // effect immediately.
260 // The purpose of this is to quickly place the device into a state where it's
261 // resource utilization is minimized while there are no frame consumers; and
262 // then quickly resume once a frame consumer is present.
264 // Note: This should only be called after AllocateAndStart() and before
265 // StopAndDeAllocate(). Otherwise, its behavior is undefined.
266 virtual void MaybeSuspend() {}
268 // Resumes frame delivery, if it was suspended. If frame delivery was not
269 // suspended, this is a no-op, and frame delivery will continue.
271 // Note: This should only be called after AllocateAndStart() and before
272 // StopAndDeAllocate(). Otherwise, its behavior is undefined.
273 virtual void Resume() {}
275 // Deallocates the video capturer, possibly asynchronously.
277 // This call requires the device to do the following things, eventually: put
278 // hardware into a state where other applications could use it, free the
279 // memory associated with capture, and delete the |client| pointer passed into
282 // If deallocation is done asynchronously, then the device implementation must
283 // ensure that a subsequent AllocateAndStart() operation targeting the same ID
284 // would be sequenced through the same task runner, so that deallocation
286 virtual void StopAndDeAllocate() = 0;
288 // Retrieve the photo capabilities and settings of the device (e.g. zoom
289 // levels etc). On success, invokes |callback|. On failure, drops callback
290 // without invoking it.
291 using GetPhotoStateCallback = base::OnceCallback<void(mojom::PhotoStatePtr)>;
292 virtual void GetPhotoState(GetPhotoStateCallback callback);
294 // On success, invokes |callback| with value |true|. On failure, drops
295 // callback without invoking it.
296 using SetPhotoOptionsCallback = base::OnceCallback<void(bool)>;
297 virtual void SetPhotoOptions(mojom::PhotoSettingsPtr settings,
298 SetPhotoOptionsCallback callback);
300 // Asynchronously takes a photo, possibly reconfiguring the capture objects
301 // and/or interrupting the capture flow. Runs |callback|, if the photo was
302 // successfully taken. On failure, drops callback without invoking it.
303 // Note that |callback| may be runned on a thread different than the thread
304 // where TakePhoto() was called.
305 using TakePhotoCallback = base::OnceCallback<void(mojom::BlobPtr blob)>;
306 virtual void TakePhoto(TakePhotoCallback callback);
308 // Gets the power line frequency, either from the params if specified by the
309 // user or from the current system time zone.
310 static PowerLineFrequency GetPowerLineFrequency(
311 const VideoCaptureParams& params);
314 // Gets the power line frequency from the current system time zone if this is
315 // defined, otherwise returns 0.
316 static PowerLineFrequency GetPowerLineFrequencyForLocation();
319 VideoCaptureFrameDropReason ConvertReservationFailureToFrameDropReason(
320 VideoCaptureDevice::Client::ReserveResult reserve_result);
324 #endif // MEDIA_CAPTURE_VIDEO_VIDEO_CAPTURE_DEVICE_H_