1 // Copyright (c) 2010 The Chromium OS 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 #ifndef MEDIA_V4L2_DEVICE_H_ 6 #define MEDIA_V4L2_DEVICE_H_ 7 8 #include <errno.h> 9 #include <fcntl.h> 10 #include <linux/videodev2.h> 11 #include <malloc.h> 12 #include <stdint.h> 13 #include <stdio.h> 14 #include <stdlib.h> 15 #include <string.h> 16 #include <sys/ioctl.h> 17 #include <sys/mman.h> 18 #include <unistd.h> 19 20 class V4L2Device { 21 public: 22 enum IOMethod { 23 IO_METHOD_READ, 24 IO_METHOD_MMAP, 25 IO_METHOD_USERPTR, 26 }; 27 28 struct Buffer { 29 void* start; 30 size_t length; 31 }; 32 33 V4L2Device(const char* dev_name, 34 IOMethod io, 35 uint32_t buffers); ~V4L2Device()36 virtual ~V4L2Device() {} 37 38 virtual bool OpenDevice(); 39 virtual void CloseDevice(); 40 virtual bool InitDevice(uint32_t width, 41 uint32_t height, 42 uint32_t pixfmt, 43 uint32_t fps); 44 virtual bool UninitDevice(); 45 virtual bool StartCapture(); 46 virtual bool StopCapture(); 47 virtual bool Run(uint32_t frames, uint32_t time_in_sec = 0); 48 49 // Helper methods. 50 bool EnumInput(); 51 bool EnumStandard(); 52 bool EnumControl(bool show_menu = true); 53 bool EnumControlMenu(const v4l2_queryctrl& query_ctrl); 54 bool EnumFormat(uint32_t* num_formats, bool show_fmt = true); 55 bool EnumFrameSize(uint32_t pixfmt, bool show_frmsize = true); 56 57 bool QueryControl(uint32_t id, v4l2_queryctrl* ctrl); 58 bool SetControl(uint32_t id, int32_t value); 59 bool ProbeCaps(v4l2_capability* cap, bool show_caps = false); 60 bool GetCropCap(v4l2_cropcap* cropcap); 61 bool GetCrop(v4l2_crop* crop); 62 bool SetCrop(v4l2_crop* crop); 63 bool GetParam(v4l2_streamparm* param); 64 bool SetParam(v4l2_streamparm* param); 65 bool SetFrameRate(uint32_t fps); 66 uint32_t GetPixelFormat(uint32_t index); 67 uint32_t GetFrameRate(); 68 bool Stop(); 69 70 // Getter. GetActualWidth()71 int32_t GetActualWidth() { 72 return width_; 73 } 74 GetActualHeight()75 int32_t GetActualHeight() { 76 return height_; 77 } 78 GetActualPixelFormat()79 v4l2_format& GetActualPixelFormat() { 80 return pixfmt_; 81 } 82 83 static uint32_t MapFourCC(const char* fourcc); 84 85 virtual void ProcessImage(const void* p); 86 87 private: 88 int32_t DoIoctl(int32_t request, void* arg); 89 int32_t ReadOneFrame(); 90 bool InitReadIO(uint32_t buffer_size); 91 bool InitMmapIO(); 92 bool InitUserPtrIO(uint32_t buffer_size); 93 bool AllocateBuffer(uint32_t buffer_count); 94 bool FreeBuffer(); 95 uint64_t Now(); 96 97 const char* dev_name_; 98 IOMethod io_; 99 int32_t fd_; 100 Buffer* v4l2_buffers_; 101 uint32_t num_buffers_; // Actual buffers allocation. 102 uint32_t min_buffers_; // Minimum buffers requirement. 103 bool stopped_; 104 105 // Valid only after |InitDevice()|. 106 uint32_t width_, height_; 107 v4l2_format pixfmt_; 108 }; 109 110 #endif // MEDIA_V4L2_DEVICE_H_ 111 112