V4L2视频采集与H264编码2—v4l2采集YUV数据

2024-06-08 00:08

本文主要是介绍V4L2视频采集与H264编码2—v4l2采集YUV数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  在上一篇中因为是在PC机上使用的USB摄像头只能支持GPEG image格式,但是H264编码需要使用YUV数据,所以我找了个ARM开发板来做测试。本以为代码从PC机移植到开发板是很简单的一个事,谁知因为平台或是V4L2底层驱动的不同,最终也是花了九牛二虎之力才把问题给解了。话不多说,直接上代码:

[objc]  view plain  copy
  1. /*============================================================================= 
  2. #     FileName: v4l2.c 
  3. #         Desc: this program aim to get image from USB camera, 
  4. #               used the V4L2 interface. 
  5. #       Author: Licaibiao 
  6. #      Version:  
  7. #   LastChange: 2016-12-10  
  8. #      History: 
  9.  
  10. =============================================================================*/  
  11. #include <unistd.h>  
  12. #include <sys/types.h>  
  13. #include <sys/stat.h>  
  14. #include <fcntl.h>  
  15. #include <stdio.h>  
  16. #include <sys/ioctl.h>  
  17. #include <stdlib.h>  
  18. #include <linux/types.h>  
  19. #include <linux/videodev2.h>  
  20. #include <malloc.h>  
  21. #include <math.h>  
  22. #include <string.h>  
  23. #include <sys/mman.h>  
  24. #include <errno.h>  
  25. #include <assert.h>  
  26.   
  27. #define FILE_VIDEO  "/dev/video0"  
  28. #define JPG "./out/image%d"  
  29.   
  30. typedef struct{  
  31.     voidvoid *start;  
  32.     int length;  
  33. }BUFTYPE;  
  34.   
  35. BUFTYPE *usr_buf;  
  36. static unsigned int n_buffer = 0;  
  37.   
  38.   
  39. /*set video capture ways(mmap)*/  
  40. int init_mmap(int fd)  
  41. {  
  42.     /*to request frame cache, contain requested counts*/  
  43.     struct v4l2_requestbuffers reqbufs;  
  44.   
  45.     memset(&reqbufs, 0sizeof(reqbufs));  
  46.     reqbufs.count = 1;                              /*the number of buffer*/  
  47.     reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;      
  48.     reqbufs.memory = V4L2_MEMORY_MMAP;                
  49.   
  50.     if(-1 == ioctl(fd,VIDIOC_REQBUFS,&reqbufs))  
  51.     {  
  52.         perror("Fail to ioctl 'VIDIOC_REQBUFS'");  
  53.         exit(EXIT_FAILURE);  
  54.     }  
  55.       
  56.     n_buffer = reqbufs.count;  
  57.     printf("n_buffer = %d\n", n_buffer);  
  58.     //usr_buf = calloc(reqbufs.count, sizeof(usr_buf));  
  59.     usr_buf = calloc(reqbufs.countsizeof(BUFTYPE));  
  60.     if(usr_buf == NULL)  
  61.     {  
  62.         printf("Out of memory\n");  
  63.         exit(-1);  
  64.     }  
  65.   
  66.     /*map kernel cache to user process*/  
  67.     for(n_buffer = 0; n_buffer < reqbufs.count; ++n_buffer)  
  68.     {  
  69.         //stand for a frame  
  70.         struct v4l2_buffer buf;  
  71.         memset(&buf, 0sizeof(buf));  
  72.         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;  
  73.         buf.memory = V4L2_MEMORY_MMAP;  
  74.         buf.index = n_buffer;  
  75.           
  76.         /*check the information of the kernel cache requested*/  
  77.         if(-1 == ioctl(fd,VIDIOC_QUERYBUF,&buf))  
  78.         {  
  79.             perror("Fail to ioctl : VIDIOC_QUERYBUF");  
  80.             exit(EXIT_FAILURE);  
  81.         }  
  82.   
  83.         usr_buf[n_buffer].length = buf.length;  
  84.         usr_buf[n_buffer].start = (charchar *)mmap(NULL,buf.length,PROT_READ | PROT_WRITE,MAP_SHARED, fd,buf.m.offset);  
  85.   
  86.         if(MAP_FAILED == usr_buf[n_buffer].start)  
  87.         {  
  88.             perror("Fail to mmap");  
  89.             exit(EXIT_FAILURE);  
  90.         }  
  91.   
  92.     }  
  93.   
  94. }  
  95.   
  96. int open_camera(void)  
  97. {  
  98.     int fd;  
  99.     struct v4l2_input inp;  
  100.   
  101.     fd = open(FILE_VIDEO, O_RDWR | O_NONBLOCK,0);  
  102.     if(fd < 0)  
  103.     {     
  104.         fprintf(stderr, "%s open err \n", FILE_VIDEO);  
  105.         exit(EXIT_FAILURE);  
  106.     };  
  107.   
  108.     inp.index = 0;  
  109.     if (-1 == ioctl (fd, VIDIOC_S_INPUT, &inp))  
  110.     {  
  111.         fprintf(stderr, "VIDIOC_S_INPUT \n");  
  112.     }  
  113.   
  114.     return fd;  
  115. }  
  116.   
  117. int init_camera(int fd)  
  118. {  
  119.     struct v4l2_capability  cap;    /* decive fuction, such as video input */  
  120.     struct v4l2_format      tv_fmt; /* frame format */    
  121.     struct v4l2_fmtdesc     fmtdesc;    /* detail control value */  
  122.     struct v4l2_control     ctrl;  
  123.     int ret;  
  124.       
  125.             /*show all the support format*/  
  126.     memset(&fmtdesc, 0sizeof(fmtdesc));  
  127.     fmtdesc.index = 0 ;                 /* the number to check */  
  128.     fmtdesc.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;  
  129.   
  130.     /* check video decive driver capability */  
  131.     if(ret=ioctl(fd, VIDIOC_QUERYCAP, &cap)<0)  
  132.     {  
  133.         fprintf(stderr, "fail to ioctl VIDEO_QUERYCAP \n");  
  134.         exit(EXIT_FAILURE);  
  135.     }  
  136.       
  137.     /*judge wherher or not to be a video-get device*/  
  138.     if(!(cap.capabilities & V4L2_BUF_TYPE_VIDEO_CAPTURE))  
  139.     {  
  140.         fprintf(stderr, "The Current device is not a video capture device \n");  
  141.         exit(EXIT_FAILURE);  
  142.     }  
  143.   
  144.     /*judge whether or not to supply the form of video stream*/  
  145.     if(!(cap.capabilities & V4L2_CAP_STREAMING))  
  146.     {  
  147.         printf("The Current device does not support streaming i/o\n");  
  148.         exit(EXIT_FAILURE);  
  149.     }  
  150.       
  151.     printf("\ncamera driver name is : %s\n",cap.driver);  
  152.     printf("camera device name is : %s\n",cap.card);  
  153.     printf("camera bus information: %s\n",cap.bus_info);  
  154.   
  155.     /*display the format device support*/  
  156.     printf("\n");  
  157.     while(ioctl(fd,VIDIOC_ENUM_FMT,&fmtdesc)!=-1)  
  158.     {     
  159.         printf("support device %d.%s\n",fmtdesc.index+1,fmtdesc.description);  
  160.         fmtdesc.index++;  
  161.     }  
  162.     printf("\n");  
  163.   
  164.     /*set the form of camera capture data*/  
  165.     tv_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;      /*v4l2_buf_typea,camera must use V4L2_BUF_TYPE_VIDEO_CAPTURE*/  
  166.     tv_fmt.fmt.pix.width = 680;  
  167.     tv_fmt.fmt.pix.height = 480;  
  168.     tv_fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUV420;   /*V4L2_PIX_FMT_YYUV*/  
  169.     tv_fmt.fmt.pix.field = V4L2_FIELD_NONE;         /*V4L2_FIELD_NONE*/  
  170.     if (ioctl(fd, VIDIOC_S_FMT, &tv_fmt)< 0)   
  171.     {  
  172.         fprintf(stderr,"VIDIOC_S_FMT set err\n");  
  173.         exit(-1);  
  174.         close(fd);  
  175.     }  
  176.   
  177.     init_mmap(fd);  
  178. }  
  179.   
  180. int start_capture(int fd)  
  181. {  
  182.     unsigned int i;  
  183.     enum v4l2_buf_type type;  
  184.       
  185.     /*place the kernel cache to a queue*/  
  186.     for(i = 0; i < n_buffer; i++)  
  187.     {  
  188.         struct v4l2_buffer buf;  
  189.         memset(&buf, 0sizeof(buf));  
  190.         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;  
  191.         buf.memory = V4L2_MEMORY_MMAP;  
  192.         buf.index = i;  
  193.   
  194.         if(-1 == ioctl(fd, VIDIOC_QBUF, &buf))  
  195.         {  
  196.             perror("Fail to ioctl 'VIDIOC_QBUF'");  
  197.             exit(EXIT_FAILURE);  
  198.         }  
  199.     }  
  200.   
  201.     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;  
  202.     if(-1 == ioctl(fd, VIDIOC_STREAMON, &type))  
  203.     {  
  204.         printf("i=%d.\n", i);  
  205.         perror("VIDIOC_STREAMON");  
  206.         close(fd);  
  207.         exit(EXIT_FAILURE);  
  208.     }  
  209.   
  210.     return 0;  
  211. }  
  212.   
  213.   
  214. int process_image(voidvoid *addr, int length)  
  215. {  
  216.     FILEFILE *fp;  
  217.   
  218.     static int num = 0;  
  219.   
  220.     char image_name[20];  
  221.     sprintf(image_name, JPG, num++);  
  222.     if((fp = fopen(image_name, "w")) == NULL)  
  223.     {  
  224.         perror("Fail to fopen");  
  225.         exit(EXIT_FAILURE);  
  226.     }  
  227.     fwrite(addr, length, 1, fp);  
  228.     usleep(500);  
  229.     fclose(fp);  
  230.     return 0;  
  231. }  
  232.   
  233. int read_frame(int fd)  
  234. {  
  235.     struct v4l2_buffer buf;  
  236.     unsigned int i;  
  237.     memset(&buf, 0sizeof(buf));  
  238.     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;  
  239.     buf.memory = V4L2_MEMORY_MMAP;  
  240.     //put cache from queue  
  241.     if(-1 == ioctl(fd, VIDIOC_DQBUF,&buf))  
  242.     {  
  243.         perror("Fail to ioctl 'VIDIOC_DQBUF'");  
  244.         exit(EXIT_FAILURE);  
  245.     }  
  246.     assert(buf.index < n_buffer);  
  247.   
  248.     //read process space's data to a file  
  249.     process_image(usr_buf[buf.index].start, usr_buf[buf.index].length);  
  250.     if(-1 == ioctl(fd, VIDIOC_QBUF,&buf))  
  251.     {  
  252.         perror("Fail to ioctl 'VIDIOC_QBUF'");  
  253.         exit(EXIT_FAILURE);  
  254.     }  
  255.     return 1;  
  256. }  
  257.   
  258.   
  259. int mainloop(int fd)  
  260. {  
  261.     int count = 10;  
  262.     while(count-- > 0)  
  263.     {  
  264.         for(;;)  
  265.         {  
  266.             fd_set fds;  
  267.             struct timeval tv;  
  268.             int r;  
  269.   
  270.             FD_ZERO(&fds);  
  271.             FD_SET(fd,&fds);  
  272.   
  273.             /*Timeout*/  
  274.             tv.tv_sec = 2;  
  275.             tv.tv_usec = 0;  
  276.             r = select(fd + 1,&fds,NULL,NULL,&tv);  
  277.               
  278.             if(-1 == r)  
  279.             {  
  280.                  if(EINTR == errno)  
  281.                     continue;  
  282.                 perror("Fail to select");  
  283.                 exit(EXIT_FAILURE);  
  284.             }  
  285.             if(0 == r)  
  286.             {  
  287.                 fprintf(stderr,"select Timeout\n");  
  288.                 exit(-1);  
  289.             }  
  290.   
  291.             if(read_frame(fd))  
  292.             break;  
  293.         }  
  294.     }  
  295.     return 0;  
  296. }  
  297.   
  298. void stop_capture(int fd)  
  299. {  
  300.     enum v4l2_buf_type type;  
  301.     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;  
  302.     if(-1 == ioctl(fd,VIDIOC_STREAMOFF,&type))  
  303.     {  
  304.         perror("Fail to ioctl 'VIDIOC_STREAMOFF'");  
  305.         exit(EXIT_FAILURE);  
  306.     }  
  307. }  
  308.   
  309. void close_camera_device(int fd)  
  310. {  
  311.     unsigned int i;  
  312.     for(i = 0;i < n_buffer; i++)  
  313.     {  
  314.         if(-1 == munmap(usr_buf[i].start,usr_buf[i].length))  
  315.         {  
  316.             exit(-1);  
  317.         }  
  318.     }  
  319.   
  320.     free(usr_buf);  
  321.   
  322.     if(-1 == close(fd))  
  323.     {  
  324.         perror("Fail to close fd");  
  325.         exit(EXIT_FAILURE);  
  326.     }  
  327. }  
  328.   
  329.   
  330. void main(void)  
  331. {  
  332.     int fd;  
  333.     fd = open_camera();  
  334.     init_camera(fd);  
  335.     start_capture(fd);  
  336.     mainloop(fd);  
  337.     stop_capture(fd);  
  338.     close_camera_device(fd);  
  339. }  
    该代码由上一章的代码移植过来,主要是针对我的板子移植,主要修改了:

