Upload upstream chromium 76.0.3809.146
[platform/framework/web/chromium-efl.git] / media / capture / video / video_capture_device.h
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.
4 //
5 // VideoCaptureDevice is the abstract base class for realizing video capture
6 // device support in Chromium. It provides the interface for OS dependent
7 // implementations.
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.
11
12 #ifndef MEDIA_CAPTURE_VIDEO_VIDEO_CAPTURE_DEVICE_H_
13 #define MEDIA_CAPTURE_VIDEO_VIDEO_CAPTURE_DEVICE_H_
14
15 #include <stddef.h>
16 #include <stdint.h>
17
18 #include <list>
19 #include <memory>
20 #include <string>
21
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"
36
37 namespace base {
38 class Location;
39 }  // namespace base
40
41 namespace media {
42
43 class CAPTURE_EXPORT VideoFrameConsumerFeedbackObserver {
44  public:
45   virtual ~VideoFrameConsumerFeedbackObserver() {}
46
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
50   // follows:
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.
54   //
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.
60   //
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
64   // corresponds to.
65   virtual void OnUtilizationReport(int frame_feedback_id, double utilization) {}
66
67   static constexpr double kNoUtilizationRecorded = -1.0;
68 };
69
70 class CAPTURE_EXPORT VideoCaptureDevice
71     : public VideoFrameConsumerFeedbackObserver {
72  public:
73
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 {
83    public:
84     // Struct bundling several parameters being passed between a
85     // VideoCaptureDevice and its VideoCaptureDevice::Client.
86     struct CAPTURE_EXPORT Buffer {
87      public:
88       // Destructor-only interface for encapsulating scoped access permission to
89       // a Buffer.
90       class CAPTURE_EXPORT ScopedAccessPermission {
91        public:
92         virtual ~ScopedAccessPermission() {}
93       };
94
95       class CAPTURE_EXPORT HandleProvider {
96        public:
97         virtual ~HandleProvider() {}
98         virtual mojo::ScopedSharedBufferHandle GetHandleForInterProcessTransit(
99             bool read_only) = 0;
100         virtual base::SharedMemoryHandle
101         GetNonOwnedSharedMemoryHandleForLegacyIPC() = 0;
102         virtual std::unique_ptr<VideoCaptureBufferHandle>
103         GetHandleForInProcessAccess() = 0;
104       };
105
106       Buffer();
107       Buffer(int buffer_id,
108              int frame_feedback_id,
109              std::unique_ptr<HandleProvider> handle_provider,
110              std::unique_ptr<ScopedAccessPermission> access_permission);
111       ~Buffer();
112       Buffer(Buffer&& other);
113       Buffer& operator=(Buffer&& other);
114
115       int id;
116       int frame_feedback_id;
117       std::unique_ptr<HandleProvider> handle_provider;
118       std::unique_ptr<ScopedAccessPermission> access_permission;
119     };
120
121     // Result code for calls to ReserveOutputBuffer()
122     enum class ReserveResult {
123       kSucceeded,
124       kMaxBufferCountExceeded,
125       kAllocationFailed
126     };
127
128     virtual ~Client() {}
129
130     // Captured a new video frame, data for which is pointed to by |data|.
131     //
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"
146     // at the same time.
147     virtual void OnIncomingCapturedData(const uint8_t* data,
148                                         int length,
149                                         const VideoCaptureFormat& frame_format,
150                                         const gfx::ColorSpace& color_space,
151                                         int clockwise_rotation,
152                                         base::TimeTicks reference_time,
153                                         base::TimeDelta timestamp,
154                                         int frame_feedback_id = 0) = 0;
155
156     // Captured a new video frame, data for which is stored in the
157     // GpuMemoryBuffer pointed to by |buffer|.  The format of the frame is
158     // described by |frame_format|.  Since the memory buffer pointed to by
159     // |buffer| may be allocated with some size/address alignment requirement,
160     // this method takes into consideration the size and offset of each plane in
161     // |buffer| when creating the content of the output buffer.
162     // |clockwise_rotation|, |reference_time|, |timestamp|, and
163     // |frame_feedback_id| serve the same purposes as in OnIncomingCapturedData.
164     virtual void OnIncomingCapturedGfxBuffer(
165         gfx::GpuMemoryBuffer* buffer,
166         const VideoCaptureFormat& frame_format,
167         int clockwise_rotation,
168         base::TimeTicks reference_time,
169         base::TimeDelta timestamp,
170         int frame_feedback_id = 0) = 0;
171
172     // Reserve an output buffer into which contents can be captured directly.
173     // The returned |buffer| will always be allocated with a memory size
174     // suitable for holding a packed video frame with pixels of |format| format,
175     // of |dimensions| frame dimensions. It is permissible for |dimensions| to
176     // be zero; in which case the returned Buffer does not guarantee memory
177     // backing, but functions as a reservation for external input for the
178     // purposes of buffer throttling.
179     //
180     // The buffer stays reserved for use by the caller as long as it
181     // holds on to the contained |buffer_read_write_permission|.
182     virtual ReserveResult ReserveOutputBuffer(const gfx::Size& dimensions,
183                                               VideoPixelFormat format,
184                                               int frame_feedback_id,
185                                               Buffer* buffer)
186         WARN_UNUSED_RESULT = 0;
187
188     // Provides VCD::Client with a populated Buffer containing the content of
189     // the next video frame. The |buffer| must originate from an earlier call to
190     // ReserveOutputBuffer().
191     // See OnIncomingCapturedData for details of |reference_time| and
192     // |timestamp|.
193     virtual void OnIncomingCapturedBuffer(Buffer buffer,
194                                           const VideoCaptureFormat& format,
195                                           base::TimeTicks reference_time,
196                                           base::TimeDelta timestamp) = 0;
197
198     // Extended version of OnIncomingCapturedBuffer() allowing clients to
199     // pass a custom |visible_rect| and |additional_metadata|.
200     virtual void OnIncomingCapturedBufferExt(
201         Buffer buffer,
202         const VideoCaptureFormat& format,
203         const gfx::ColorSpace& color_space,
204         base::TimeTicks reference_time,
205         base::TimeDelta timestamp,
206         gfx::Rect visible_rect,
207         const VideoFrameMetadata& additional_metadata) = 0;
208
209     // An error has occurred that cannot be handled and VideoCaptureDevice must
210     // be StopAndDeAllocate()-ed. |reason| is a text description of the error.
211     virtual void OnError(VideoCaptureError error,
212                          const base::Location& from_here,
213                          const std::string& reason) = 0;
214
215     virtual void OnFrameDropped(VideoCaptureFrameDropReason reason) = 0;
216
217     // VideoCaptureDevice requests the |message| to be logged.
218     virtual void OnLog(const std::string& message) {}
219
220     // Returns the current buffer pool utilization, in the range 0.0 (no buffers
221     // are in use by producers or consumers) to 1.0 (all buffers are in use).
222     virtual double GetBufferPoolUtilization() const = 0;
223
224     // VideoCaptureDevice reports it's successfully started.
225     virtual void OnStarted() = 0;
226   };
227
228   ~VideoCaptureDevice() override;
229
230   // Prepares the video capturer for use. StopAndDeAllocate() must be called
231   // before the object is deleted.
232   virtual void AllocateAndStart(const VideoCaptureParams& params,
233                                 std::unique_ptr<Client> client) = 0;
234
235   // In cases where the video capturer self-pauses (e.g., a screen capturer
236   // where the screen's content has not changed in a while), consumers may call
237   // this to request a "refresh frame" be delivered to the Client.  This is used
238   // in a number of circumstances, such as:
239   //
240   //   1. An additional consumer of video frames is starting up and requires a
241   //      first frame (as opposed to not receiving a frame for an indeterminate
242   //      amount of time).
243   //   2. A few repeats of the same frame would allow a lossy video encoder to
244   //      improve the video quality of unchanging content.
245   //
246   // The default implementation is a no-op. VideoCaptureDevice implementations
247   // are not required to honor this request, especially if they do not
248   // self-pause and/or if honoring the request would cause them to exceed their
249   // configured maximum frame rate. Any VideoCaptureDevice that does self-pause,
250   // however, should provide an implementation of this method that makes
251   // reasonable attempts to honor these requests.
252   //
253   // Note: This should only be called after AllocateAndStart() and before
254   // StopAndDeAllocate(). Otherwise, its behavior is undefined.
255   virtual void RequestRefreshFrame() {}
256
257   // Optionally suspends frame delivery. The VideoCaptureDevice may or may not
258   // honor this request. Thus, the caller cannot assume frame delivery will
259   // actually stop. Even if frame delivery is suspended, this might not take
260   // effect immediately.
261   //
262   // The purpose of this is to quickly place the device into a state where it's
263   // resource utilization is minimized while there are no frame consumers; and
264   // then quickly resume once a frame consumer is present.
265   //
266   // Note: This should only be called after AllocateAndStart() and before
267   // StopAndDeAllocate(). Otherwise, its behavior is undefined.
268   virtual void MaybeSuspend() {}
269
270   // Resumes frame delivery, if it was suspended. If frame delivery was not
271   // suspended, this is a no-op, and frame delivery will continue.
272   //
273   // Note: This should only be called after AllocateAndStart() and before
274   // StopAndDeAllocate(). Otherwise, its behavior is undefined.
275   virtual void Resume() {}
276
277   // Deallocates the video capturer, possibly asynchronously.
278   //
279   // This call requires the device to do the following things, eventually: put
280   // hardware into a state where other applications could use it, free the
281   // memory associated with capture, and delete the |client| pointer passed into
282   // AllocateAndStart.
283   //
284   // If deallocation is done asynchronously, then the device implementation must
285   // ensure that a subsequent AllocateAndStart() operation targeting the same ID
286   // would be sequenced through the same task runner, so that deallocation
287   // happens first.
288   virtual void StopAndDeAllocate() = 0;
289
290   // Retrieve the photo capabilities and settings of the device (e.g. zoom
291   // levels etc). On success, invokes |callback|. On failure, drops callback
292   // without invoking it.
293   using GetPhotoStateCallback = base::OnceCallback<void(mojom::PhotoStatePtr)>;
294   virtual void GetPhotoState(GetPhotoStateCallback callback);
295
296   // On success, invokes |callback| with value |true|. On failure, drops
297   // callback without invoking it.
298   using SetPhotoOptionsCallback = base::OnceCallback<void(bool)>;
299   virtual void SetPhotoOptions(mojom::PhotoSettingsPtr settings,
300                                SetPhotoOptionsCallback callback);
301
302   // Asynchronously takes a photo, possibly reconfiguring the capture objects
303   // and/or interrupting the capture flow. Runs |callback|, if the photo was
304   // successfully taken. On failure, drops callback without invoking it.
305   // Note that |callback| may be runned on a thread different than the thread
306   // where TakePhoto() was called.
307   using TakePhotoCallback = base::OnceCallback<void(mojom::BlobPtr blob)>;
308   virtual void TakePhoto(TakePhotoCallback callback);
309
310   // Gets the power line frequency, either from the params if specified by the
311   // user or from the current system time zone.
312   static PowerLineFrequency GetPowerLineFrequency(
313       const VideoCaptureParams& params);
314
315  private:
316   // Gets the power line frequency from the current system time zone if this is
317   // defined, otherwise returns 0.
318   static PowerLineFrequency GetPowerLineFrequencyForLocation();
319 };
320
321 VideoCaptureFrameDropReason ConvertReservationFailureToFrameDropReason(
322     VideoCaptureDevice::Client::ReserveResult reserve_result);
323
324 }  // namespace media
325
326 #endif  // MEDIA_CAPTURE_VIDEO_VIDEO_CAPTURE_DEVICE_H_