摄像头原始数据读取——V4L2(userptr模式,V4L2_MEMORY_USERPTR)

摄像头原始数据读取——V4L2(userptr模式,V4L2_MEMORY_USERPTR)

用户指针方式允许用户空间的应用程序分配内存,并将内存地址传递给内核中的驱动程序。驱动程序直接将数据填充到用户空间的内存中,从而避免了数据的拷贝过程。
流程:

  1. 通过VIDIOC_REQBUFS ioctl请求内核分配视频数据缓冲区,在v4l2_requestbuffers里将memory字段设置成V4L2_MEMORY_USERPTR
  2. 通过VIDIOC_QUERYBUF ioctl获取内核已经分配好的视频数据缓冲区信息。
  3. 应用程序分配内存,并将内存地址填充到已经分配好的视频缓冲区中。
  4. 通过VIDIOC_QBUF ioctl将已经申请好的缓冲区放入数据缓存队列,将memory字段设置成V4L2_MEMORY_USERPTR
  5. 启动视频流后,使用poll或select函数等待设备缓冲区数据就绪。
  6. 通过VIDIOC_DQBUF ioctl从队列中取出已填充的数据缓冲区并进行处理。
  7. 处理完数据后,再次通过VIDIOC_QBUF ioctl将缓冲区放入输入队列,循环使用。

v4l2userptrmode.hpp

#ifndef _V4L2USERPTRMODE_H_
#define _V4L2USERPTRMODE_H_#include <iostream>
#include <list>
#include <vector>
#include <utility>
#include <functional>
#include <mutex>
#include <thread>
#include <linux/videodev2.h>//图像帧数据结构体
struct VideoBufferStruct
{std::string dev_name;   //video设备名unsigned int pixel_format; //当前使用的图像格式int width;     //图像宽度int height;   //图像高度unsigned long timestamp; //图像从内核读上来后的时间戳size_t data_len;  //图像数据长度void *data;   //图像数据
};class V4L2CaptureVideoData
{
public:static bool m_keeprunning;public:explicit V4L2CaptureVideoData();~V4L2CaptureVideoData();void RegisterVideoDataProcessCallback(std::function<void(const VideoBufferStruct&)> func);bool OpenVideoDevice(std::string device_name);bool closeVideoDevice();bool QueryVideoDeviceCapability(const unsigned int capability);void RegisterVideoUserptr(std::vector<std::pair<unsigned long, unsigned int>> &video_userptr);void StartUserptrData();/* VIDIOC_QUERYCAP 获取设备支持的操作*/bool GetVideoDeviceCapability(struct v4l2_capability &cap);/* VIDIOC_G_PRIORITY   获取设备操作的优先级*/bool GetVideoDevicePriority(unsigned int &priority);/* VIDIOC_S_PRIORITY   设置设备操作的优先级*/bool SetVideoDevicePriority(const unsigned int priority);/* VIDIOC_LOG_STATUS  获取关于视频设备当前状态的日志信息*/bool GetVideoDeviceLogStatus(void);/* VIDIOC_ENUM_FMT 列举设备所支持的视频格式*/bool EnumVideoDeviceFormat(std::list<struct v4l2_fmtdesc> &fmtdesc);/* VIDIOC_G_FMT 获取设备当前使用的视频像素格式*/bool GetVideoDeviceFormat(struct v4l2_format &fmt);/* VIDIOC_S_FMT 设置设备当前使用的视频像素格式*/bool SetVideoDeviceFormat(const struct v4l2_format &fmt);/* VIDIOC_TRY_FMT 尝试设置视频像素格式、用于判断设备是否支持该视频像素格式*/bool TrySetVideoDeviceFormat(const struct v4l2_format &fmt);/* VIDIOC_ENUM_FRAMESIZES 枚举设备支持的视频采集分辨率*/bool EnumVideoDeviceFrameSize(const unsigned int pixel_format, std::list<struct v4l2_frmsizeenum> &frmsize);/* VIDIOC_ENUM_FRAMEINTERVALS 枚举设备支持的视频采集帧率fps*/bool EnumVideoDeviceFrameIntervals(const unsigned int pixel_format, const unsigned int width, const unsigned int height, std::list<struct v4l2_frmivalenum> &frmivals);/*VIDIOC_STREAMON 启动视频采集*/bool StartVideoCapture(void);/*VIDIOC_STREAMOFF 停止视频采集*/bool StopVideoCapture(void);/*VIDIOC_REQBUFS  申请驱动分配视频帧缓冲区*/bool RequestVideoBuffer(const struct v4l2_requestbuffers &requestbuf);/*VIDIOC_QUERYBUF 查询视频缓冲区信息 struct v4l2_buffer*/bool GetVideoBuffer(const unsigned int memory_type, unsigned int index, v4l2_buffer &video_buffer);/*VIDIOC_QBUF 将申请的缓冲帧放入队列*/bool PushVideoBuffer(const struct v4l2_buffer &video_buffer);/*VIDIOC_DQBUF 采集的缓冲帧出队列*/bool PopVideoBuffer(const unsigned int memory_type, struct v4l2_buffer &video_buffer);private:unsigned long getEpochTimeShiftus();private:int m_video_fd;std::function<void(const VideoBufferStruct&)> m_video_data_callback;std::string m_video_device_name;std::vector<std::pair<unsigned long, unsigned int>> m_video_userptr;
};#endif // _V4L2USERPTRMODE_H_