(1)camera 打开由阻塞打开改为了非阻塞方式打开

(2)mmap 由原来的MAP_PRIVATE 模式改为MAP_SHARED方式

(3)imag 格式由原来的V4L2_PIX_FMT_JPEG 改为V4L2_PIX_FMT_YUV420

(4)在我的开发板中,必须设定camera 设备的索引号,也就是上面代码中的ioctl (fd, VIDIOC_S_INPUT, &inp) ,值为inp.index = 0; 如果不设置,select的时候会出现select   timeout 的问题。

    将上面代码交叉编译后放到开发板上去运行,结果如下:

[objc]  view plain  copy
  1. /tmp # ./test   
  2.   
  3. camera driver name is : sunxi-vfe  
  4. camera device name is : sunxi-vfe  
  5. camera bus information: sunxi_vfe vfe.2  
  6.   
  7. support device 1.planar YUV 422  
  8. support device 2.planar YUV 420  
  9. support device 3.planar YVU 420  
  10. support device 4.planar YUV 422 UV combined  
  11. support device 5.planar YUV 420 UV combined  
  12. support device 6.planar YUV 422 VU combined  
  13. support device 7.planar YUV 420 VU combined  
  14. support device 8.MB YUV420  
  15. support device 9.YUV422 YUYV  
  16. support device 10.YUV422 YVYU  
  17. support device 11.YUV422 UYVY  
  18. support device 12.YUV422 VYUY  
  19. support device 13.RAW Bayer BGGR 8bit  
  20. support device 14.RAW Bayer GBRG 8bit  
  21. support device 15.RAW Bayer GRBG 8bit  
  22. support device 16.RAW Bayer RGGB 8bit  
  23. support device 17.RAW Bayer BGGR 10bit  
  24. support device 18.RAW Bayer GBRG 10bit  
  25. support device 19.RAW Bayer GRBG 10bit  
  26. support device 20.RAW Bayer RGGB 10bit  
  27. support device 21.RAW Bayer BGGR 12bit  
  28. support device 22.RAW Bayer GBRG 12bit  
  29. support device 23.RAW Bayer GRBG 12bit  
  30. support device 24.RAW Bayer RGGB 12bit  
  31.   
  32. n_buffer = 3  
  33. /tmp # ls  
  34. hostapd   messages  out       test      utmp  
  35. /tmp # cd out  
  36. /tmp/out # ls  
  37. image0  image2  image4  image6  image8  
  38. image1  image3  image5  image7  image9  
  39. /tmp/out # ls -l  
  40. total 4520  
  41. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image0  
  42. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image1  
  43. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image2  
  44. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image3  
  45. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image4  
  46. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image5  
  47. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image6  
  48. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image7  
  49. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image8  
  50. -rw-r--r--    1 root     root        460800 Jan  1 00:01 image9  
  51. /tmp/out #   
    从我们输出的信息可以看出,在我开发板上可以支持24种image格式,在这了我们后面H264的编码,这里选用的是V4L2_PIX_FMT_YUV420 格式。我开发板上装的是GC0308 VGA 摄像头,从生成image的大小可以判断出是正确的(YUV420数据大小 = 长 * 宽 * 1.5 = 640 * 480 * 1.5 = 460800 = 450k)

