V4L2 API讲解附demo

(注:从他人博客整理修正而来)

(看完本文后,更简便的api请移步至video for linux 2 API)

1. 定义

V4L2(Video For Linux Two) 是内核提供给应用程序访问音、视频驱动的统一接口。

2. 工作流程:

打开设备-> 检查和设置设备属性-> 设置帧格式-> 设置一种输入输出方法(缓冲 区管理)-> 循环获取数据-> 关闭设备。

3. 设备的打开和关闭:

[cpp] view plaincopy print?
  1. #include <fcntl.h>
  2. int open(const char *device_name, int flags);
  3. #include <unistd.h>
  4. int clo se(int fd);

例:

[cpp] view plaincopy print?
  1. int fd=open(“/dev/video0”,O_RDWR); // 打开设备
  2. close(fd); // 关闭设备

注意:V4L2 的相关定义包含在头文件<linux/videodev2.h> 中.

4. 查询设备属性: VIDIOC_QUERYCAP

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_capability *argp);

相关结构体:

[cpp] view plaincopy print?
  1. struct v4l2_capability
  2. {
  3. u8 driver[16]; // 驱动名字
  4. u8 card[32]; // 设备名字
  5. u8 bus_info[32]; // 设备在系统中的位置
  6. u32 version; // 驱动版本号
  7. u32 capabilities; // 设备支持的操作
  8. u32 reserved[4]; // 保留字段
  9. };

capabilities 常用值:

V4L2_CAP_VIDEO_CAPTURE // 是否支持图像获取

例:显示设备信息

[cpp] view plaincopy print?
  1. struct v4l2_capability cap;
  2. ioctl(fd,VIDIOC_QUERYCAP,&cap);
  3. 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,帧的格式个包括宽度和高度等。

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_fmtdesc *argp);
  2. 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

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_fmtdesc *argp);

相关结构体:

[cpp] view plaincopy print?
  1. struct v4l2_fmtdesc
  2. {
  3. u32 index; // 要查询的格式序号,应用程序设置
  4. enum v4l2_buf_type type; // 帧类型,应用程序设置
  5. u32 flags; // 是否为压缩格式
  6. u8 description[32]; // 格式名称
  7. u32 pixelformat; // 格式
  8. u32 reserved[4]; // 保留
  9. };

例:显示所有支持的格式

[cpp] view plaincopy print?
  1. struct v4l2_fmtdesc fmtdesc; fmtdesc.index=0; fmtdesc.type=V4L2_BUF_TYPE_VIDEO_CAPTURE; printf("Support format:\n");
  2. while(ioctl(fd, VIDIOC_ENUM_FMT, &fmtdesc) != -1)
  3. {
  4. printf("\t%d.%s\n",fmtdesc.index+1,fmtdesc.description);
  5. fmtdesc.index++;
  6. }

5.2 查看或设置当前格式: VIDIOC_G_FMT, VIDIOC_S_FMT

检查是否支持某种格式:VIDIOC_TRY_FMT

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_format *argp);

相关结构体:

[cpp] view plaincopy print?
  1. struct v4l2_format
  2. {
  3. enum v4l2_buf_type type; // 帧类型,应用程序设置
  4. union fmt
  5. {
  6. struct v4l2_pix_format pix; // 视频设备使用
  7. struct v4l2_window win;
  8. struct v4l2_vbi_format vbi;
  9. struct v4l2_sliced_vbi_format sliced;
  10. u8 raw_data[200];
  11. };
  12. };
  13. struct v4l2_pix_format
  14. {
  15. u32 width; // 帧宽,单位像素
  16. u32 height; // 帧高,单位像素
  17. u32 pixelformat; // 帧格式
  18. enum v4l2_field field;
  19. u32 bytesperline;
  20. u32 sizeimage;
  21. enum v4l2_colorspace colorspace;
  22. u32 priv;
  23. };

例:显示当前帧的相关信息

[cpp] view plaincopy print?
  1. struct v4l2_format fmt;
  2. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  3. ioctl(fd, VIDIOC_G_FMT, &fmt);
  4. printf(“Current data format information:\n\twidth:%d\n\theight:%d\n”, fmt.fmt.pix.width,fmt.fmt.pix.height);
  5. struct v4l2_fmtdesc fmtdesc;
  6. fmtdesc.index = 0;
  7. fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  8. while(ioctl(fd,VIDIOC_ENUM_FMT,&fmtdesc) != -1)
  9. {
  10. if(fmtdesc.pixelformat & fmt.fmt.pix.pixelformat)
  11. {
  12. printf(“\tformat:%s\n”,fmtdesc.description);
  13. break;
  14. }
  15. fmtdesc.index++;
  16. }

例:检查是否支持某种帧格式

[cpp] view plaincopy print?
  1. struct v4l2_format fmt;
  2. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  3. fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB32;
  4. if(ioctl(fd,VIDIOC_TRY_FMT,&fmt) == -1)
  5. {
  6. if(errno==EINVAL)
  7. {
  8. printf(“not support format RGB32!\n”);
  9. }
  10. }