v4l2userptrmode.cpp

#include "v4l2userptrmode.hpp"#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#include <fcntl.h> 
#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>bool V4L2CaptureVideoData::m_keeprunning=true;V4L2CaptureVideoData::V4L2CaptureVideoData()
{m_video_fd=-1;m_video_data_callback=nullptr;m_video_device_name.clear();m_video_userptr.clear();
}V4L2CaptureVideoData::~V4L2CaptureVideoData()
{if(m_video_fd!=-1){closeVideoDevice();}
}void V4L2CaptureVideoData::RegisterVideoDataProcessCallback(std::function<void(const VideoBufferStruct&)> func)
{m_video_data_callback=func;
}bool V4L2CaptureVideoData::OpenVideoDevice(std::string device_name)
{m_video_device_name=device_name;std::string device_head="/dev/video";if(m_video_device_name.compare(0, device_head.size(), device_head)!=0){std::cerr<<m_video_device_name<<" is not camera device"<<std::endl;return false;}m_video_fd = open(m_video_device_name.c_str(), O_RDWR /* required */ | O_NONBLOCK, 0);if (-1 == m_video_fd) {std::cerr<<"cannot open video device:"<<"device name="<<m_video_device_name<<",errno="<<errno<<",strerror="<<strerror(errno)<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::closeVideoDevice()
{if(m_video_fd<0){return true;}if(close(m_video_fd)==-1){std::cerr<<"close video device failed:"<<"errno="<<errno<<",strerror="<<strerror(errno)<<std::endl;m_video_fd=-1;return false;}m_video_fd=-1;return true;
}bool V4L2CaptureVideoData::QueryVideoDeviceCapability(const unsigned int capability)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}v4l2_capability video_cap;if(GetVideoDeviceCapability(video_cap)==false){return false;}if(!(video_cap.capabilities & capability)){std::cerr<<m_video_device_name<<" not support this capability="<<capability<<std::endl;return false;}return true;
}void V4L2CaptureVideoData::RegisterVideoUserptr(std::vector<std::pair<unsigned long, unsigned int>> &video_userptr)
{m_video_userptr=video_userptr;
}void V4L2CaptureVideoData::StartUserptrData()
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return;}if(QueryVideoDeviceCapability(V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING)==false){return;}if(m_video_userptr.size()==0){std::cerr<<"not input already allocated memory block for v4l2 using in userptr mode"<<std::endl;return;}struct v4l2_format video_format;GetVideoDeviceFormat(video_format);struct VideoBufferStruct  data_buffer;data_buffer.dev_name=m_video_device_name;data_buffer.pixel_format=video_format.fmt.pix.pixelformat;data_buffer.width=video_format.fmt.pix.width;data_buffer.height=video_format.fmt.pix.height;unsigned int video_req_buffer_cnt=m_video_userptr.size();struct v4l2_requestbuffers video_req_buffer;memset(&video_req_buffer,'\0',sizeof(video_req_buffer));video_req_buffer.count = video_req_buffer_cnt;video_req_buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;video_req_buffer.memory = V4L2_MEMORY_USERPTR;if(RequestVideoBuffer(video_req_buffer)==false){return;}for(int index=0;index<video_req_buffer_cnt;index++){struct v4l2_buffer tmp_video_buffer;tmp_video_buffer.index=index;tmp_video_buffer.type  = V4L2_BUF_TYPE_VIDEO_CAPTURE;tmp_video_buffer.memory = V4L2_MEMORY_USERPTR;tmp_video_buffer.m.userptr = m_video_userptr[index].first;tmp_video_buffer.length =m_video_userptr[index].second;if(PushVideoBuffer(tmp_video_buffer)==false){return;}}if(StartVideoCapture()==false){return;}fd_set fds;struct timeval tv;int ret;while(m_keeprunning==true){FD_ZERO (&fds);FD_SET (m_video_fd, &fds);tv.tv_sec = 3;tv.tv_usec = 0;ret = select (m_video_fd + 1, &fds, NULL, NULL, &tv);if (-1 == ret) {if (EINTR == errno){continue;}else{std::cerr<<"select failed:"<<"errno="<<errno<<",strerror="<<strerror(errno)<<std::endl;break;}}else if (0 == ret) {std::cerr<<"select timeout no data available."<<std::endl;break;}else{struct v4l2_buffer video_buffer_data;if(PopVideoBuffer(V4L2_MEMORY_USERPTR,video_buffer_data)==false){break;}data_buffer.data=(void*)m_video_userptr[video_buffer_data.index].first;data_buffer.data_len=video_buffer_data.bytesused;data_buffer.timestamp=video_buffer_data.timestamp.tv_sec*1000000+video_buffer_data.timestamp.tv_usec+getEpochTimeShiftus();m_video_data_callback(data_buffer);if(PushVideoBuffer(video_buffer_data)==false){return;}std::this_thread::sleep_for(std::chrono::milliseconds(10));}}if(StopVideoCapture()==false){return;}closeVideoDevice();
}bool V4L2CaptureVideoData::GetVideoDeviceCapability(v4l2_capability &cap)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_QUERYCAP, &cap);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_QUERYCAP failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}std::cout<<"camera v4l2_capability {"<<std::endl<<"       driver = "<<cap.driver<<std::endl<<"         card = "<<cap.card<<std::endl<<"     bus_info = "<<cap.bus_info<<std::endl<<"      version = "<<cap.version<<std::endl<<" capabilities = "<<cap.capabilities<<std::endl<<"  device_caps = "<<cap.device_caps<<std::endl<<"}"<<std::endl;return true;
}bool V4L2CaptureVideoData::GetVideoDevicePriority(unsigned int &priority)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_G_PRIORITY, &priority);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_G_PRIORITY failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}std::cout<<"video device get priority = "<<priority<<std::endl;return true;
}bool V4L2CaptureVideoData::SetVideoDevicePriority(const unsigned int priority)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}unsigned int bk_priority=priority;int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_S_PRIORITY, &bk_priority);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_S_PRIORITY failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}if(bk_priority!=priority){std::cerr<<"actual video device priority set "<<bk_priority<<" not input value "<<priority<<std::endl;return false;}std::cout<<"video device set priority = "<<priority<<std::endl;return true;
}bool V4L2CaptureVideoData::GetVideoDeviceLogStatus()
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_LOG_STATUS, NULL);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_LOG_STATUS failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::EnumVideoDeviceFormat(std::list<struct v4l2_fmtdesc> &fmtdesc)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}fmtdesc.clear();struct v4l2_fmtdesc tmp_fmtdesc;tmp_fmtdesc.index = 0;tmp_fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;int ret=0;while(!((ret == -1) && (errno != EINTR) && (errno != EAGAIN))){ret=ioctl(m_video_fd,VIDIOC_ENUM_FMT,&tmp_fmtdesc);if(ret==0){fmtdesc.push_back(tmp_fmtdesc);std::cout<<"camera v4l2_fmtdesc {"<<std::endl<<"       index = "<<tmp_fmtdesc.index<<std::endl<<"        type = "<<tmp_fmtdesc.type<<std::endl<<"       flags = "<<tmp_fmtdesc.flags<<std::endl<<" description = "<<tmp_fmtdesc.description<<std::endl<<" pixelformat = "<<std::hex<<tmp_fmtdesc.pixelformat<<std::dec<<std::endl<<"}"<<std::endl;tmp_fmtdesc.index++;} }if(fmtdesc.size()==0){std::cerr<<"get video format cout is 0"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::GetVideoDeviceFormat(v4l2_format &fmt)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}fmt.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_G_FMT, &fmt);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_G_FMT failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}std::cout<<"camera v4l2_format {"<<std::endl<<"                          type = "<<fmt.type<<std::endl<<"         v4l2_pix_format.width = "<<fmt.fmt.pix.width<<std::endl<<"        v4l2_pix_format.height = "<<fmt.fmt.pix.height<<std::endl<<"   v4l2_pix_format.pixelformat = "<<std::hex<<fmt.fmt.pix.pixelformat<<std::dec<<std::endl<<"         v4l2_pix_format.field = "<<fmt.fmt.pix.field<<std::endl<<"  v4l2_pix_format.bytesperline = "<<fmt.fmt.pix.bytesperline<<std::endl<<"     v4l2_pix_format.sizeimage = "<<fmt.fmt.pix.sizeimage<<std::endl<<"    v4l2_pix_format.colorspace = "<<fmt.fmt.pix.colorspace<<std::endl<<"          v4l2_pix_format.priv = "<<fmt.fmt.pix.priv<<std::endl<<"         v4l2_pix_format.flags = "<<fmt.fmt.pix.flags<<std::endl<<"}"<<std::endl;return true;
}bool V4L2CaptureVideoData::SetVideoDeviceFormat(const v4l2_format &fmt)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}v4l2_format tmp_fmt;memcpy(&tmp_fmt,&fmt,sizeof(tmp_fmt));int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_S_FMT, &tmp_fmt);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_S_FMT failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}if((tmp_fmt.fmt.pix.width==fmt.fmt.pix.width) && (tmp_fmt.fmt.pix.height==fmt.fmt.pix.height) && (tmp_fmt.fmt.pix.pixelformat==fmt.fmt.pix.pixelformat)){std::cout<<"camera set v4l2_format {"<<std::endl<<"                          type = "<<fmt.type<<std::endl<<"         v4l2_pix_format.width = "<<fmt.fmt.pix.width<<std::endl<<"        v4l2_pix_format.height = "<<fmt.fmt.pix.height<<std::endl<<"   v4l2_pix_format.pixelformat = "<<std::hex<<fmt.fmt.pix.pixelformat<<std::dec<<std::endl<<"}"<<std::endl;return true;}else{std::cerr<<"camera actual set v4l2_format {"<<std::endl<<"                          type = "<<tmp_fmt.type<<std::endl<<"         v4l2_pix_format.width = "<<tmp_fmt.fmt.pix.width<<std::endl<<"        v4l2_pix_format.height = "<<tmp_fmt.fmt.pix.height<<std::endl<<"   v4l2_pix_format.pixelformat = "<<std::hex<<tmp_fmt.fmt.pix.pixelformat<<std::dec<<std::endl<<"}"<<std::endl;return false;}
}bool V4L2CaptureVideoData::TrySetVideoDeviceFormat(const v4l2_format &fmt)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}std::cout<<"camera try set v4l2_format {"<<std::endl<<"                          type = "<<fmt.type<<std::endl<<"         v4l2_pix_format.width = "<<fmt.fmt.pix.width<<std::endl<<"        v4l2_pix_format.height = "<<fmt.fmt.pix.height<<std::endl<<"   v4l2_pix_format.pixelformat = "<<std::hex<<fmt.fmt.pix.pixelformat<<std::dec<<std::endl<<"         v4l2_pix_format.field = "<<fmt.fmt.pix.field<<std::endl<<"}"<<std::endl;int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_TRY_FMT, &fmt);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_TRY_FMT failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::EnumVideoDeviceFrameSize(const unsigned int pixel_format,std::list<struct v4l2_frmsizeenum> &frmsize)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}frmsize.clear();struct v4l2_frmsizeenum tmp_frmsize;tmp_frmsize.index=0;tmp_frmsize.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;tmp_frmsize.pixel_format = pixel_format;int ret=0;while(!((ret == -1) && (errno != EINTR) && (errno != EAGAIN))){ret=ioctl(m_video_fd,VIDIOC_ENUM_FRAMESIZES,&tmp_frmsize);if(ret==0){frmsize.push_back(tmp_frmsize);std::cout<<"camera v4l2_frmsizeenum {"<<std::endl<<"                        index = "<<tmp_frmsize.index<<std::endl<<"                         type = "<<tmp_frmsize.type<<std::endl<<"                 pixel_format = "<<std::hex<<tmp_frmsize.pixel_format<<std::dec<<std::endl<<"  v4l2_frmsize_discrete.width = "<<tmp_frmsize.discrete.width<<std::endl<<" v4l2_frmsize_discrete.height = "<<tmp_frmsize.discrete.height<<std::endl<<"}"<<std::endl;tmp_frmsize.index++;} }if(frmsize.size()==0){std::cerr<<"get video frame size cout is 0"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::EnumVideoDeviceFrameIntervals(const unsigned int pixel_format,const unsigned int width,const unsigned int height,std::list<struct v4l2_frmivalenum> &frmivals)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}frmivals.clear();struct v4l2_frmivalenum tmp_frmival;tmp_frmival.index = 0;tmp_frmival.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;tmp_frmival.pixel_format = pixel_format;tmp_frmival.width = width;tmp_frmival.height = height;int ret=0;while(!((ret == -1) && (errno != EINTR) && (errno != EAGAIN))){ret=ioctl(m_video_fd, VIDIOC_ENUM_FRAMEINTERVALS, &tmp_frmival);if(ret==0){frmivals.push_back(tmp_frmival);std::cout<<"Frame interval<"<<tmp_frmival.discrete.denominator / tmp_frmival.discrete.numerator<<"fps>"<<std::endl;std::cout<<"camera v4l2_frmivalenum {"<<std::endl<<"                  index = "<<tmp_frmival.index<<std::endl<<"                   type = "<<tmp_frmival.type<<std::endl<<"           pixel_format = "<<std::hex<<tmp_frmival.pixel_format<<std::dec<<std::endl<<"                  width = "<<tmp_frmival.width<<std::endl<<"                 height = "<<tmp_frmival.height<<std::endl<<"   v4l2_fract.numerator = "<<tmp_frmival.discrete.numerator<<std::endl<<" v4l2_fract.denominator = "<<tmp_frmival.discrete.denominator<<std::endl<<"  numerator/denominator = "<<tmp_frmival.discrete.denominator / tmp_frmival.discrete.numerator<<" fps"<<std::endl<<"}"<<std::endl;tmp_frmival.index++;}}if(frmivals.size()==0){std::cerr<<"get video frame intervals cout is 0"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::StartVideoCapture()
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_STREAMON, &type);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_STREAMON failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::StopVideoCapture()
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_STREAMOFF, &type);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_STREAMOFF failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::RequestVideoBuffer(const v4l2_requestbuffers &requestbuf)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}if(ioctl(m_video_fd, VIDIOC_REQBUFS, &requestbuf)==-1){std::cerr<<"ioctl VIDIOC_REQBUFS failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::GetVideoBuffer(const unsigned int memory_type,unsigned int index,struct v4l2_buffer &video_buffer)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}video_buffer.index = index;video_buffer.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;video_buffer.memory = memory_type;int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_QUERYBUF, &video_buffer);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_QUERYBUF failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}std::cout<<"camera v4l2_buffer {"<<std::endl<<"   index = "<<video_buffer.index<<std::endl<<"    type = "<<video_buffer.type<<std::endl<<"   flags = "<<video_buffer.flags<<std::endl<<"  memory = "<<video_buffer.memory<<std::endl<<"  length = "<<video_buffer.length<<std::endl<<"  offset = "<<std::hex<<video_buffer.m.offset<<std::dec<<std::endl<<"      fd = "<<std::hex<<video_buffer.m.fd<<std::dec<<std::endl<<" userptr = "<<std::hex<<video_buffer.m.userptr<<std::dec<<std::endl<<"}"<<std::endl;return true;
}bool V4L2CaptureVideoData::PushVideoBuffer(const v4l2_buffer &video_buffer)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_QBUF, &video_buffer);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_QBUF failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}return true;
}bool V4L2CaptureVideoData::PopVideoBuffer(const unsigned int memory_type,struct v4l2_buffer &video_buffer)
{if(m_video_fd==-1){std::cerr<<"not open video device,must open first"<<std::endl;return false;}video_buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;video_buffer.memory = memory_type;int ret=0;do{ret=ioctl(m_video_fd, VIDIOC_DQBUF, &video_buffer);} while (ret == -1 && ((errno == EINTR) || (errno == EAGAIN)));if(ret!=0){std::cerr<<"ioctl VIDIOC_DQBUF failed:("<<"errno="<<errno<<",strerror="<<strerror(errno)<<")"<<std::endl;return false;}return true;
}unsigned long V4L2CaptureVideoData::getEpochTimeShiftus()
{struct timeval epochtime;struct timespec  vsTime;gettimeofday(&epochtime, NULL);clock_gettime(CLOCK_MONOTONIC, &vsTime);unsigned long uptime_us = vsTime.tv_sec*1000000+(long)round(vsTime.tv_nsec/ 1000.0);unsigned long epoch_us =  epochtime.tv_sec*1000000+epochtime.tv_usec;return epoch_us - uptime_us;
}