可以将image文件拷出来,使用pYUV 软件查看YUV图片。这里需要注意,使用pYUV 查看YUV图片的时候,需要正确设置图片格式,按我上面代码采集的数据格式,其设置如下图:


正常打开显示的图片为:


到这里采集YUV数据就结束了,下一章介绍使用X264库将YUV数据编码成H264视频文件。


这篇关于V4L2视频采集与H264编码2—v4l2采集YUV数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1040690

相关文章

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

使用SpringBoot整合Sharding Sphere实现数据脱敏的示例

《使用SpringBoot整合ShardingSphere实现数据脱敏的示例》ApacheShardingSphere数据脱敏模块,通过SQL拦截与改写实现敏感信息加密存储,解决手动处理繁琐及系统改... 目录痛点一:痛点二:脱敏配置Quick Start——Spring 显示配置:1.引入依赖2.创建脱敏

详解如何使用Python构建从数据到文档的自动化工作流

《详解如何使用Python构建从数据到文档的自动化工作流》这篇文章将通过真实工作场景拆解,为大家展示如何用Python构建自动化工作流,让工具代替人力完成这些数字苦力活,感兴趣的小伙伴可以跟随小编一起... 目录一、Excel处理:从数据搬运工到智能分析师二、PDF处理:文档工厂的智能生产线三、邮件自动化:

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L