6. 图像的缩放 VIDIOC_CROPCAP

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_cropcap *argp);
  2. int ioctl(int fd, int request, struct v4l2_crop *argp);
  3. 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 设置设备捕捉能力的参数

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_cropcap *argp);

相关结构体:

[cpp] view plaincopy print?
  1. struct v4l2_cropcap
  2. {
  3. enum v4l2_buf_type type; // 数据流的类型,应用程序设置
  4. struct v4l2_rect bounds; // 这是 camera 的镜头能捕捉到的窗口大小的局限
  5. struct v4l2_rect defrect; // 定义默认窗口大小,包括起点位置及长,宽的大小,大小以像素为单位
  6. struct v4l2_fract pixelaspect; // 定义了图片的宽高比
  7. };

6.2 设置窗口取景参数 VIDIOC_G_CROP 和 VIDIOC_S_CROP

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_crop *argp);
  2. int ioctl(int fd, int request, const struct v4l2_crop *argp);

相关结构体:

[cpp] view plaincopy print?
  1. struct v4l2_crop
  2. {
  3. enum v4l2_buf_type type;// 应用程序设置
  4. struct v4l2_rect c;
  5. }

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.

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_input *argp);

相关结构体:

[cpp] view plaincopy print?
  1. struct v4l2_input
  2. {
  3. __u32 index;    /* Which input */
  4. __u8 name[32];  /* Label */
  5. __u32 type;     /* Type of input */
  6. __u32 audioset; /* Associated audios (bitfield) */
  7. __u32 tuner;    /* Associated tuner */
  8. v4l2_std_id std;
  9. __u32 status;
  10. __u32 reserved[4];
  11. };

我们可以通过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.

例: 列举当前输入视频所支持的视频格式

[cpp] view plaincopy print?
  1. struct v4l2_input input;
  2. struct v4l2_standard standard;
  3. memset (&input, 0, sizeof (input));
  4. //首先获得当前输入的 index,注意只是 index,要获得具体的信息,就的调用列举操作
  5. if (-1 == ioctl (fd, VIDIOC_G_INPUT, &input.index))
  6. {
  7. perror (”VIDIOC_G_INPUT”);
  8. exit (EXIT_FAILURE);
  9. }
  10. //调用列举操作,获得 input.index 对应的输入的具体信息
  11. if (-1 == ioctl (fd, VIDIOC_ENUMINPUT, &input))
  12. {
  13. perror (”VIDIOC_ENUM_INPUT”);
  14. exit (EXIT_FAILURE);
  15. }
  16. printf (”Current input %s supports:\n”, input.name); memset (&standard, 0, sizeof (standard)); standard.index = 0;
  17. //列举所有的所支持的 standard,如果 standard.id 与当前 input 的 input.std 有共同的
  18. //bit flag,意味着当前的输入支持这个 standard,这样将所有驱动所支持的 standard 列举一个
  19. //遍,就可以找到该输入所支持的所有 standard 了。
  20. while (0 == ioctl (fd, VIDIOC_ENUMSTD, &standard))
  21. {
  22. if (standard.id & input.std)
  23. printf (”%s\n”, standard.name);
  24. standard.index++;
  25. }
  26. /* EINVAL indicates the end of the enumeration, which cannot be empty unless this device falls under the USB exception. */
  27. if (errno != EINVAL || standard.index == 0)
  28. {
  29. perror (”VIDIOC_ENUMSTD”);
  30. exit (EXIT_FAILURE);
  31. }

8. Video standards

相关函数:

[cpp] view plaincopy print?
  1. v4l2_std_id std_id; //这个就是个64bit得数
  2. int ioctl(int fd, int request, struct v4l2_standard *argp);

相关结构体:

[cpp] view plaincopy print?
  1. typedef u64 v4l2_std_id;
  2. struct v4l2_standard
  3. {
  4. u32 index;
  5. v4l2_std_id id;
  6. u8 name[24];
  7. struct v4l2_fract frameperiod; /* Frames, not fields */
  8. u32 framelines;
  9. u32 reserved[4];
  10. };

当然世界上现在有多个视频标准,如NTSC和PAL,他们又细分为好多种,那么我们的设 备输入/输出究竟支持什么样的标准呢?我们的当前在使用的输入和输出正在使用的是哪 个标准呢?我们怎么设置我们的某个输入输出使用的标准呢?这都是有方法的。

查询我们的输入支持什么标准,首先就得找到当前的这个输入的index,然后查出它的 属性,在其属性里面可以得到该输入所支持的标准,将它所支持的各个标准与所有的标准 的信息进行比较,就可以获知所支持的各个标准的属性。一个输入所支持的标准应该是一 个集合,而这个集合是用bit与的方式用一个64位数字表示。因此我们所查到的是一个数字。

Example: Information about the current video standard v4l2_std_id std_id; //这个就是个64bit得数