测试代码test.cpp

#include "v4l2userptrmode.hpp"
#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>//信号绑定,绑定Ctrl+C
static void sig_handler(int sig) 
{if (sig == SIGINT) {V4L2CaptureVideoData::m_keeprunning = false;}
}// save picture to file
static int id_index = 0;
//视频帧数据处理函数
void VideoDataFunc(const VideoBufferStruct &video_data)
{std::cout << "device name:" << video_data.dev_name << ",timestamp:" << video_data.timestamp << ",width:" << video_data.width << ",height:" << video_data.height << ",data length:" << video_data.data_len << std::endl;std::string filename = "pictures_yuv/test" + std::to_string(id_index) + ".yuv";int file_fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0777);write(file_fd, video_data.data, video_data.data_len);close(file_fd);id_index++;
}int main(int, char **)
{signal(SIGINT, sig_handler); V4L2CaptureVideoData camera_read;//注册回调函数camera_read.RegisterVideoDataProcessCallback(VideoDataFunc);//打开视频设备if(camera_read.OpenVideoDevice("/dev/video0")==false){return -1;}struct v4l2_format video_fmt;memset(&video_fmt, '\0', sizeof(video_fmt));//获取当前视频设备的格式if(camera_read.GetVideoDeviceFormat(video_fmt)==false){return -1;}//设置视频设备的格式video_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;video_fmt.fmt.pix.width = 1280;video_fmt.fmt.pix.height = 720;video_fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;video_fmt.fmt.pix.field = V4L2_FIELD_ANY;if(camera_read.SetVideoDeviceFormat(video_fmt)==false){return -1;}//申请用户空间内存std::vector<std::pair<unsigned long, unsigned int>> video_userptr_block;void *userptr_databuffer[4];for (int index = 0; index < 4; index++){userptr_databuffer[index] = malloc(video_fmt.fmt.pix.sizeimage);video_userptr_block.push_back(std::make_pair((unsigned long)userptr_databuffer[index], video_fmt.fmt.pix.sizeimage));}//注册用户空间内存,用以接收图像数据camera_read.RegisterVideoUserptr(video_userptr_block);//开始采集数据camera_read.StartUserptrData();//释放用户空间申请的内存for (int index = 0; index < 4; index++){free(userptr_databuffer[index]);userptr_databuffer[index]=NULL;}return 0;
}