使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)

《使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)》字体设计和矢量图形处理是编程中一个有趣且实用的领域,通过Python的matplotlib库,我们可以轻松将字体轮廓... 目录背景知识字体轮廓的表示实现步骤1. 安装依赖库2. 准备数据3. 解析路径指令4. 绘制图形关键

解决mysql插入数据锁等待超时报错:Lock wait timeout exceeded;try restarting transaction

《解决mysql插入数据锁等待超时报错:Lockwaittimeoutexceeded;tryrestartingtransaction》:本文主要介绍解决mysql插入数据锁等待超时报... 目录报错信息解决办法1、数据库中执行如下sql2、再到 INNODB_TRX 事务表中查看总结报错信息Lock

使用C#删除Excel表格中的重复行数据的代码详解

《使用C#删除Excel表格中的重复行数据的代码详解》重复行是指在Excel表格中完全相同的多行数据,删除这些重复行至关重要,因为它们不仅会干扰数据分析,还可能导致错误的决策和结论,所以本文给大家介绍... 目录简介使用工具C# 删除Excel工作表中的重复行语法工作原理实现代码C# 删除指定Excel单元

Linux lvm实例之如何创建一个专用于MySQL数据存储的LVM卷组

《Linuxlvm实例之如何创建一个专用于MySQL数据存储的LVM卷组》:本文主要介绍使用Linux创建一个专用于MySQL数据存储的LVM卷组的实例,具有很好的参考价值,希望对大家有所帮助,... 目录在Centos 7上创建卷China编程组并配置mysql数据目录1. 检查现有磁盘2. 创建物理卷3. 创