[cpp] view plaincopy print?
  1. struct v4l2_standard standard;
  2. // VIDIOC_G_STD就是获得当前输入使用的standard,不过这里只是得到了该标准的id
  3. // 即flag,还没有得到其具体的属性信息,具体的属性信息要通过列举操作来得到。
  4. if (-1 == ioctl (fd, VIDIOC_G_STD, &std_id))
  5. {
  6. perror (”VIDIOC_G_STD”);
  7. exit (EXIT_FAILURE);
  8. //获得了当前输入使用的standard
  9. // Note when VIDIOC_ENUMSTD always returns EINVAL this is no video device
  10. // or it falls under the USB exception, and VIDIOC_G_STD returning EINVAL
  11. // is no error.
  12. }
  13. memset (&standard, 0, sizeof (standard));
  14. standard.index = 0; //从第一个开始列举
  15. // VIDIOC_ENUMSTD用来列举所支持的所有的video标准的信息,不过要先给standard
  16. // 结构的index域制定一个数值,所列举的标 准的信息属性包含在standard里面,
  17. // 如果我们所列举的标准和std_id有共同的bit,那么就意味着这个标准就是当前输
  18. // 入所使用的标准,这样我们就得到了当前输入使用的标准的属性信息
  19. while (0 == ioctl (fd, VIDIOC_ENUMSTD, &standard))
  20. {
  21. if (standard.id & std_id)
  22. {
  23. printf (”Current video standard: %s\n”, standard.name);
  24. exit (EXIT_SUCCESS);
  25. }
  26. standard.index++;
  27. }
  28. /* EINVAL indicates the end of the enumeration, which cannot be empty unless this device falls under the USB exception. */
  29. if (errno == EINVAL || standard.index == 0)
  30. {
  31. perror (”VIDIOC_ENUMSTD”);
  32. exit (EXIT_FAILURE);
  33. }

9. 申请和管理缓冲区

应用程序和设备有三种交换数据的方法,直接 read/write、内存映射(memory mapping)

和用户指针。这里只讨论内存映射(memory mapping)。

9.1 向设备申请缓冲区 VIDIOC_REQBUFS

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_requestbuffers *argp);

相关结构体:

[cpp] view plaincopy print?
  1. struct v4l2_requestbuffers
  2. {
  3. u32 count; // 缓冲区内缓冲帧的数目
  4. enum v4l2_buf_type type; // 缓冲帧数据格式
  5. enum v4l2_memory memory; // 区别是内存映射还是用户指针方式
  6. u32 reserved[2];
  7. };

注:

enum v4l2_memoy

{

V4L2_MEMORY_MMAP, V4L2_MEMORY_USERPTR

};

//count,type,memory 都要应用程序设置

例:申请一个拥有四个缓冲帧的缓冲区

[cpp] view plaincopy print?
  1. struct v4l2_requestbuffers req;
  2. req.count = 4;
  3. req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  4. req.memory = V4L2_MEMORY_MMAP;
  5. ioctl(fd,VIDIOC_REQBUFS,&req);

9.2 获取缓冲帧的地址,长度:VIDIOC_QUERYBUF

相关函数:

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_buffer *argp);

相关结构体:

[cpp] view plaincopy print?
  1. struct v4l2_buffer
  2. {
  3. u32 index; //buffer 序号
  4. enum v4l2_buf_type type; //buffer 类型
  5. u32 byteused; //buffer 中已使用的字节数
  6. u32 flags; // 区分是MMAP 还是USERPTR
  7. enum v4l2_field field;
  8. struct timeval timestamp; // 获取第一个字节时的系统时间
  9. struct v4l2_timecode timecode;
  10. u32 sequence; // 队列中的序号
  11. enum v4l2_memory memory; //IO 方式,被应用程序设置
  12. union m
  13. {
  14. u32 offset; // 缓冲帧地址,只对MMAP 有效
  15. unsigned long userptr;
  16. };
  17. u32 length; // 缓冲帧长度
  18. u32 input;
  19. u32 reserved;
  20. };

9.3 内存映射MMAP 及定义一个结构体来映射每个缓冲帧。 相关结构体:

[cpp] view plaincopy print?
  1. struct buffer
  2. {
  3. void* start;
  4. unsigned int length;
  5. }*buffers;

相关函数:

[cpp] view plaincopy print?
  1. #include <sys/mman.h>
  2. 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)

相关函数:

[cpp] view plaincopy print?
  1. int munmap(void *addr, size_t length);// 断开映射

//addr 为映射后的地址,length 为映射后的内存长度

例:将四个已申请到的缓冲帧映射到应用程序,用buffers 指针记录。

[cpp] view plaincopy print?
  1. buffers = (buffer*)calloc (req.count, sizeof (*buffers));
  2. if (!buffers)
  3. {
  4. // 映射
  5. fprintf (stderr, "Out of memory/n");
  6. exit (EXIT_FAILURE);
  7. }
  8. for (unsigned int n_buffers = 0; n_buffers < req.count; ++n_buffers)
  9. {
  10. struct v4l2_buffer buf;
  11. memset(&buf,0,sizeof(buf));
  12. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  13. buf.memory = V4L2_MEMORY_MMAP;
  14. buf.index = n_buffers;
  15. // 查询序号为n_buffers 的缓冲区,得到其起始物理地址和大小
  16. if (-1 == ioctl (fd, VIDIOC_QUERYBUF, &buf))
  17. {
  18. exit(-1);
  19. }
  20. buffers[n_buffers].length = buf.length;
  21. // 映射内存
  22. buffers[n_buffers].start = mmap (NULL,buf.length,PROT_READ | PROT_WRITE ,MAP_SHARED,fd, buf.m.offset);
  23. if (MAP_FAILED == buffers[n_buffers].start)
  24. {
  25. exit(-1);
  26. }
  27. }