测试结果:
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/62101.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

浏览器缓存与协商缓存

1. 强缓存&#xff08;Strong Cache&#xff09; 定义 强缓存是指在缓存的资源有效期内&#xff0c;浏览器会直接使用缓存中的数据&#xff0c;而不会发起网络请求。也就是说&#xff0c;浏览器会直接从本地缓存读取资源&#xff0c;不会与服务器进行任何交互。 如何控制强缓…

AI 写作(一):开启创作新纪元(1/10)

一、AI 写作&#xff1a;重塑创作格局 在当今数字化高速发展的时代&#xff0c;AI 写作正以惊人的速度重塑着创作格局。AI 写作在现代社会中占据着举足轻重的地位&#xff0c;发挥着不可替代的作用。 随着信息的爆炸式增长&#xff0c;人们对于内容的需求日益旺盛。AI 写作能够…

RabbitMQ 篇-深入了解延迟消息、MQ 可靠性(生产者可靠性、MQ 可靠性、消费者可靠性)

??博客主页&#xff1a;【_-CSDN博客】** 感谢大家点赞??收藏评论** 文章目录 ???1.0 RabbitMQ 的可靠性 ? ? ? ? 2.0 发送者的可靠性 ? ? ? ? 2.1 生产者重试机制 ? ? ? ? 2.2 生产者确认机制 ? ? ? ? 2.2.1 开启生产者确认机制 ? ? ? ? 2.2…

