Linux V4L2 notes(3)

An example to use V4L2 API (MMAP streaming I/O).

1.  Open the device

v4l_fd = open (“/dev/videox”, O_RDWR, 0); 

ioctl(v4l_fd, VIDIOC_QUERYCAP, &cap); 

check if V4L2_CAP_VIDEO_CAPTURE and V4L2_CAP_STREAMING is set;

2. Change device properties, select a video and audio input, video standard, cropping, picture brightness, etc

ioctl(v4l_fd, VIDIOC_S_INPUT, &input); 

ioctl(v4l_fd, VIDIOC_G_STD, &std); 

ioctl(v4l_fd, VIDIOC_S_STD, &std); 

ioctl(v4l_fd, VIDIOC_CROPCAP, &cropcap); 

ioctl(v4l_fd, VIDIOC_S_CROP, &crop); 

ioctl(v4l_fd, VIDIOC_S_PARAM, &param);  //high quality capture, frame rate, etc

3. negotiate a data format

ioctl(v4l_fd, VIDIOC_S_FMT, &fmt);  // set data format, interlaced or not

ioctl(v4l_fd, VIDIOC_G_FMT, &fmt);  // get the captured size: fmt.fmt.pix.width/height

4. negotiate an input method. For MMAP streaming IO, request number of buffers, and queue them.


req.count = num;


req.memory = V4L2_MEMORY_MMAP;

ioctl(v4l_handle, VIDIOC_REQBUFS, &req); 

for each buffer,

struct v4l2_buffer buf_info;

ioctl(, VIDIOC_QUERYBUF, &buf_info); // query the buffer information for each requested buffer;

buffers[i]. length/offset = output_buf_info.length/offset;

buffers[i].start = mmap(NULL, buffers[i].length, READ|WRITE|MAP_SHARED, buffers[i].offset;


buf_info.memory = V4L2_MEMORY_CAPTURE;

ioctl(, VIDIOC_QBUF, &buf_info);

5. the actual input loop


// loop until get the desired number of buffers


    ioctl(v4l_fd, VIDIOC_DQBUF, &capture_buf); // get a captured buffer

process/display the buffer


    ioctl(v4l_fd, VIDIOC_QBUF, &capture_buf);


6. close the device

ioctl(v4l_fd, VIDIOC_STREAMOFF, …);

for each buffer,

munmap(buffers[j].start, buffers[j].length);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s