10. 缓冲区处理好之后,就可以开始获取数据了

10.1 启动 或 停止数据流 VIDIOC_STREAMON, VIDIOC_STREAMOFF

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, const int *argp);

//argp 为流类型指针,如V4L2_BUF_TYPE_VIDEO_CAPTURE.

10.2 在开始之前,还应当把缓冲帧放入缓冲队列:

VIDIOC_QBUF// 把帧放入队列

VIDIOC_DQBUF// 从队列中取出帧

[cpp] view plaincopy print?
  1. int ioctl(int fd, int request, struct v4l2_buffer *argp);

例:把四个缓冲帧放入队列,并启动数据流

[cpp] view plaincopy print?
  1. unsigned int i;
  2. enum v4l2_buf_type type;
  3. for (i = 0; i < 4; ++i) // 将缓冲帧放入队列
  4. {
  5. struct v4l2_buffer buf;
  6. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  7. buf.memory = V4L2_MEMORY_MMAP;
  8. buf.index = i;
  9. ioctl (fd, VIDIOC_QBUF, &buf);
  10. }
  11. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  12. ioctl (fd, VIDIOC_STREAMON, &type);
  13. // 这有个问题,这些buf 看起来和前面申请的buf 没什么关系,为什么呢?

例:获取一帧并处理

[cpp] view plaincopy print?
  1. struct v4l2_buffer buf; CLEAR (buf);
  2. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  3. buf.memory = V4L2_MEMORY_MMAP;
  4. ioctl (fd, VIDIOC_DQBUF, &buf); // 从缓冲区取出一个缓冲帧
  5. process_image (buffers[buf.index.]start); //
  6. ioctl (fdVIDIOC_QBUF&buf); //

附官方 v4l2 video capture example

