xref: /aosp_15_r20/external/v4l2_codec2/v4l2/include/v4l2_codec2/v4l2/V4L2Device.h (revision 0ec5a0ec62797f775085659156625e7f1bdb369f)
1 // Copyright 2014 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 // This file defines the V4L2Device which is used by the V4L2Decoder and V4L2Encoder classes to
6 // delegate/pass the device specific handling of any of the functionalities.
7 // Note: ported from Chromium commit head: 2f13d62f0c0d, but some parts have been removed.
8 
9 #ifndef ANDROID_V4L2_CODEC2_V4L2_V4L2_DEVICE_H
10 #define ANDROID_V4L2_CODEC2_V4L2_V4L2_DEVICE_H
11 
12 #include <linux/videodev2.h>
13 #include <stddef.h>
14 #include <stdint.h>
15 
16 #include <cstdint>
17 #include <optional>
18 #include <vector>
19 
20 #include <C2Config.h>
21 #include <base/containers/flat_map.h>
22 #include <base/files/scoped_file.h>
23 #include <base/memory/ref_counted.h>
24 
25 #include <ui/Size.h>
26 #include <v4l2_codec2/common/Common.h>
27 #include <v4l2_codec2/common/VideoTypes.h>
28 #include <v4l2_codec2/v4l2/V4L2DevicePoller.h>
29 
30 // VP8 parsed frames
31 #ifndef V4L2_PIX_FMT_VP8_FRAME
32 #define V4L2_PIX_FMT_VP8_FRAME v4l2_fourcc('V', 'P', '8', 'F')
33 #endif
34 
35 // VP9 parsed frames
36 #ifndef V4L2_PIX_FMT_VP9_FRAME
37 #define V4L2_PIX_FMT_VP9_FRAME v4l2_fourcc('V', 'P', '9', 'F')
38 #endif
39 
40 // H264 parsed slices
41 #ifndef V4L2_PIX_FMT_H264_SLICE
42 #define V4L2_PIX_FMT_H264_SLICE v4l2_fourcc('S', '2', '6', '4')
43 #endif
44 
45 // HEVC parsed slices
46 #ifndef V4L2_PIX_FMT_HEVC_SLICE
47 #define V4L2_PIX_FMT_HEVC_SLICE v4l2_fourcc('S', '2', '6', '5')
48 #endif
49 
50 namespace android {
51 
52 class V4L2Queue;
53 class V4L2BufferRefBase;
54 class V4L2BuffersList;
55 class V4L2DecodeSurface;
56 
57 // Wrapper for the 'v4l2_ext_control' structure.
58 struct V4L2ExtCtrl {
59     V4L2ExtCtrl(uint32_t id);
60     V4L2ExtCtrl(uint32_t id, int32_t val);
61     struct v4l2_ext_control ctrl;
62 };
63 
64 bool isValidPixFmtForCodec(VideoCodec codec, uint32_t pixFmt);
65 
66 // A unique reference to a buffer for clients to prepare and submit.
67 //
68 // Clients can prepare a buffer for queuing using the methods of this class, and then either queue
69 // it using the Queue() method corresponding to the memory type of the buffer, or drop the reference
70 // to make the buffer available again.
71 class V4L2WritableBufferRef {
72 public:
73     V4L2WritableBufferRef(V4L2WritableBufferRef&& other);
74     V4L2WritableBufferRef() = delete;
75     V4L2WritableBufferRef& operator=(V4L2WritableBufferRef&& other);
76 
77     // Return the memory type of the buffer. Useful to e.g. decide which Queue() method to use.
78     enum v4l2_memory memory() const;
79 
80     // Queue a MMAP buffer. If successful, true is returned and the reference to the buffer is
81     // dropped so this reference becomes invalid. In case of error, false is returned and the buffer
82     // is returned to the free list.
83     bool queueMMap() &&;
84     // Queue a USERPTR buffer, assigning |ptrs| as pointer for each plane. The size of |ptrs| must
85     // be equal to the number of planes of this buffer. If successful, true is returned and the
86     // reference to the buffer is dropped so this reference becomes invalid. In case of error, false
87     // is returned and the buffer is returned to the free list.
88     bool queueUserPtr(const std::vector<void*>& ptrs) &&;
89     // Queue a DMABUF buffer, assigning |fds| as file descriptors for each plane. It is allowed the
90     // number of |fds| might be greater than the number of planes of this buffer. It happens when
91     // the v4l2 pixel format is single planar. The fd of the first plane is only used in that case.
92     // If successful, true is returned and the reference to the buffer is dropped so this reference
93     // becomes invalid. In case of error, false is returned and the buffer is returned to the free
94     // list.
95     bool queueDMABuf(const std::vector<int>& fds) &&;
96 
97     // Returns the number of planes in this buffer.
98     size_t planesCount() const;
99     // Returns the size of the requested |plane|, in bytes.
100     size_t getPlaneSize(const size_t plane) const;
101     // Set the size of the requested |plane|, in bytes. It is only valid for USERPTR and DMABUF
102     // buffers. When using an MMAP buffer, this method triggers an assert and is a no-op for release
103     // builds.
104     void setPlaneSize(const size_t plane, const size_t size);
105     // This method can only be used with MMAP buffers. It will return a pointer to the data of the
106     // |plane|th plane. In case of error (invalid plane index or mapping failed), a nullptr is
107     // returned.
108     void* getPlaneMapping(const size_t plane);
109     // Set the timestamp field for this buffer.
110     void setTimeStamp(const struct timeval& timestamp);
111     // Return the previously-set timestamp field for this buffer.
112     const struct timeval& getTimeStamp() const;
113     // Set the number of bytes used for |plane|.
114     void setPlaneBytesUsed(const size_t plane, const size_t bytesUsed);
115     // Returns the previously-set number of bytes used for |plane|.
116     size_t getPlaneBytesUsed(const size_t plane) const;
117     // Set the data offset for |plane|, in bytes.
118     void setPlaneDataOffset(const size_t plane, const size_t dataOffset);
119 
120     // Return the V4L2 buffer ID of the underlying buffer.
121     size_t bufferId() const;
122 
123     ~V4L2WritableBufferRef();
124 
125 private:
126     friend class V4L2BufferRefFactory;
127 
128     // Do the actual queue operation once the v4l2_buffer structure is properly filled.
129     bool doQueue() &&;
130 
131     V4L2WritableBufferRef(const struct v4l2_buffer& v4l2Buffer, ::base::WeakPtr<V4L2Queue> queue);
132 
133     V4L2WritableBufferRef(const V4L2WritableBufferRef&) = delete;
134     V4L2WritableBufferRef& operator=(const V4L2WritableBufferRef&) = delete;
135 
136     std::unique_ptr<V4L2BufferRefBase> mBufferData;
137 
138     SEQUENCE_CHECKER(mSequenceChecker);
139 };
140 
141 // A reference to a read-only, dequeued buffer.
142 //
143 // Clients use this class to query the buffer state and content, and are guaranteed that the buffer
144 // will not be reused until all references are destroyed.
145 // All methods of this class must be called from the same sequence, but instances of
146 // V4L2ReadableBuffer objects can be destroyed from any sequence. They can even outlive the V4L2
147 // buffers they originate from. This flexibility is required because V4L2ReadableBufferRefs can be
148 // embedded into VideoFrames, which are then passed to other threads and not necessarily destroyed
149 // before the V4L2Queue buffers are freed.
150 class V4L2ReadableBuffer : public ::base::RefCountedThreadSafe<V4L2ReadableBuffer> {
151 public:
152     // Returns whether the V4L2_BUF_FLAG_LAST flag is set for this buffer.
153     bool isLast() const;
154     // Returns whether the V4L2_BUF_FLAG_KEYFRAME flag is set for this buffer.
155     bool isKeyframe() const;
156     // Return the timestamp set by the driver on this buffer.
157     struct timeval getTimeStamp() const;
158     // Returns the number of planes in this buffer.
159     size_t planesCount() const;
160     // Returns the number of bytes used for |plane|.
161     size_t getPlaneBytesUsed(size_t plane) const;
162     // Returns the data offset for |plane|.
163     size_t getPlaneDataOffset(size_t plane) const;
164     // This method can only be used with MMAP buffers. It will return a pointer to the data of the
165     // |plane|th plane. In case of error (invalid plane index or mapping failed), a nullptr is
166     // returned.
167     const void* getPlaneMapping(const size_t plane) const;
168 
169     // Return the V4L2 buffer ID of the underlying buffer.
170     size_t bufferId() const;
171 
172 private:
173     friend class V4L2BufferRefFactory;
174     friend class ::base::RefCountedThreadSafe<V4L2ReadableBuffer>;
175 
176     ~V4L2ReadableBuffer();
177 
178     V4L2ReadableBuffer(const struct v4l2_buffer& v4l2Buffer, ::base::WeakPtr<V4L2Queue> queue);
179 
180     V4L2ReadableBuffer(const V4L2ReadableBuffer&) = delete;
181     V4L2ReadableBuffer& operator=(const V4L2ReadableBuffer&) = delete;
182 
183     std::unique_ptr<V4L2BufferRefBase> mBufferData;
184 
185     SEQUENCE_CHECKER(mSequenceChecker);
186 };
187 
188 // Shortcut for naming consistency.
189 using V4L2ReadableBufferRef = scoped_refptr<V4L2ReadableBuffer>;
190 
191 class V4L2Device;
192 class V4L2Buffer;
193 
194 // Interface representing a specific queue of a |V4L2Device|. It provides free and queued buffer
195 // management that is commonly required by clients.
196 //
197 // Buffers managed by this class undergo the following cycle:
198 // 1) Allocated buffers are put into a free buffers pool, indicating that they are used neither by
199 //    the client nor the hardware.
200 // 2) The client obtains a unique, writable reference to one of the free  buffers in order to set
201 //    its content and other parameters.
202 // 3) The client then queues the buffer obtained in 2), which invalidates its reference. The buffer
203 //    is now prepared to be processed by the hardware.
204 // 4) Once the hardware is done with the buffer, it is ready to be dequeued by the client. The
205 //    client obtains a read-only, counted reference to the buffer and can read its content and
206 //    metadata, as well as making other references to it. The buffer will not be reused until all
207 //    the references are dropped. Once this happens, the buffer goes back to the free list described
208 //    in 1).
209 class V4L2Queue : public ::base::RefCountedThreadSafe<V4L2Queue> {
210 public:
211     // Set |fourcc| as the current format on this queue. |size| corresponds to the desired buffer's
212     // dimensions (i.e. width and height members of v4l2_pix_format_mplane (if not applicable, pass
213     // Size()).
214     // |bufferSize| is the desired size in bytes of the buffer for single-planar formats (i.e.
215     // sizeimage of the first plane). It can be set to 0 if not relevant for the desired format.
216     // |stride| is the desired stride in bytes of the buffer (i.e. bytesperline). It can be set to 0
217     // if not relevant or to let the driver decide. If the format could be set, then the
218     // |v4l2_format| reflecting the actual format is returned. It is guaranteed to feature the
219     // specified |fourcc|, but any other parameter (including |size| and |bufferSize| may have been
220     // adjusted by the driver, so the caller must check their values.
221     std::optional<struct v4l2_format> setFormat(uint32_t fourcc, const ui::Size& size,
222                                                 size_t bufferSize,
223                                                 uint32_t stride = 0) WARN_UNUSED_RESULT;
224 
225     // Identical to |setFormat|, but does not actually apply the format, and can be called anytime.
226     // Returns an adjusted V4L2 format if |fourcc| is supported by the queue, or |nullopt| if
227     // |fourcc| is not supported or an ioctl error happened.
228     std::optional<struct v4l2_format> tryFormat(uint32_t fourcc, const ui::Size& size,
229                                                 size_t bufferSize) WARN_UNUSED_RESULT;
230 
231     // Returns the currently set format on the queue. The result is returned as a std::pair where
232     // the first member is the format, or ::base::nullopt if the format could not be obtained due
233     // to an ioctl error. The second member is only used in case of an error and contains the
234     // |errno| set by the failing ioctl. If the first member is not ::base::nullopt, the second
235     // member will always be zero.
236     //
237     // If the second member is 0, then the first member is guaranteed to have a valid value. So
238     // clients that are not interested in the precise error message can just check that the first
239     // member is valid and go on.
240     //
241     // This pair is used because not all failures to get the format are necessarily errors, so we
242     // need to way to let the use decide whether it is one or not.
243     std::pair<std::optional<struct v4l2_format>, int> getFormat();
244 
245     // Allocate |count| buffers for the current format of this queue, with a specific |memory|
246     // allocation, and returns the number of buffers allocated or zero if an error occurred, or if
247     // references to any previously allocated buffers are still held by any clients.
248     //
249     // The number of allocated buffers may be larger than the number requested, so callers must
250     // always check the return value.
251     //
252     // Calling this method while buffers are still allocated results in an error.
253     size_t allocateBuffers(size_t count, enum v4l2_memory memory) WARN_UNUSED_RESULT;
254 
255     // Deallocate all buffers previously allocated by |allocateBuffers|. Any references to buffers
256     // previously allocated held by the client must be released, or this call will fail.
257     bool deallocateBuffers();
258 
259     // Returns the memory usage of v4l2 buffers owned by this V4L2Queue which are mapped in user
260     // space memory.
261     size_t getMemoryUsage() const;
262 
263     // Returns |mMemory|, memory type of last buffers allocated by this V4L2Queue.
264     v4l2_memory getMemoryType() const;
265 
266     // Return a reference to a free buffer for the caller to prepare and submit, or nullopt if no
267     // buffer is currently free.
268     //
269     // If the caller discards the returned reference, the underlying buffer is made available to
270     // clients again.
271     std::optional<V4L2WritableBufferRef> getFreeBuffer();
272     std::optional<V4L2WritableBufferRef> getFreeBuffer(size_t requestedBufferId);
273 
274     // Attempt to dequeue a buffer, and return a reference to it if one was available.
275     //
276     // The first element of the returned pair will be false if an error occurred, in which case the
277     // second element will be nullptr. If no error occurred, then the first element will be true and
278     // the second element will contain a reference to the dequeued buffer if one was available, or
279     // nullptr otherwise. Dequeued buffers will not be reused by the driver until all references to
280     // them are dropped.
281     std::pair<bool, V4L2ReadableBufferRef> dequeueBuffer();
282 
283     // Returns true if this queue is currently streaming.
284     bool isStreaming() const;
285     // If not currently streaming, starts streaming. Returns true if we started streaming, or were
286     // already streaming, or false if we were not streaming and an error occurred when attempting to
287     // start the stream. On failure, any previously-queued buffers will be dequeued without
288     // processing and made available to the client, while any buffers held by the client will remain
289     // unchanged and their ownership will remain with the client.
290     bool streamon();
291     // If currently streaming, stops streaming. Also make all queued buffers available to the client
292     // again regardless of the streaming state. If an error occurred while attempting to stop
293     // streaming, then false is returned and queued buffers are left untouched since the V4L2 queue
294     // may still be using them.
295     bool streamoff();
296 
297     // Returns the number of buffers currently allocated for this queue.
298     size_t allocatedBuffersCount() const;
299     // Returns the number of currently free buffers on this queue.
300     size_t freeBuffersCount() const;
301     // Returns the number of buffers currently queued on this queue.
302     size_t queuedBuffersCount() const;
303 
304 private:
305     ~V4L2Queue();
306 
307     V4L2Queue(const V4L2Queue&) = delete;
308     V4L2Queue& operator=(const V4L2Queue&) = delete;
309 
310     // Called when clients request a buffer to be queued.
311     bool queueBuffer(struct v4l2_buffer* v4l2Buffer);
312 
313     void reportTraceMetrics();
314 
315     const enum v4l2_buf_type mType;
316     enum v4l2_memory mMemory = V4L2_MEMORY_MMAP;
317     bool mIsStreaming = false;
318     size_t mPlanesCount = 0;
319     // Current format as set by SetFormat.
320     std::optional<struct v4l2_format> mCurrentFormat;
321 
322     std::vector<std::unique_ptr<V4L2Buffer>> mBuffers;
323 
324     // Buffers that are available for client to get and submit. Buffers in this list are not
325     // referenced by anyone else than ourselves.
326     scoped_refptr<V4L2BuffersList> mFreeBuffers;
327     // Buffers that have been queued by the client, and not dequeued yet.
328     std::set<size_t> mQueuedBuffers;
329 
330     scoped_refptr<V4L2Device> mDevice;
331     // Callback to call in this queue's destructor.
332     ::base::OnceClosure mDestroyCb;
333 
334     V4L2Queue(scoped_refptr<V4L2Device> dev, enum v4l2_buf_type type,
335               ::base::OnceClosure destroyCb);
336     friend class V4L2QueueFactory;
337     friend class V4L2BufferRefBase;
338     friend class ::base::RefCountedThreadSafe<V4L2Queue>;
339 
340     SEQUENCE_CHECKER(mSequenceChecker);
341 
342     ::base::WeakPtrFactory<V4L2Queue> mWeakThisFactory{this};
343 };
344 
345 class V4L2Device : public ::base::RefCountedThreadSafe<V4L2Device> {
346 public:
347     // Utility format conversion functions
348     // If there is no corresponding single- or multi-planar format, returns 0.
349     static uint32_t c2ProfileToV4L2PixFmt(C2Config::profile_t profile, bool sliceBased);
350     static C2Config::level_t v4L2LevelToC2Level(VideoCodec codec, uint32_t level);
351     static C2Config::profile_t v4L2ProfileToC2Profile(VideoCodec codec, uint32_t profile);
352     static uint32_t videoCodecToPixFmt(VideoCodec codec);
353     // Calculates the largest plane's allocation size requested by a V4L2 device.
354     static ui::Size allocatedSizeFromV4L2Format(const struct v4l2_format& format);
355 
356     // Convert required H264 profile and level to V4L2 enums.
357     static int32_t c2ProfileToV4L2H264Profile(C2Config::profile_t profile);
358     static int32_t h264LevelIdcToV4L2H264Level(uint8_t levelIdc);
359     static v4l2_mpeg_video_bitrate_mode c2BitrateModeToV4L2BitrateMode(
360             C2Config::bitrate_mode_t bitrateMode);
361 
362     // Converts v4l2_memory to a string.
363     static const char* v4L2MemoryToString(const v4l2_memory memory);
364 
365     // Returns the printable name of a v4l2_buf_type.
366     static const char* v4L2BufferTypeToString(const enum v4l2_buf_type bufType);
367 
368     // Converts v4l2_buf_type to a string, used for tracing.
369     static std::string v4L2BufferTypeToATraceLabel(uint32_t debugStreamId,
370                                                    const enum v4l2_buf_type type,
371                                                    const char* label);
372 
373     // Composes human readable string of v4l2_format.
374     static std::string v4L2FormatToString(const struct v4l2_format& format);
375 
376     // Composes human readable string of v4l2_buffer.
377     static std::string v4L2BufferToString(const struct v4l2_buffer& buffer);
378 
379     // Composes VideoFrameLayout based on v4l2_format. If error occurs, it returns ::base::nullopt.
380     static std::optional<VideoFrameLayout> v4L2FormatToVideoFrameLayout(
381             const struct v4l2_format& format);
382 
383     // Returns number of planes of |pixFmt|.
384     static size_t getNumPlanesOfV4L2PixFmt(uint32_t pixFmt);
385 
386     enum class Type { kDecoder, kEncoder };
387 
388     // Gets supported coding formats for |type| device and |pixelFormats|
389     static SupportedProfiles getSupportedProfiles(Type type,
390                                                   const std::vector<uint32_t>& pixelFormats);
391 
392     // Gets supported levels for all decoder devices
393     static std::vector<C2Config::level_t> getSupportedDecodeLevels(VideoCodec videoCodecType);
394 
395     // Get first current profile for any device
396     static C2Config::profile_t getDefaultProfile(VideoCodec codec);
397 
398     // Gets first current profile for any device
399     static C2Config::level_t getDefaultLevel(VideoCodec codec);
400 
401     // Gets all capabilites of the decoder devices.
402     static SupportedCapabilities queryDecodingCapabilities(VideoCodec codec);
403 
404     // Gets all capabilites of the encoder devices.
405     static SupportedCapabilities queryEncodingCapabilities(VideoCodec codec);
406 
407     // Create and initialize an appropriate V4L2Device instance for the current platform, or return
408     // nullptr if not available.
409     static scoped_refptr<V4L2Device> create(uint32_t debugStreamId = -1);
410 
411     // Open a V4L2 device of |type| for use with |v4l2PixFmt|. Return true on success. The device
412     // will be closed in the destructor.
413     bool open(Type type, uint32_t v4l2PixFmt);
414 
415     // Returns the V4L2Queue corresponding to the requested |type|, or nullptr if the requested
416     // queue type is not supported.
417     scoped_refptr<V4L2Queue> getQueue(enum v4l2_buf_type type);
418 
419     // Parameters and return value are the same as for the standard ioctl() system call.
420     int ioctl(int request, void* arg);
421 
422     // This method sleeps until either:
423     // - SetDevicePollInterrupt() is called (on another thread),
424     // - |pollDevice| is true, and there is new event from the device has arrived;
425     //   in this case |*eventPending| will be set to true.
426     // - |pollBuffers| is true and |pollDevice| is true and there is new data to
427     //   be read from the device; in this case |*buffersPending| will be set to true.
428     // Returns false on error, true otherwise. This method should be called from a separate thread.
429     bool poll(bool pollDevice, bool pollBuffers, bool* eventPending, bool* buffersPending);
430 
431     // These methods are used to interrupt the thread sleeping on poll() and force it to return
432     // regardless of device state, which is usually when the client is no longer interested in what
433     // happens with the device (on cleanup, client state change, etc.). When
434     // setDevicePollInterrupt() is called, poll() will return immediately, and any subsequent calls
435     // to it will also do so until clearDevicePollInterrupt() is called.
436     bool setDevicePollInterrupt();
437     bool clearDevicePollInterrupt();
438 
439     // Wrappers for standard mmap/munmap system calls.
440     void* mmap(void* addr, unsigned int len, int prot, int flags, unsigned int offset);
441     void munmap(void* addr, unsigned int len);
442 
443     // Return a vector of dmabuf file descriptors, exported for V4L2 buffer with |index|, assuming
444     // the buffer contains |numPlanes| V4L2 planes and is of |bufType|. Return an empty vector on
445     // failure. The caller is responsible for closing the file descriptors after use.
446     std::vector<::base::ScopedFD> getDmabufsForV4L2Buffer(int index, size_t numPlanes,
447                                                           enum v4l2_buf_type bufType);
448 
449     // Returns the preferred V4L2 input formats for |type| or empty if none.
450     std::vector<uint32_t> preferredInputFormat(Type type);
451 
452     // NOTE: The below methods to query capabilities have a side effect of closing the
453     // previously-open device, if any, and should not be called after Open().
454 
455     // Get minimum and maximum resolution for fourcc |pixelFormat| and store to |minResolution| and
456     // |maxResolution|.
457     void getSupportedResolution(uint32_t pixelFormat, ui::Size* minResolution,
458                                 ui::Size* maxResolution);
459 
460     // Queries supported levels for |pixFmt| pixel format
461     std::vector<C2Config::level_t> queryC2Levels(uint32_t pixFmt);
462 
463     // Queries supported profiles for |pixFmt| pixel format
464     std::vector<C2Config::profile_t> queryC2Profiles(uint32_t pixFmt);
465 
466     // Queries supported pixel format for a |bufType| queue type
467     std::vector<uint32_t> enumerateSupportedPixelformats(v4l2_buf_type bufType);
468 
469     // Queries supported levels for |videoCodecType|
470     std::vector<C2Config::level_t> enumerateSupportedDecodeLevels(VideoCodec videoCodecType);
471 
472     // Start polling on this V4L2Device. |eventCallback| will be posted to the caller's sequence if
473     // a buffer is ready to be dequeued and/or a V4L2 event has been posted. |errorCallback| will
474     // be posted to the client's
475     // sequence if a polling error has occurred.
476     bool startPolling(scoped_refptr<::base::SequencedTaskRunner> taskRunner,
477                       android::V4L2DevicePoller::EventCallback eventCallback,
478                       ::base::RepeatingClosure errorCallback);
479     // Stop polling this V4L2Device if polling was active. No new events will be posted after this
480     // method has returned.
481     bool stopPolling();
482     // Schedule a polling event if polling is enabled. This method is intended to be called from
483     // V4L2Queue, clients should not need to call it directly.
484     void schedulePoll();
485 
486     // Check whether the V4L2 control with specified |ctrlId| is supported.
487     bool isCtrlExposed(uint32_t ctrlId);
488     // Set the specified list of |ctrls| for the specified |ctrlClass|, returns whether the
489     // operation succeeded.
490     bool setExtCtrls(uint32_t ctrlClass, std::vector<V4L2ExtCtrl> ctrls);
491 
492     // Check whether the V4L2 command with specified |commandId| is supported.
493     bool isCommandSupported(uint32_t commandId);
494     // Check whether the V4L2 device has the specified |capabilities|.
495     bool hasCapabilities(uint32_t capabilities);
496 
497     // Returns identifier used for debugging purposes.
getDebugStreamId()498     uint32_t getDebugStreamId() { return mDebugStreamId; }
499 
500 private:
501     // Vector of video device node paths and corresponding pixelformats supported by each device node.
502     using DeviceInfos = std::vector<std::pair<std::string, std::vector<uint32_t>>>;
503 
504     // Enumerate all V4L2 devices on the system for |type| and return them
505     static const DeviceInfos& getDeviceInfosForType(V4L2Device::Type type);
506 
507     friend class ::base::RefCountedThreadSafe<V4L2Device>;
508     V4L2Device(uint32_t debugStreamId);
509     ~V4L2Device();
510 
511     V4L2Device(const V4L2Device&) = delete;
512     V4L2Device& operator=(const V4L2Device&) = delete;
513 
514     SupportedProfiles enumerateSupportedProfiles(V4L2Device::Type type,
515                                                  const std::vector<uint32_t>& pixelFormats);
516 
517     // Open device node for |path| as a device of |type|.
518     bool openDevicePath(const std::string& path, Type type);
519 
520     // Close the currently open device.
521     void closeDevice();
522 
523     // Return device node path for device of |type| supporting |pixFmt|, or an empty string if the
524     // given combination is not supported by the system.
525     std::string getDevicePathFor(V4L2Device::Type type, uint32_t pixFmt);
526 
527     // Callback that is called upon a queue's destruction, to cleanup its pointer in mQueues.
528     void onQueueDestroyed(v4l2_buf_type buf_type);
529 
530     // Identifier used for debugging purposes.
531     uint32_t mDebugStreamId;
532 
533     // The actual device fd.
534     ::base::ScopedFD mDeviceFd;
535 
536     // eventfd fd to signal device poll thread when its poll() should be interrupted.
537     ::base::ScopedFD mDevicePollInterruptFd;
538 
539     // Associates a v4l2_buf_type to its queue.
540     ::base::flat_map<enum v4l2_buf_type, V4L2Queue*> mQueues;
541 
542     // Used if EnablePolling() is called to signal the user that an event happened or a buffer is
543     // ready to be dequeued.
544     std::unique_ptr<android::V4L2DevicePoller> mDevicePoller;
545 
546     SEQUENCE_CHECKER(mClientSequenceChecker);
547 };
548 
549 }  // namespace android
550 
551 #endif  // ANDROID_V4L2_CODEC2_V4L2_V4L2_DEVICE_H
552