问:SpringBoot核心配置文件都有啥,怎么配?

在SpringBoot的开发过程中&#xff0c;核心配置文件扮演着至关重要的角色。这些文件用于配置应用程序的各种属性和环境设置&#xff0c;使得开发者能够灵活地定制和管理应用程序的行为。本文将探讨SpringBoot的核心配置文件&#xff0c;包括它们的作用、区别&#xff0c;并通过…

【机器学习】数据集合集!

本文将为您介绍经典、热门的数据集&#xff0c;希望对您在选择适合的数据集时有所帮助。 1 privacy 更新时间&#xff1a;2024-11-26 访问地址: GitHub 描述&#xff1a; 此存储库包含 TensorFlow Privacy&#xff08;一种 Python&#xff09;的源代码 库&#xff0c;其中包…

Linux V4L2框架介绍

linux V4L2框架介绍 V4L2框架介绍 V4L2&#xff0c;全称Video for Linux 2&#xff0c;是Linux操作系统下用于视频数据采集设备的驱动框。它提供了一种标准化的方式使用户空间程序能够与视频设备进行通信和交互。通过V4L2接口&#xff0c;用户可以方便地实现视频图像数据的采…

[网安靶场] [更新中] UPLOAD LABS —— 靶场笔记合集

GitHub - c0ny1/upload-labs: 一个想帮你总结所有类型的上传漏洞的靶场一个想帮你总结所有类型的上传漏洞的靶场. Contribute to c0ny1/upload-labs development by creating an account on GitHub.https://github.com/c0ny1/upload-labs 0x01&#xff1a;UPLOAD LABS 靶场初识…