[cpp] view plaincopy print?
  1. /*
  2. *  V4L2 video capture example
  3. *
  4. *  This program can be used and distributed without restrictions.
  5. *
  6. *      This program is provided with the V4L2 API
  7. * see http://linuxtv.org/docs.php for more information
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <assert.h>
  13. #include <getopt.h>             /* getopt_long() */
  14. #include <fcntl.h>              /* low-level i/o */
  15. #include <unistd.h>
  16. #include <errno.h>
  17. #include <sys/stat.h>
  18. #include <sys/types.h>
  19. #include <sys/time.h>
  20. #include <sys/mman.h>
  21. #include <sys/ioctl.h>
  22. #include <linux/videodev2.h>
  23. #define CLEAR(x) memset(&(x), 0, sizeof(x))
  24. enum io_method {
  25. IO_METHOD_READ,
  26. IO_METHOD_MMAP,
  27. IO_METHOD_USERPTR,
  28. };
  29. struct buffer {
  30. void   *start;
  31. size_t  length;
  32. };
  33. static char            *dev_name;
  34. static enum io_method   io = IO_METHOD_MMAP;
  35. static int              fd = -1;
  36. struct buffer          *buffers;
  37. static unsigned int     n_buffers;
  38. static int              out_buf;
  39. static int              force_format;
  40. static int              frame_count = 70;
  41. /*
  42. *
  43. *
  44. *
  45. *
  46. */
  47. static void errno_exit(const char *s)
  48. {
  49. fprintf(stderr, "%s error %d, %s\n", s, errno, strerror(errno));
  50. exit(EXIT_FAILURE);
  51. }
  52. static int xioctl(int fh, int request, void *arg)
  53. {
  54. int r;
  55. do {
  56. r = ioctl(fh, request, arg);
  57. } while (-1 == r && EINTR == errno);
  58. return r;
  59. }
  60. static void process_image(const void *p, int size)
  61. {
  62. if (out_buf)
  63. fwrite(p, size, 1, stdout);
  64. fflush(stderr);
  65. fprintf(stderr, ".");
  66. fflush(stdout);
  67. }
  68. static int read_frame(void)
  69. {
  70. struct v4l2_buffer buf;
  71. unsigned int i;
  72. switch (io) {
  73. case IO_METHOD_READ:
  74. if (-1 == read(fd, buffers[0].start, buffers[0].length)) {
  75. switch (errno) {
  76. case EAGAIN:
  77. return 0;
  78. case EIO:
  79. /* Could ignore EIO, see spec. */
  80. /* fall through */
  81. default:
  82. errno_exit("read");
  83. }
  84. }
  85. process_image(buffers[0].start, buffers[0].length);
  86. break;
  87. case IO_METHOD_MMAP:
  88. CLEAR(buf);
  89. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  90. buf.memory = V4L2_MEMORY_MMAP;
  91. if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
  92. switch (errno) {
  93. case EAGAIN:
  94. return 0;
  95. case EIO:
  96. /* Could ignore EIO, see spec. */
  97. /* fall through */
  98. default:
  99. errno_exit("VIDIOC_DQBUF");
  100. }
  101. }
  102. assert(buf.index < n_buffers);
  103. process_image(buffers[buf.index].start, buf.bytesused);
  104. if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
  105. errno_exit("VIDIOC_QBUF");
  106. break;
  107. case IO_METHOD_USERPTR:
  108. CLEAR(buf);
  109. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  110. buf.memory = V4L2_MEMORY_USERPTR;
  111. if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
  112. switch (errno) {
  113. case EAGAIN:
  114. return 0;
  115. case EIO:
  116. /* Could ignore EIO, see spec. */
  117. /* fall through */
  118. default:
  119. errno_exit("VIDIOC_DQBUF");
  120. }
  121. }
  122. for (i = 0; i < n_buffers; ++i)
  123. if (buf.m.userptr == (unsigned long)buffers[i].start
  124. && buf.length == buffers[i].length)
  125. break;
  126. assert(i < n_buffers);
  127. process_image((void *)buf.m.userptr, buf.bytesused);
  128. if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
  129. errno_exit("VIDIOC_QBUF");
  130. break;
  131. }
  132. return 1;
  133. }
  134. /* two operations
  135. * step1 : delay
  136. * step2 : read frame
  137. */
  138. static void mainloop(void)
  139. {
  140. unsigned int count;
  141. count = frame_count;
  142. while (count-- > 0) {
  143. for (;;) {
  144. fd_set fds;
  145. struct timeval tv;
  146. int r;
  147. FD_ZERO(&fds);
  148. FD_SET(fd, &fds);
  149. /* Timeout. */
  150. tv.tv_sec = 2;
  151. tv.tv_usec = 0;
  152. r = select(fd + 1, &fds, NULL, NULL, &tv);
  153. if (-1 == r) {
  154. if (EINTR == errno)
  155. continue;
  156. errno_exit("select");
  157. }
  158. if (0 == r) {
  159. fprintf(stderr, "select timeout\n");
  160. exit(EXIT_FAILURE);
  161. }
  162. if (read_frame())
  163. break;
  164. /* EAGAIN - continue select loop. */
  165. }
  166. }
  167. }
  168. /*
  169. * one operation
  170. * step1 : VIDIOC_STREAMOFF
  171. */
  172. static void stop_capturing(void)
  173. {
  174. enum v4l2_buf_type type;
  175. switch (io) {
  176. case IO_METHOD_READ:
  177. /* Nothing to do. */
  178. break;
  179. case IO_METHOD_MMAP:
  180. case IO_METHOD_USERPTR:
  181. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  182. if (-1 == xioctl(fd, VIDIOC_STREAMOFF, &type))
  183. errno_exit("VIDIOC_STREAMOFF");
  184. break;
  185. }
  186. }
  187. /* tow operations
  188. * step1 : VIDIOC_QBUF(insert buffer to queue)
  189. * step2 : VIDIOC_STREAMOFF
  190. */
  191. static void start_capturing(void)
  192. {
  193. unsigned int i;
  194. enum v4l2_buf_type type;
  195. switch (io) {
  196. case IO_METHOD_READ:
  197. /* Nothing to do. */
  198. break;
  199. case IO_METHOD_MMAP:
  200. for (i = 0; i < n_buffers; ++i) {
  201. struct v4l2_buffer buf;
  202. CLEAR(buf);
  203. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  204. buf.memory = V4L2_MEMORY_MMAP;
  205. buf.index = i;
  206. if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
  207. errno_exit("VIDIOC_QBUF");
  208. }
  209. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  210. if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
  211. errno_exit("VIDIOC_STREAMON");
  212. break;
  213. case IO_METHOD_USERPTR:
  214. for (i = 0; i < n_buffers; ++i) {
  215. struct v4l2_buffer buf;
  216. CLEAR(buf);
  217. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  218. buf.memory = V4L2_MEMORY_USERPTR;
  219. buf.index = i;
  220. buf.m.userptr = (unsigned long)buffers[i].start;
  221. buf.length = buffers[i].length;
  222. if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
  223. errno_exit("VIDIOC_QBUF");
  224. }
  225. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  226. if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
  227. errno_exit("VIDIOC_STREAMON");
  228. break;
  229. }
  230. }
  231. /* two operations
  232. * step1 : munmap buffers
  233. * steo2 : free buffers
  234. */
  235. static void uninit_device(void)
  236. {
  237. unsigned int i;
  238. switch (io) {
  239. case IO_METHOD_READ:
  240. free(buffers[0].start);
  241. break;
  242. case IO_METHOD_MMAP:
  243. for (i = 0; i < n_buffers; ++i)
  244. if (-1 == munmap(buffers[i].start, buffers[i].length))
  245. errno_exit("munmap");
  246. break;
  247. case IO_METHOD_USERPTR:
  248. for (i = 0; i < n_buffers; ++i)
  249. free(buffers[i].start);
  250. break;
  251. }
  252. free(buffers);
  253. }
  254. static void init_read(unsigned int buffer_size)
  255. {
  256. buffers = calloc(1, sizeof(*buffers));
  257. if (!buffers) {
  258. fprintf(stderr, "Out of memory\n");
  259. exit(EXIT_FAILURE);
  260. }
  261. buffers[0].length = buffer_size;
  262. buffers[0].start = malloc(buffer_size);
  263. if (!buffers[0].start) {
  264. fprintf(stderr, "Out of memory\n");
  265. exit(EXIT_FAILURE);
  266. }
  267. }
  268. static void init_mmap(void)
  269. {
  270. struct v4l2_requestbuffers req;
  271. CLEAR(req);
  272. req.count = 4;
  273. req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  274. req.memory = V4L2_MEMORY_MMAP;
  275. if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
  276. if (EINVAL == errno) {
  277. fprintf(stderr, "%s does not support "
  278. "memory mapping\n", dev_name);
  279. exit(EXIT_FAILURE);
  280. } else {
  281. errno_exit("VIDIOC_REQBUFS");
  282. }
  283. }
  284. if (req.count < 2) {
  285. fprintf(stderr, "Insufficient buffer memory on %s\n",
  286. dev_name);
  287. exit(EXIT_FAILURE);
  288. }
  289. buffers = calloc(req.count, sizeof(*buffers));
  290. if (!buffers) {
  291. fprintf(stderr, "Out of memory\n");
  292. exit(EXIT_FAILURE);
  293. }
  294. for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
  295. struct v4l2_buffer buf;
  296. CLEAR(buf);
  297. buf.type        = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  298. buf.memory      = V4L2_MEMORY_MMAP;
  299. buf.index       = n_buffers;
  300. if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
  301. errno_exit("VIDIOC_QUERYBUF");
  302. buffers[n_buffers].length = buf.length;
  303. buffers[n_buffers].start =
  304. mmap(NULL /* start anywhere */,
  305. buf.length,
  306. PROT_READ | PROT_WRITE /* required */,
  307. MAP_SHARED /* recommended */,
  308. fd, buf.m.offset);
  309. if (MAP_FAILED == buffers[n_buffers].start)
  310. errno_exit("mmap");
  311. }
  312. }
  313. static void init_userp(unsigned int buffer_size)
  314. {
  315. struct v4l2_requestbuffers req;
  316. CLEAR(req);
  317. req.count  = 4;
  318. req.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  319. req.memory = V4L2_MEMORY_USERPTR;
  320. if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
  321. if (EINVAL == errno) {
  322. fprintf(stderr, "%s does not support "
  323. "user pointer i/o\n", dev_name);
  324. exit(EXIT_FAILURE);
  325. } else {
  326. errno_exit("VIDIOC_REQBUFS");
  327. }
  328. }
  329. buffers = calloc(4, sizeof(*buffers));
  330. if (!buffers) {
  331. fprintf(stderr, "Out of memory\n");
  332. exit(EXIT_FAILURE);
  333. }
  334. for (n_buffers = 0; n_buffers < 4; ++n_buffers) {
  335. buffers[n_buffers].length = buffer_size;
  336. buffers[n_buffers].start = malloc(buffer_size);
  337. if (!buffers[n_buffers].start) {
  338. fprintf(stderr, "Out of memory\n");
  339. exit(EXIT_FAILURE);
  340. }
  341. }
  342. }
  343. /* five operations
  344. * step1 : cap :query camera's capability and check it(is a video device? is it support read? is it support streaming?)
  345. * step2 : cropcap:set cropcap's type and get cropcap by VIDIOC_CROPCAP
  346. * step3 : set crop parameter by VIDIOC_S_CROP (such as frame type and angle)
  347. * step4 : set fmt
  348. * step5 : mmap
  349. */
  350. static void init_device(void)
  351. {
  352. struct v4l2_capability cap;
  353. struct v4l2_cropcap cropcap;
  354. struct v4l2_crop crop;
  355. struct v4l2_format fmt;
  356. unsigned int min;
  357. if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) {
  358. if (EINVAL == errno) {
  359. fprintf(stderr, "%s is no V4L2 device\n",
  360. dev_name);
  361. exit(EXIT_FAILURE);
  362. } else {
  363. errno_exit("VIDIOC_QUERYCAP");
  364. }
  365. }
  366. if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
  367. fprintf(stderr, "%s is no video capture device\n",
  368. dev_name);
  369. exit(EXIT_FAILURE);
  370. }
  371. switch (io) {
  372. case IO_METHOD_READ:
  373. if (!(cap.capabilities & V4L2_CAP_READWRITE)) {
  374. fprintf(stderr, "%s does not support read i/o\n",
  375. dev_name);
  376. exit(EXIT_FAILURE);
  377. }
  378. break;
  379. case IO_METHOD_MMAP:
  380. case IO_METHOD_USERPTR:
  381. if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
  382. fprintf(stderr, "%s does not support streaming i/o\n",
  383. dev_name);
  384. exit(EXIT_FAILURE);
  385. }
  386. break;
  387. }
  388. /* Select video input, video standard and tune here. */
  389. CLEAR(cropcap);
  390. cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  391. /* if device support cropcap's type then set crop */
  392. if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap)) {
  393. crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  394. crop.c = cropcap.defrect; /* reset to default */
  395. if (-1 == xioctl(fd, VIDIOC_S_CROP, &crop)) {
  396. switch (errno) {
  397. case EINVAL:
  398. /* Cropping not supported. */
  399. break;
  400. default:
  401. /* Errors ignored. */
  402. break;
  403. }
  404. }
  405. } else {
  406. /* Errors ignored. */
  407. }
  408. CLEAR(fmt);
  409. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  410. if (force_format) {
  411. fmt.fmt.pix.width       = 640;
  412. fmt.fmt.pix.height      = 480;
  413. fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
  414. fmt.fmt.pix.field       = V4L2_FIELD_INTERLACED;
  415. if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt))
  416. errno_exit("VIDIOC_S_FMT");
  417. /* Note VIDIOC_S_FMT may change width and height. */
  418. } else {
  419. /* Preserve original settings as set by v4l2-ctl for example */
  420. if (-1 == xioctl(fd, VIDIOC_G_FMT, &fmt))
  421. errno_exit("VIDIOC_G_FMT");
  422. }
  423. /* Buggy driver paranoia. */
  424. min = fmt.fmt.pix.width * 2;
  425. if (fmt.fmt.pix.bytesperline < min)
  426. fmt.fmt.pix.bytesperline = min;
  427. min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
  428. if (fmt.fmt.pix.sizeimage < min)
  429. fmt.fmt.pix.sizeimage = min;
  430. switch (io) {
  431. case IO_METHOD_READ:
  432. init_read(fmt.fmt.pix.sizeimage);
  433. break;
  434. case IO_METHOD_MMAP:
  435. init_mmap();
  436. break;
  437. case IO_METHOD_USERPTR:
  438. init_userp(fmt.fmt.pix.sizeimage);
  439. break;
  440. }
  441. }
  442. /*
  443. * close (fd)
  444. */
  445. static void close_device(void)
  446. {
  447. if (-1 == close(fd))
  448. errno_exit("close");
  449. fd = -1;
  450. }
  451. /* three operations
  452. * step 1 : check dev_name and st_mode
  453. * step 2 : open(device)
  454. */
  455. static void open_device(void)
  456. {
  457. struct stat st;
  458. if (-1 == stat(dev_name, &st)) {
  459. fprintf(stderr, "Cannot identify '%s': %d, %s\n",
  460. dev_name, errno, strerror(errno));
  461. exit(EXIT_FAILURE);
  462. }
  463. if (!S_ISCHR(st.st_mode)) {
  464. fprintf(stderr, "%s is no device\n", dev_name);
  465. exit(EXIT_FAILURE);
  466. }
  467. fd = open(dev_name, O_RDWR /* required */ | O_NONBLOCK, 0);
  468. if (-1 == fd) {
  469. fprintf(stderr, "Cannot open '%s': %d, %s\n",
  470. dev_name, errno, strerror(errno));
  471. exit(EXIT_FAILURE);
  472. }
  473. }
  474. static void usage(FILE *fp, int argc, char **argv)
  475. {
  476. fprintf(fp,
  477. "Usage: %s [options]\n\n"
  478. "Version 1.3\n"
  479. "Options:\n"
  480. "-d | --device name   Video device name [%s]\n"
  481. "-h | --help          Print this message\n"
  482. "-m | --mmap          Use memory mapped buffers [default]\n"
  483. "-r | --read          Use read() calls\n"
  484. "-u | --userp         Use application allocated buffers\n"
  485. "-o | --output        Outputs stream to stdout\n"
  486. "-f | --format        Force format to 640x480 YUYV\n"
  487. "-c | --count         Number of frames to grab [%i]\n"
  488. "",
  489. argv[0], dev_name, frame_count);
  490. }
  491. static const char short_options[] = "d:hmruofc:";
  492. static const struct option
  493. long_options[] = {
  494. { "device", required_argument, NULL, 'd' },
  495. { "help",   no_argument,       NULL, 'h' },
  496. { "mmap",   no_argument,       NULL, 'm' },
  497. { "read",   no_argument,       NULL, 'r' },
  498. { "userp",  no_argument,       NULL, 'u' },
  499. { "output", no_argument,       NULL, 'o' },
  500. { "format", no_argument,       NULL, 'f' },
  501. { "count",  required_argument, NULL, 'c' },
  502. { 0, 0, 0, 0 }
  503. };
  504. int main(int argc, char **argv)
  505. {
  506. dev_name = "/dev/video4";
  507. for (;;) {
  508. int idx;
  509. int c;
  510. c = getopt_long(argc, argv,
  511. short_options, long_options, &idx);
  512. if (-1 == c)
  513. break;
  514. switch (c) {
  515. case 0: /* getopt_long() flag */
  516. break;
  517. case 'd':
  518. dev_name = optarg;
  519. break;
  520. case 'h':
  521. usage(stdout, argc, argv);
  522. exit(EXIT_SUCCESS);
  523. case 'm':
  524. io = IO_METHOD_MMAP;
  525. break;
  526. case 'r':
  527. io = IO_METHOD_READ;
  528. break;
  529. case 'u':
  530. io = IO_METHOD_USERPTR;
  531. break;
  532. case 'o':
  533. out_buf++;
  534. break;
  535. case 'f':
  536. force_format++;
  537. break;
  538. case 'c':
  539. errno = 0;
  540. frame_count = strtol(optarg, NULL, 0);
  541. if (errno)
  542. errno_exit(optarg);
  543. break;
  544. default:
  545. usage(stderr, argc, argv);
  546. exit(EXIT_FAILURE);
  547. }
  548. }
  549. open_device();
  550. init_device();
  551. start_capturing();
  552. mainloop();
  553. stop_capturing();
  554. uninit_device();
  555. close_device();
  556. fprintf(stderr, "\n");
  557. return 0;
  558. }

