Video for linux 2 example (v4l2 demo)
V4L2 API講解附demo
(注:從他人部落格整理修正而來)
(看完本文後,更簡便的api請移步至video for linux 2 API)
1. 定義
V4L2(Video For Linux Two) 是核心提供給應用程式訪問音、視訊驅動的統一介面。
2. 工作流程:
開啟裝置-> 檢查和設定裝置屬性-> 設定幀格式-> 設定一種輸入輸出方法(緩衝 區管理)-> 迴圈獲取資料-> 關閉裝置。
3. 裝置的開啟和關閉:
#include <fcntl.h>
int open(const char *device_name, int flags);
#include <unistd.h>
int clo se(int fd);
例:
int fd=open(“/dev/video0”,O_RDWR); // 開啟裝置
close(fd); // 關閉裝置
注意:V4L2 的相關定義包含在標頭檔案<linux/videodev2.h> 中.
4. 查詢裝置屬性: VIDIOC_QUERYCAP
相關函式:
int ioctl(int fd, int request, struct v4l2_capability *argp);
相關結構體:
struct v4l2_capability
{
u8 driver[16]; // 驅動名字
u8 card[32]; // 裝置名字
u8 bus_info[32]; // 裝置在系統中的位置
u32 version; // 驅動版本號
u32 capabilities; // 裝置支援的操作
u32 reserved[4]; // 保留欄位
};
capabilities 常用值:
V4L2_CAP_VIDEO_CAPTURE // 是否支援影像獲取
例:顯示裝置資訊
struct v4l2_capability cap;
ioctl(fd,VIDIOC_QUERYCAP,&cap);
printf(“Driver Name:%s\nCard Name:%s\nBus info:%s\nDriver Version:%u.%u.%u\n”,cap.driver,cap.card,cap.bus_info,(cap.version>>16)&0XFF, (cap.version>>8)&0XFF,cap.version&0XFF);
5. 設定視訊的制式和幀格式
制式包括PAL,NTSC,幀的格式個包括寬度和高度等。
相關函式:
int ioctl(int fd, int request, struct v4l2_fmtdesc *argp);
int ioctl(int fd, int request, struct v4l2_format *argp);
相關結構體:
v4l2_cropcap 結構體用來設定攝像頭的捕捉能力,在捕捉上視訊時應先先設定
v4l2_cropcap 的 type 域,再通過 VIDIO_CROPCAP 操作命令獲取裝置捕捉能力的引數,儲存於 v4l2_cropcap 結構體中,包括 bounds(最大捕捉方框的左上角座標和寬高),defrect
(預設捕捉方框的左上角座標和寬高)等。
v4l2_format 結構體用來設定攝像頭的視訊制式、幀格式等,在設定這個引數時應先填 好 v4l2_format 的各個域,如 type(傳輸流型別),fmt.pix.width(寬),
fmt.pix.heigth(高),fmt.pix.field(取樣區域,如隔行取樣),fmt.pix.pixelformat(採
樣型別,如 YUV4:2:2),然後通過 VIDIO_S_FMT 操作命令設定視訊捕捉格式。如下圖所示:
5.1 查詢並顯示所有支援的格式:VIDIOC_ENUM_FMT
相關函式:
int ioctl(int fd, int request, struct v4l2_fmtdesc *argp);
相關結構體:
struct v4l2_fmtdesc
{
u32 index; // 要查詢的格式序號,應用程式設定
enum v4l2_buf_type type; // 幀型別,應用程式設定
u32 flags; // 是否為壓縮格式
u8 description[32]; // 格式名稱
u32 pixelformat; // 格式
u32 reserved[4]; // 保留
};
例:顯示所有支援的格式
struct v4l2_fmtdesc fmtdesc; fmtdesc.index=0; fmtdesc.type=V4L2_BUF_TYPE_VIDEO_CAPTURE; printf("Support format:\n");
while(ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc) != -1)
{
printf("\t%d.%s\n",fmtdesc.index+1,fmtdesc.description);
fmtdesc.index++;
}
5.2 檢視或設定當前格式: VIDIOC_G_FMT, VIDIOC_S_FMT
檢查是否支援某種格式:VIDIOC_TRY_FMT
相關函式:
int ioctl(int fd, int request, struct v4l2_format *argp);
相關結構體:
struct v4l2_format
{
enum v4l2_buf_type type; // 幀型別,應用程式設定
union fmt
{
struct v4l2_pix_format pix; // 視訊裝置使用
struct v4l2_window win;
struct v4l2_vbi_format vbi;
struct v4l2_sliced_vbi_format sliced;
u8 raw_data[200];
};
};
struct v4l2_pix_format
{
u32 width; // 幀寬,單位畫素
u32 height; // 幀高,單位畫素
u32 pixelformat; // 幀格式
enum v4l2_field field;
u32 bytesperline;
u32 sizeimage;
enum v4l2_colorspace colorspace;
u32 priv;
};
例:顯示當前幀的相關資訊
struct v4l2_format fmt;
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ioctl(fd, VIDIOC_G_FMT, &fmt);
printf(“Current data format information:\n\twidth:%d\n\theight:%d\n”, fmt.fmt.pix.width,fmt.fmt.pix.height);
struct v4l2_fmtdesc fmtdesc;
fmtdesc.index = 0;
fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
while(ioctl(fd,VIDIOC_ENUM_FMT,&fmtdesc) != -1)
{
if(fmtdesc.pixelformat & fmt.fmt.pix.pixelformat)
{
printf(“\tformat:%s\n”,fmtdesc.description);
break;
}
fmtdesc.index++;
}
例:檢查是否支援某種幀格式
struct v4l2_format fmt;
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB32;
if(ioctl(fd,VIDIOC_TRY_FMT,&fmt) == -1)
{
if(errno==EINVAL)
{
printf(“not support format RGB32!\n”);
}
}
6. 影像的縮放 VIDIOC_CROPCAP
相關函式:
int ioctl(int fd, int request, struct v4l2_cropcap *argp);
int ioctl(int fd, int request, struct v4l2_crop *argp);
int ioctl(int fd, int request, const struct v4l2_crop *argp);
相關結構體:
v4l2_cropcap 結構體用來設定攝像頭的捕捉能力,在捕捉上視訊時應先先設定v4l2_cropcap 的 type 域,再通過 VIDIO_CROPCAP 操作命令獲取裝置捕捉能力的引數,儲存於 v4l2_cropcap 結構體中,包括 bounds(最大捕捉方框的左上角座標和寬高),defrect(預設捕捉方框的左上角座標和寬高)等。
Cropping 和 scaling 主要指的是影像的取景範圍及圖片的比例縮放的支援。Crop 就 是把得到的資料作一定的裁剪和伸縮,裁剪可以只取樣我們可以得到的影像大小的一部分, 剪裁的主要引數是位置、長度、寬度。而 scale 的設定是通過 VIDIOC_G_FMT 和 VIDIOC_S_FMT 來獲得和設定當前的 image 的長度,寬度來實現的。看下圖
我們可以假設 bounds 是 sensor 最大能捕捉到的影像範圍,而 defrect 是裝置預設 的最大取樣範圍,這個可以通過 VIDIOC_CROPCAP 的 ioctl 來獲得裝置的 crap 相關的屬 性 v4l2_cropcap,其中的 bounds 就是這個 bounds,其實就是上限。每個裝置都有個默 認的取樣範圍,就是 defrect,就是 default rect 的意思,它比 bounds 要小一些。這 個範圍也是通過 VIDIOC_CROPCAP 的 ioctl 來獲得的 v4l2_cropcap 結構中的 defrect 來表示的,我們可以通過 VIDIOC_G_CROP 和 VIDIOC_S_CROP 來獲取和設定裝置當前的 crop 設定。
6.1 設定裝置捕捉能力的引數
相關函式:
int ioctl(int fd, int request, struct v4l2_cropcap *argp);
相關結構體:
struct v4l2_cropcap
{
enum v4l2_buf_type type; // 資料流的型別,應用程式設定
struct v4l2_rect bounds; // 這是 camera 的鏡頭能捕捉到的視窗大小的侷限
struct v4l2_rect defrect; // 定義預設視窗大小,包括起點位置及長,寬的大小,大小以畫素為單位
struct v4l2_fract pixelaspect; // 定義了圖片的寬高比
};
6.2 設定視窗取景引數 VIDIOC_G_CROP 和 VIDIOC_S_CROP
相關函式:
int ioctl(int fd, int request, struct v4l2_crop *argp);
int ioctl(int fd, int request, const struct v4l2_crop *argp);
相關結構體:
struct v4l2_crop
{
enum v4l2_buf_type type;// 應用程式設定
struct v4l2_rect c;
}
7.video Inputs and Outputs
VIDIOC_G_INPUT 和 VIDIOC_S_INPUT 用來查詢和選則當前的 input,一個 video 裝置 節點可能對應多個視訊源,比如 saf7113 可以最多支援四路 cvbs 輸入,如果上層想在四 個cvbs視訊輸入間切換,那麼就要呼叫 ioctl(fd, VIDIOC_S_INPUT, &input) 來切換。VIDIOC_G_INPUT and VIDIOC_G_OUTPUT 返回當前的 video input和output的index.
相關函式:
int ioctl(int fd, int request, struct v4l2_input *argp);
相關結構體:
struct v4l2_input
{
__u32 index; /* Which input */
__u8 name[32]; /* Label */
__u32 type; /* Type of input */
__u32 audioset; /* Associated audios (bitfield) */
__u32 tuner; /* Associated tuner */
v4l2_std_id std;
__u32 status;
__u32 reserved[4];
};
我們可以通過VIDIOC_ENUMINPUT and VIDIOC_ENUMOUTPUT 分別列舉一個input或者 output的資訊,我們使用一個v4l2_input結構體來存放查詢結果,這個結構體中有一個 index域用來指定你索要查詢的是第幾個input/ouput,如果你所查詢的這個input是當前正 在使用的,那麼在v4l2_input還會包含一些當前的狀態資訊,如果所 查詢的input/output 不存在,那麼回返回EINVAL錯誤,所以,我們通過迴圈查詢,直到返回錯誤來遍歷所有的 input/output. VIDIOC_G_INPUT and VIDIOC_G_OUTPUT 返回當前的video input和output 的index.
例: 列舉當前輸入視訊所支援的視訊格式
struct v4l2_input input;
struct v4l2_standard standard;
memset (&input, 0, sizeof (input));
//首先獲得當前輸入的 index,注意只是 index,要獲得具體的資訊,就的呼叫列舉操作
if (-1 == ioctl (fd, VIDIOC_G_INPUT, &input.index))
{
perror (”VIDIOC_G_INPUT”);
exit (EXIT_FAILURE);
}
//呼叫列舉操作,獲得 input.index 對應的輸入的具體資訊
if (-1 == ioctl (fd, VIDIOC_ENUMINPUT, &input))
{
perror (”VIDIOC_ENUM_INPUT”);
exit (EXIT_FAILURE);
}
printf (”Current input %s supports:\n”, input.name); memset (&standard, 0, sizeof (standard)); standard.index = 0;
//列舉所有的所支援的 standard,如果 standard.id 與當前 input 的 input.std 有共同的
//bit flag,意味著當前的輸入支援這個 standard,這樣將所有驅動所支援的 standard 列舉一個
//遍,就可以找到該輸入所支援的所有 standard 了。
while (0 == ioctl (fd, VIDIOC_ENUMSTD, &standard))
{
if (standard.id & input.std)
printf (”%s\n”, standard.name);
standard.index++;
}
/* EINVAL indicates the end of the enumeration, which cannot be empty unless this device falls under the USB exception. */
if (errno != EINVAL || standard.index == 0)
{
perror (”VIDIOC_ENUMSTD”);
exit (EXIT_FAILURE);
}
8. Video standards
相關函式:
v4l2_std_id std_id; //這個就是個64bit得數
int ioctl(int fd, int request, struct v4l2_standard *argp);
相關結構體:
typedef u64 v4l2_std_id;
struct v4l2_standard
{
u32 index;
v4l2_std_id id;
u8 name[24];
struct v4l2_fract frameperiod; /* Frames, not fields */
u32 framelines;
u32 reserved[4];
};
當然世界上現在有多個視訊標準,如NTSC和PAL,他們又細分為好多種,那麼我們的設 備輸入/輸出究竟支援什麼樣的標準呢?我們的當前在使用的輸入和輸出正在使用的是哪 個標準呢?我們怎麼設定我們的某個輸入輸出使用的標準呢?這都是有方法的。
查詢我們的輸入支援什麼標準,首先就得找到當前的這個輸入的index,然後查出它的 屬性,在其屬性裡面可以得到該輸入所支援的標準,將它所支援的各個標準與所有的標準 的資訊進行比較,就可以獲知所支援的各個標準的屬性。一個輸入所支援的標準應該是一 個集合,而這個集合是用bit與的方式用一個64位數字表示。因此我們所查到的是一個數字。
Example: Information about the current video standard v4l2_std_id std_id; //這個就是個64bit得數
struct v4l2_standard standard;
// VIDIOC_G_STD就是獲得當前輸入使用的standard,不過這裡只是得到了該標準的id
// 即flag,還沒有得到其具體的屬性資訊,具體的屬性資訊要通過列舉操作來得到。
if (-1 == ioctl (fd, VIDIOC_G_STD, &std_id))
{
perror (”VIDIOC_G_STD”);
exit (EXIT_FAILURE);
//獲得了當前輸入使用的standard
// Note when VIDIOC_ENUMSTD always returns EINVAL this is no video device
// or it falls under the USB exception, and VIDIOC_G_STD returning EINVAL
// is no error.
}
memset (&standard, 0, sizeof (standard));
standard.index = 0; //從第一個開始列舉
// VIDIOC_ENUMSTD用來列舉所支援的所有的video標準的資訊,不過要先給standard
// 結構的index域制定一個數值,所列舉的標 準的資訊屬性包含在standard裡面,
// 如果我們所列舉的標準和std_id有共同的bit,那麼就意味著這個標準就是當前輸
// 入所使用的標準,這樣我們就得到了當前輸入使用的標準的屬性資訊
while (0 == ioctl (fd, VIDIOC_ENUMSTD, &standard))
{
if (standard.id & std_id)
{
printf (”Current video standard: %s\n”, standard.name);
exit (EXIT_SUCCESS);
}
standard.index++;
}
/* EINVAL indicates the end of the enumeration, which cannot be empty unless this device falls under the USB exception. */
if (errno == EINVAL || standard.index == 0)
{
perror (”VIDIOC_ENUMSTD”);
exit (EXIT_FAILURE);
}
9. 申請和管理緩衝區
應用程式和裝置有三種交換資料的方法,直接 read/write、記憶體對映(memory mapping)
和使用者指標。這裡只討論記憶體對映(memory mapping)。
9.1 向裝置申請緩衝區 VIDIOC_REQBUFS
相關函式:
int ioctl(int fd, int request, struct v4l2_requestbuffers *argp);
相關結構體:
struct v4l2_requestbuffers
{
u32 count; // 緩衝區內緩衝幀的數目
enum v4l2_buf_type type; // 緩衝幀資料格式
enum v4l2_memory memory; // 區別是記憶體對映還是使用者指標方式
u32 reserved[2];
};
注:
enum v4l2_memoy
{
V4L2_MEMORY_MMAP, V4L2_MEMORY_USERPTR
};
//count,type,memory 都要應用程式設定
例:申請一個擁有四個緩衝幀的緩衝區
struct v4l2_requestbuffers req;
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
ioctl(fd,VIDIOC_REQBUFS,&req);
9.2 獲取緩衝幀的地址,長度:VIDIOC_QUERYBUF
相關函式:
int ioctl(int fd, int request, struct v4l2_buffer *argp);
相關結構體:
struct v4l2_buffer
{
u32 index; //buffer 序號
enum v4l2_buf_type type; //buffer 型別
u32 byteused; //buffer 中已使用的位元組數
u32 flags; // 區分是MMAP 還是USERPTR
enum v4l2_field field;
struct timeval timestamp; // 獲取第一個位元組時的系統時間
struct v4l2_timecode timecode;
u32 sequence; // 佇列中的序號
enum v4l2_memory memory; //IO 方式,被應用程式設定
union m
{
u32 offset; // 緩衝幀地址,只對MMAP 有效
unsigned long userptr;
};
u32 length; // 緩衝幀長度
u32 input;
u32 reserved;
};
9.3 記憶體對映MMAP 及定義一個結構體來對映每個緩衝幀。 相關結構體:
struct buffer
{
void* start;
unsigned int length;
}*buffers;
相關函式:
#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
//addr 對映起始地址,一般為NULL ,讓核心自動選擇
//length 被對映記憶體塊的長度
//prot 標誌對映後能否被讀寫,其值為PROT_EXEC,PROT_READ,PROT_WRITE, PROT_NONE
//flags 確定此記憶體對映能否被其他程式共享,MAP_SHARED,MAP_PRIVATE
//fd,offset, 確定被對映的記憶體地址 返回成功對映後的地址,不成功返回MAP_FAILED ((void*)-1)
相關函式:
int munmap(void *addr, size_t length);// 斷開對映
//addr 為對映後的地址,length 為對映後的記憶體長度
例:將四個已申請到的緩衝幀對映到應用程式,用buffers 指標記錄。
buffers = (buffer*)calloc (req.count, sizeof (*buffers));
if (!buffers)
{
// 對映
fprintf (stderr, "Out of memory/n");
exit (EXIT_FAILURE);
}
for (unsigned int n_buffers = 0; n_buffers < req.count; ++n_buffers)
{
struct v4l2_buffer buf;
memset(&buf,0,sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
// 查詢序號為n_buffers 的緩衝區,得到其起始實體地址和大小
if (-1 == ioctl (fd, VIDIOC_QUERYBUF, &buf))
{
exit(-1);
}
buffers[n_buffers].length = buf.length;
// 對映記憶體
buffers[n_buffers].start = mmap (NULL,buf.length,PROT_READ | PROT_WRITE ,MAP_SHARED,fd, buf.m.offset);
if (MAP_FAILED == buffers[n_buffers].start)
{
exit(-1);
}
}
10. 緩衝區處理好之後,就可以開始獲取資料了
10.1 啟動 或 停止資料流 VIDIOC_STREAMON, VIDIOC_STREAMOFF
int ioctl(int fd, int request, const int *argp);
//argp 為流型別指標,如V4L2_BUF_TYPE_VIDEO_CAPTURE.
10.2 在開始之前,還應當把緩衝幀放入緩衝佇列:
VIDIOC_QBUF// 把幀放入佇列
VIDIOC_DQBUF// 從佇列中取出幀
int ioctl(int fd, int request, struct v4l2_buffer *argp);
例:把四個緩衝幀放入佇列,並啟動資料流
unsigned int i;
enum v4l2_buf_type type;
for (i = 0; i < 4; ++i) // 將緩衝幀放入佇列
{
struct v4l2_buffer buf;
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
ioctl (fd, VIDIOC_QBUF, &buf);
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ioctl (fd, VIDIOC_STREAMON, &type);
// 這有個問題,這些buf 看起來和前面申請的buf 沒什麼關係,為什麼呢?
例:獲取一幀並處理
struct v4l2_buffer buf; CLEAR (buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
ioctl (fd, VIDIOC_DQBUF, &buf); // 從緩衝區取出一個緩衝幀
process_image (buffers[buf.index.]start); //
ioctl (fdVIDIOC_QBUF&buf); //
附官方 v4l2 video capture example
/*
* V4L2 video capture example
*
* This program can be used and distributed without restrictions.
*
* This program is provided with the V4L2 API
* see http://linuxtv.org/docs.php for more information
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h> /* getopt_long() */
#include <fcntl.h> /* low-level i/o */
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#define CLEAR(x) memset(&(x), 0, sizeof(x))
enum io_method {
IO_METHOD_READ,
IO_METHOD_MMAP,
IO_METHOD_USERPTR,
};
struct buffer {
void *start;
size_t length;
};
static char *dev_name;
static enum io_method io = IO_METHOD_MMAP;
static int fd = -1;
struct buffer *buffers;
static unsigned int n_buffers;
static int out_buf;
static int force_format;
static int frame_count = 70;
/*
*
*
*
*
*/
static void errno_exit(const char *s)
{
fprintf(stderr, "%s error %d, %s\n", s, errno, strerror(errno));
exit(EXIT_FAILURE);
}
static int xioctl(int fh, int request, void *arg)
{
int r;
do {
r = ioctl(fh, request, arg);
} while (-1 == r && EINTR == errno);
return r;
}
static void process_image(const void *p, int size)
{
if (out_buf)
fwrite(p, size, 1, stdout);
fflush(stderr);
fprintf(stderr, ".");
fflush(stdout);
}
static int read_frame(void)
{
struct v4l2_buffer buf;
unsigned int i;
switch (io) {
case IO_METHOD_READ:
if (-1 == read(fd, buffers[0].start, buffers[0].length)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("read");
}
}
process_image(buffers[0].start, buffers[0].length);
break;
case IO_METHOD_MMAP:
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("VIDIOC_DQBUF");
}
}
assert(buf.index < n_buffers);
process_image(buffers[buf.index].start, buf.bytesused);
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
break;
case IO_METHOD_USERPTR:
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_USERPTR;
if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("VIDIOC_DQBUF");
}
}
for (i = 0; i < n_buffers; ++i)
if (buf.m.userptr == (unsigned long)buffers[i].start
&& buf.length == buffers[i].length)
break;
assert(i < n_buffers);
process_image((void *)buf.m.userptr, buf.bytesused);
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
break;
}
return 1;
}
/* two operations
* step1 : delay
* step2 : read frame
*/
static void mainloop(void)
{
unsigned int count;
count = frame_count;
while (count-- > 0) {
for (;;) {
fd_set fds;
struct timeval tv;
int r;
FD_ZERO(&fds);
FD_SET(fd, &fds);
/* Timeout. */
tv.tv_sec = 2;
tv.tv_usec = 0;
r = select(fd + 1, &fds, NULL, NULL, &tv);
if (-1 == r) {
if (EINTR == errno)
continue;
errno_exit("select");
}
if (0 == r) {
fprintf(stderr, "select timeout\n");
exit(EXIT_FAILURE);
}
if (read_frame())
break;
/* EAGAIN - continue select loop. */
}
}
}
/*
* one operation
* step1 : VIDIOC_STREAMOFF
*/
static void stop_capturing(void)
{
enum v4l2_buf_type type;
switch (io) {
case IO_METHOD_READ:
/* Nothing to do. */
break;
case IO_METHOD_MMAP:
case IO_METHOD_USERPTR:
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (-1 == xioctl(fd, VIDIOC_STREAMOFF, &type))
errno_exit("VIDIOC_STREAMOFF");
break;
}
}
/* tow operations
* step1 : VIDIOC_QBUF(insert buffer to queue)
* step2 : VIDIOC_STREAMOFF
*/
static void start_capturing(void)
{
unsigned int i;
enum v4l2_buf_type type;
switch (io) {
case IO_METHOD_READ:
/* Nothing to do. */
break;
case IO_METHOD_MMAP:
for (i = 0; i < n_buffers; ++i) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
errno_exit("VIDIOC_STREAMON");
break;
case IO_METHOD_USERPTR:
for (i = 0; i < n_buffers; ++i) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_USERPTR;
buf.index = i;
buf.m.userptr = (unsigned long)buffers[i].start;
buf.length = buffers[i].length;
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
errno_exit("VIDIOC_STREAMON");
break;
}
}
/* two operations
* step1 : munmap buffers
* steo2 : free buffers
*/
static void uninit_device(void)
{
unsigned int i;
switch (io) {
case IO_METHOD_READ:
free(buffers[0].start);
break;
case IO_METHOD_MMAP:
for (i = 0; i < n_buffers; ++i)
if (-1 == munmap(buffers[i].start, buffers[i].length))
errno_exit("munmap");
break;
case IO_METHOD_USERPTR:
for (i = 0; i < n_buffers; ++i)
free(buffers[i].start);
break;
}
free(buffers);
}
static void init_read(unsigned int buffer_size)
{
buffers = calloc(1, sizeof(*buffers));
if (!buffers) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
buffers[0].length = buffer_size;
buffers[0].start = malloc(buffer_size);
if (!buffers[0].start) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
}
static void init_mmap(void)
{
struct v4l2_requestbuffers req;
CLEAR(req);
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
if (EINVAL == errno) {
fprintf(stderr, "%s does not support "
"memory mapping\n", dev_name);
exit(EXIT_FAILURE);
} else {
errno_exit("VIDIOC_REQBUFS");
}
}
if (req.count < 2) {
fprintf(stderr, "Insufficient buffer memory on %s\n",
dev_name);
exit(EXIT_FAILURE);
}
buffers = calloc(req.count, sizeof(*buffers));
if (!buffers) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
errno_exit("VIDIOC_QUERYBUF");
buffers[n_buffers].length = buf.length;
buffers[n_buffers].start =
mmap(NULL /* start anywhere */,
buf.length,
PROT_READ | PROT_WRITE /* required */,
MAP_SHARED /* recommended */,
fd, buf.m.offset);
if (MAP_FAILED == buffers[n_buffers].start)
errno_exit("mmap");
}
}
static void init_userp(unsigned int buffer_size)
{
struct v4l2_requestbuffers req;
CLEAR(req);
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_USERPTR;
if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
if (EINVAL == errno) {
fprintf(stderr, "%s does not support "
"user pointer i/o\n", dev_name);
exit(EXIT_FAILURE);
} else {
errno_exit("VIDIOC_REQBUFS");
}
}
buffers = calloc(4, sizeof(*buffers));
if (!buffers) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
for (n_buffers = 0; n_buffers < 4; ++n_buffers) {
buffers[n_buffers].length = buffer_size;
buffers[n_buffers].start = malloc(buffer_size);
if (!buffers[n_buffers].start) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
}
}
/* five operations
* step1 : cap :query camera's capability and check it(is a video device? is it support read? is it support streaming?)
* step2 : cropcap:set cropcap's type and get cropcap by VIDIOC_CROPCAP
* step3 : set crop parameter by VIDIOC_S_CROP (such as frame type and angle)
* step4 : set fmt
* step5 : mmap
*/
static void init_device(void)
{
struct v4l2_capability cap;
struct v4l2_cropcap cropcap;
struct v4l2_crop crop;
struct v4l2_format fmt;
unsigned int min;
if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) {
if (EINVAL == errno) {
fprintf(stderr, "%s is no V4L2 device\n",
dev_name);
exit(EXIT_FAILURE);
} else {
errno_exit("VIDIOC_QUERYCAP");
}
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
fprintf(stderr, "%s is no video capture device\n",
dev_name);
exit(EXIT_FAILURE);
}
switch (io) {
case IO_METHOD_READ:
if (!(cap.capabilities & V4L2_CAP_READWRITE)) {
fprintf(stderr, "%s does not support read i/o\n",
dev_name);
exit(EXIT_FAILURE);
}
break;
case IO_METHOD_MMAP:
case IO_METHOD_USERPTR:
if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
fprintf(stderr, "%s does not support streaming i/o\n",
dev_name);
exit(EXIT_FAILURE);
}
break;
}
/* Select video input, video standard and tune here. */
CLEAR(cropcap);
cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
/* if device support cropcap's type then set crop */
if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap)) {
crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop.c = cropcap.defrect; /* reset to default */
if (-1 == xioctl(fd, VIDIOC_S_CROP, &crop)) {
switch (errno) {
case EINVAL:
/* Cropping not supported. */
break;
default:
/* Errors ignored. */
break;
}
}
} else {
/* Errors ignored. */
}
CLEAR(fmt);
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (force_format) {
fmt.fmt.pix.width = 640;
fmt.fmt.pix.height = 480;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt))
errno_exit("VIDIOC_S_FMT");
/* Note VIDIOC_S_FMT may change width and height. */
} else {
/* Preserve original settings as set by v4l2-ctl for example */
if (-1 == xioctl(fd, VIDIOC_G_FMT, &fmt))
errno_exit("VIDIOC_G_FMT");
}
/* Buggy driver paranoia. */
min = fmt.fmt.pix.width * 2;
if (fmt.fmt.pix.bytesperline < min)
fmt.fmt.pix.bytesperline = min;
min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
if (fmt.fmt.pix.sizeimage < min)
fmt.fmt.pix.sizeimage = min;
switch (io) {
case IO_METHOD_READ:
init_read(fmt.fmt.pix.sizeimage);
break;
case IO_METHOD_MMAP:
init_mmap();
break;
case IO_METHOD_USERPTR:
init_userp(fmt.fmt.pix.sizeimage);
break;
}
}
/*
* close (fd)
*/
static void close_device(void)
{
if (-1 == close(fd))
errno_exit("close");
fd = -1;
}
/* three operations
* step 1 : check dev_name and st_mode
* step 2 : open(device)
*/
static void open_device(void)
{
struct stat st;
if (-1 == stat(dev_name, &st)) {
fprintf(stderr, "Cannot identify '%s': %d, %s\n",
dev_name, errno, strerror(errno));
exit(EXIT_FAILURE);
}
if (!S_ISCHR(st.st_mode)) {
fprintf(stderr, "%s is no device\n", dev_name);
exit(EXIT_FAILURE);
}
fd = open(dev_name, O_RDWR /* required */ | O_NONBLOCK, 0);
if (-1 == fd) {
fprintf(stderr, "Cannot open '%s': %d, %s\n",
dev_name, errno, strerror(errno));
exit(EXIT_FAILURE);
}
}
static void usage(FILE *fp, int argc, char **argv)
{
fprintf(fp,
"Usage: %s [options]\n\n"
"Version 1.3\n"
"Options:\n"
"-d | --device name Video device name [%s]\n"
"-h | --help Print this message\n"
"-m | --mmap Use memory mapped buffers [default]\n"
"-r | --read Use read() calls\n"
"-u | --userp Use application allocated buffers\n"
"-o | --output Outputs stream to stdout\n"
"-f | --format Force format to 640x480 YUYV\n"
"-c | --count Number of frames to grab [%i]\n"
"",
argv[0], dev_name, frame_count);
}
static const char short_options[] = "d:hmruofc:";
static const struct option
long_options[] = {
{ "device", required_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "mmap", no_argument, NULL, 'm' },
{ "read", no_argument, NULL, 'r' },
{ "userp", no_argument, NULL, 'u' },
{ "output", no_argument, NULL, 'o' },
{ "format", no_argument, NULL, 'f' },
{ "count", required_argument, NULL, 'c' },
{ 0, 0, 0, 0 }
};
int main(int argc, char **argv)
{
dev_name = "/dev/video4";
for (;;) {
int idx;
int c;
c = getopt_long(argc, argv,
short_options, long_options, &idx);
if (-1 == c)
break;
switch (c) {
case 0: /* getopt_long() flag */
break;
case 'd':
dev_name = optarg;
break;
case 'h':
usage(stdout, argc, argv);
exit(EXIT_SUCCESS);
case 'm':
io = IO_METHOD_MMAP;
break;
case 'r':
io = IO_METHOD_READ;
break;
case 'u':
io = IO_METHOD_USERPTR;
break;
case 'o':
out_buf++;
break;
case 'f':
force_format++;
break;
case 'c':
errno = 0;
frame_count = strtol(optarg, NULL, 0);
if (errno)
errno_exit(optarg);
break;
default:
usage(stderr, argc, argv);
exit(EXIT_FAILURE);
}
}
open_device();
init_device();
start_capturing();
mainloop();
stop_capturing();
uninit_device();
close_device();
fprintf(stderr, "\n");
return 0;
}
相關文章
- Linux V4l2簡單使用Linux
- angular 2 by exampleAngular
- V4L2應用程式開發(1)
- Camera | 5.Linux v4l2架構(基於rk3568)Linux架構
- DB2 PL/SQL Example: RunstatsDB2SQL
- 嵌入式Linux驅動筆記(十八)------淺析V4L2框架之ioctlLinux筆記框架
- ffmpeg demo decode_video.c例子流程圖IDE流程圖
- HTML5視訊video開發demo例子HTMLIDE
- DB2 PL/SQL Example: Sleep ProcedureDB2SQL
- Amazing Algorithms with NoSQL: A MongoDB Example Part 2SQLMongoDB
- 嵌入式Linux驅動筆記(十七)------詳解V4L2框架(UVC驅動)Linux筆記框架
- DB2 PL/SQL Example: bonus_increaseDB2SQL
- Spark exampleSpark
- oracle exampleOracle
- Chapter 2. Video Formats and QualityAPTIDEORM
- The Linux USB Video Class (UVC) driverLinuxIDE
- Video4linux 解析(轉)IDELinux
- An example of polybase for OracleOracle
- Oracle By Example (OBE)Oracle
- simd example code
- An example about git hookGitHook
- react router animation exampleReact
- An Example of How Oracle WorksOracle
- [Typescript] Query builder exampleTypeScriptUI
- ENSP Demo2 RIP & static & OSPF
- mvp+rxjava2+retrofit2專案框架demoMVPRxJava框架
- A example that using JQuery clonejQuery
- a simple example for spring AOPSpring
- An Application Context exampleAPPContext
- Example of SQL Linux Windows Authentication configuration using Managed Service AccountsSQLLinuxWindows
- 【RabbitMQ】direct type exchange example in golangMQGolang
- 【RabbitMQ】topic type exchange example in golangMQGolang
- 【RabbitMQ】fanout type exchange example in golangMQGolang
- openni example NiViewer opengl blockViewBloC
- Common threads: Awk by examplethread
- Amazing Algorithms with NoSQL: A MongoDB ExampleSQLMongoDB
- JDBC Connection Pool Example (轉)JDBC
- Bitmap Index Example (223)Index