SpringBoot社团管理:用户体验优化

3系统分析 3.1可行性分析 通过对本社团管理系统实行的目的初步调查和分析&#xff0c;提出可行性方案并对其一一进行论证。我们在这里主要从技术可行性、经济可行性、操作可行性等方面进行分析。 3.1.1技术可行性 本社团管理系统采用SSM框架&#xff0c;JAVA作为开发语言&#…

org.apache.log4j的日志记录级别和基础使用Demo

org.apache.log4j的日志记录级别和基础使用Demo&#xff0c;本次案例展示&#xff0c;使用是的maven项目&#xff0c;搭建的一个简单的爬虫案例。里面采用了大家熟悉的日志记录插件&#xff0c;log4j。来自apache公司的开源插件。 package com.qian.test;import org.apache.log…

2024年第15届蓝桥杯C/C++组蓝桥杯JAVA实现

目录 第一题握手&#xff0c;这个直接从49累加到7即可&#xff0c;没啥难度&#xff0c;后面7个不握手就好了&#xff0c;没啥讲的&#xff0c;(然后第二个题填空好难&#xff0c;嘻嘻不会&#xff09; 第三题.好数​编辑 第四题0R格式 宝石组合 数字接龙 最后一题:拔河 第…

matlab根据excel表头筛选表格数据