Video for linux 2 example (v4l2 demo)相关推荐

  1. 深入理解l内核v4l2框架之video for linux 2(一)

    在看了很多关于v4l2驱动的例程之后,想深入研究下linux内核的v4l2框架,顺便把这些记录下来,以备查用. Video for Linux 2 随着一些视频或者图像硬件的复杂化,V4L2驱动也越来 ...

  2. 深入理解l内核v4l2框架之video for linux 2(转载)

    在看了很多关于v4l2驱动的例程之后,想深入研究下linux内核的v4l2框架,顺便把这些记录下来,以备查用. Video for Linux 2 随着一些视频或者图像硬件的复杂化,V4L2驱动也越来 ...

  3. Linux下通过v4l2获取视频设备名、支持的编解码及视频size列表实现

    早些时候给出了在Windows下通过dshow获取视频设备信息的实现,包括获取视频设备名.获取每种视频设备支持的编解码格式列表.每种编解码格式支持的video size列表,见:https://blo ...

  4. Linux 下UVCamp;V4L2技术简单介绍(二)

    通过前文Linux 下UVC&V4L2技术简单介绍(一)我们了解了UVC和V4L2的简单知识. 这里是USB设备的文档描写叙述:http://www.usb.org/developers/do ...

  5. 亚马逊AWS Kinesis Video Streams with IOT mqtt的demo示例

    title: 亚马逊AWS Kinesis Video Streams with IOT mqtt的demo示例 categories:[Linux C] tags:[亚马逊云平台] date: 20 ...

  6. Linux中通过v4l2框架获取摄像头的能力的方法

    v4l2(video for linux two)是Linux中内核提供给应用层访问音视频驱动的统一接口.v4l2中获取摄像头的能力的是通过ioctl函数的VIDIOC_QUERYCAP命令获取,并且 ...

  7. 国外linux内核视频播放器,基于Video for Linux内核的USB摄像头视频信号采集实现

    摘要:Video for Linux是Linux中关于视频设备的内核驱动,本文介绍了在Video for Linux内 >> 基于ARM9和USB摄像头的网络视频采集系统设计 基于嵌入式V ...

  8. 【Linux开发】V4L2应用程序框架

    V4L2应用程序框架 V4L2较V4L有较大的改动,并已成为2.6的标准接口,函盖video\dvb\FM...,多数驱动都在向V4l2迁移.更好地了解V4L2先从应用入手,然后再深入到内核中结合物理 ...

  9. linux驱动管道,Xilinx Linux 如何理解V4L2的管道驱动程序

    xvipp 函数调用关系图 4.主要函数 4.1. 函数xvip_composite_probe() 函数xvip_composite_probe是整个驱动的入口,主要工作是初始化驱动的数据结构xvi ...