有如下表格需要筛选&#xff1a; 如果要筛选style中的A&#xff0c;color中的F2&#xff0c;num中的3。 代码如下&#xff1a; clear;clc; file_Pathstrcat(F:\csdn\,test1.xlsx); %表格路径、文件名 E1readtable(file_Path,Sheet,1); %读取表格中的字母和数字,1代表第一个…

day05(单片机高级)PCB基础

目录 PCB基础 什么是PCB&#xff1f;PCB的作用&#xff1f; PCB的制作过程 PCB板的层数 PCB设计软件 安装立创EDA PCB基础 什么是PCB&#xff1f;PCB的作用&#xff1f; PCB&#xff08;Printed Circuit Board&#xff09;&#xff0c;中文名称为印制电路板&#xff0c;又称印刷…

【机器学习】——朴素贝叶斯模型

&#x1f4bb;博主现有专栏&#xff1a; C51单片机&#xff08;STC89C516&#xff09;&#xff0c;c语言&#xff0c;c&#xff0c;离散数学&#xff0c;算法设计与分析&#xff0c;数据结构&#xff0c;Python&#xff0c;Java基础&#xff0c;MySQL&#xff0c;linux&#xf…

【Android+多线程】异步 多线程 知识总结:基础概念 / 多种方式 / 实现方法 / 源码分析