最新文章

  1. 像教光学一样在高中教深度学习?怼过LeCun的Google大牛认为这事有出路
  2. springmvc 将post转换为delete,put
  3. 文本处理相关资料整理
  4. erlang精要(9)-erl(1)
  5. C#decimal数据类型——有效长度问题
  6. Oracle之外部表
  7. 不止代码:ybtoj-棋盘分割(二维区间dp)
  8. Leetcode--994. 腐烂的橘子(java)
  9. 2万字,看完这篇才敢说自己真的懂线程池!
  10. Python面向过程和面向对象
  11. 对fragment的学习
  12. android开发(4) 闪屏的实现
  13. html条纹填充色,HTML5/Canvas 上传图片的彩色斑马条纹遮罩效果
  14. C++ 输出日志到 DbgView
  15. 13年草根程序员转型之路
  16. 什么叫图像或轮廓的空间矩、中心矩、归一化中心矩?并利用OpenCV的类Moments计算轮廓的这几个矩和质心位置
  17. oracle pl/sqp 连接 ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务
  18. JAVA微服务架构视频教程
  19. 计算机毕业设计Java城市智能公交系统(源码+系统+mysql数据库+lw文档)
  20. 苹果7处理器_苹果发布重磅创世纪新品!苹果将再次改变世界了吗?

热门文章

  1. openstack运维实战系列(一)之keystone用户建立
  2. 加速你的开发环境[VS2003]
  3. Apache Hudi 是Uber 大数据存储系统
  4. 移动应用框架 Ionic 4 Ionic for Everyone
  5. QTdesigner使用--待更新
  6. 【机器学习】隐马尔可夫模型及其三个基本问题(一)
  7. loop在python中什么意思_在python中使用loop打开多个文件
  8. 发明python的人是个天才_BBC纪录片《天才的发明 The Genius of Invention》全4集 英语中英字幕 720P高清纪录片...
  9. 有关计算机方面的知识竞赛,关于计算机知识竞赛试题
  10. linux下安装mysql57_Linux下安装MySql