1 基本概念 1.1 线程 定义&#xff1a;一个基本的CPU执行单元 & 程序执行流的最小单元 比进程更小的可独立运行的基本单位&#xff0c;可理解为&#xff1a;轻量级进程组成&#xff1a;线程ID 程序计数器 寄存器集合 堆栈注&#xff1a;线程自己不拥有系统资源&#…

Error: Invalid version flag: if 问题排查

问题描述&#xff1a; 国产化系统适配&#xff0c;arm架构的centos 在上面运行docker 启动后需要安装数据库 依赖perl 在yum install -y perl 时提示&#xff1a; “Error: Invalid version flag: if”

华为鸿蒙内核成为HarmonyOS NEXT流畅安全新基座

HDC2024华为重磅发布全自研操作系统内核—鸿蒙内核&#xff0c;鸿蒙内核替换Linux内核成为HarmonyOS NEXT稳定流畅新基座。鸿蒙内核具备更弹性、更流畅、更安全三大特征&#xff0c;性能超越Linux内核10.7%。 鸿蒙内核更弹性&#xff1a;元OS架构&#xff0c;性能安全双收益 万…

五种创建k8s的configMap的方式及configmap使用

configmap介绍 Kubernetes 提供了 ConfigMap 来管理应用配置数据&#xff0c;将配置信息从容器镜像中解耦&#xff0c;使应用更灵活、可移植。 1、基于一个目录来创建ConfigMap ​ 你可以使用 kubectl create configmap 基于同一目录中的多个文件创建 ConfigMap。 当你基于目…

如何将本地项目上传到gitee上

本地项目代码想上传到gitee管理、使用idea编辑器操作上传 新建仓库、填写信息 创建好了仓库&#xff0c;把HTTPS路径复制一下&#xff0c;之后会用到。 用命令进入项目进行git初始化 执行命令&#xff1a; cd 文件夹 git init 用idea把项目打开&#xff0c;然后配置一下gi…

大型语言模型LLM - Finetuning vs Prompting

资料来自台湾大学李宏毅教授机器学课程ML 2023 Spring&#xff0c;如有侵权请通知下架 台大机器学课程ML 2023 Springhttps://speech.ee.ntu.edu.tw/~hylee/ml/2023-spring.php2023/3/10 课程 機器如何生成文句 内容概要 主要探讨了大型语言模型的两种不同期待及其导致的两类…

Scikit-learn Pipeline完全指南:高效构建机器学习工作流

在机器学习工作流程中,组合估计器通过将多个转换器(Transformer)和预测器(Predictor)整合到一个管道(Pipeline)中,可以有效简化整个过程。这种方法不仅简化了数据预处理环节,还能确保处理过程的一致性,最大限度地降低数据泄露的风险。构建组合估计器最常用的工具是Scikit-learn…