Module 13 · Lesson 38 of 98

V4L2 capture and mmap streaming

Inspect a V4L2 capture node, interpret YUYV and NV12 layouts, and explain how mapped buffers move between a Linux camera driver and an application.

  • Beginner to advanced
  • 6 min read
  • 16 min lab
What you will need

Ubuntu 24.04 with v4l-utils and an accessible V4L2 capture device for live streaming. The format and queue exercises also run in WSL2 or a VM without a camera.

Your place in the module
By the end you can 4 objectives
  • Identify a V4L2 capture node and list its advertised formats.
  • Distinguish the byte layout of YUYV from the image planes of NV12.
  • Order buffer allocation, mapping, queueing, dequeueing, and cleanup.
  • Verify that a capture device can stream a bounded set of frames using mmap.
Video coming soonV4L2 capture and mmap streaming
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Classifying the bottleneck from the counters
  • The Memory Throughput summary can be high even when DRAM throughput is low.
  • Low throughput and frequent cycles without eligible warps support a latency diagnosis.
  • A high stall ranking needs corroboration from scheduler activity and resource utilisation.
01

Choosing a capture node and pixel format

3 min read

You can now profile GPU code. Now you feed the GPU from a camera, and this lesson answers how V4L2 captures frames and streams them with mmap.

A camera can produce a valid frame that looks corrupted in your application. For example, if the driver adds padding at the end of each image row and the application assumes tightly packed rows, every row after the first can start at the wrong byte. The V4L2 capture interface gives the application the actual row stride along with the format and dimensions. Video capture interface

V4L2 stands for Video4Linux2. A capture application opens a character device such as /dev/video0 and uses ioctl() requests on its file descriptor to configure and control capture. The number in /dev/videoN identifies a node on the running system. A device can expose several nodes, so check which one supports video capture. Use VIDIOC_QUERYCAP and read device_caps when capabilities contains V4L2_CAP_DEVICE_CAPS. Otherwise, use capabilities. This lesson follows the single-planar capture API, which uses V4L2_CAP_VIDEO_CAPTURE and buffer type V4L2_BUF_TYPE_VIDEO_CAPTURE. Check for V4L2_CAP_STREAMING before attempting streaming.

With v4l-utils installed, list the devices and inspect the candidate node. Substitute the path that belongs to your camera. These commands need a capture device visible to the Linux system where they run.

bash
v4l2-ctl --list-devices
v4l2-ctl -d /dev/video0 --all
v4l2-ctl -d /dev/video0 --list-formats-ext

The format listing lets you select a pixel format and see the frame sizes and intervals the driver enumerates. In a program, use VIDIOC_ENUM_FMT to enumerate formats for the chosen buffer type. To configure capture, pass the desired width, height, and pixel format to VIDIOC_S_FMT. Read back the returned fields after success. The driver can adjust the request, and the values it returns govern the stream. VIDIOC_G_FMT lets you inspect the active format.

A YUYV and NV12 both store luma (Y) and chroma (Cb and Cr), but they arrange and share those samples differently.

  • YUYV stores each horizontal pair of pixels as Y0 Cb Y1 Cr. Each pixel has its own luma and the pair shares chroma. This is packed YUV 4:2:2.
  • NV12 stores a full-resolution luma plane followed by an interleaved chroma plane in the contiguous NV12 layout. The chroma plane stores Cb Cr pairs, with one pair for each two-by-two block of luma samples. This is YUV 4:2:0.
YUYV and NV12 layoutsYUYVNV12Luma storagePacked withchromaFull-resolution planeChroma storagePacked withlumaInterleavedCb Cr planeChroma sharingHorizontalpixel pairTwo-by-twopixel block
YUYV packs samples together. NV12 groups luma and chroma into separate image planes.

The single-planar API can carry contiguous NV12 in one mapped buffer even though the image layout has two planes. Read bytesperline as the row stride in bytes and sizeimage as the buffer size needed for the negotiated image format. For YUYV, the first pair in each row starts at the row's stride offset from the base. For contiguous NV12, the chroma plane follows the full luma plane, including luma row padding. Use the returned height and stride to locate it. Width describes the visible pixels. Stride tells you where the next row begins.

02

Allocating and mapping buffers

2 min read

Set the format before allocating buffers so the driver can size them for that layout. Prepare a struct v4l2_requestbuffers with the capture type, memory set to V4L2_MEMORY_MMAP, and count set to the number of buffers you want. Call VIDIOC_REQBUFS and check its result. The driver returns the actual count in the same structure. Use that count when creating your buffer records and stop setup if the allocation cannot support your capture loop. A device can advertise streaming while rejecting a particular streaming memory method. The request tests whether the driver can provide buffers for this method and buffer type.

For every index from zero through the returned count minus one, fill a struct v4l2_buffer with the buffer type, memory method, and index. Call VIDIOC_QUERYBUF to obtain the buffer's length and m.offset. Pass that length and offset to mmap() with the device file descriptor, PROT_READ | PROT_WRITE, and MAP_SHARED. Check for MAP_FAILED. Store the returned address and length under the same index. If setup fails halfway through, you can use those records to unmap the buffers that were mapped successfully.

Preparing mapped capture buffersSet formatUsereturnedlayoutRequestbuffersUsereturnedcountQuery eachbufferGet offsetand lengthMap eachbufferSaveaddress byindexSet formatUsereturnedlayoutRequestbuffersUsereturnedcountQuery eachbufferGet offsetand lengthMap eachbufferSaveaddress byindex
The driver returns the buffer count and supplies the offset and length for each mapping.

Three byte counts come from different steps. sizeimage describes storage needed by the negotiated format. The length returned by VIDIOC_QUERYBUF is the extent to map and later unmap. The bytesused returned when you dequeue tells you how much of that buffer is occupied by the captured payload. Keep the mapping length for resource management and check the payload size before reading a frame.

Mapping gives the application a virtual address for the driver's capture buffer. It can read the completed payload through this address without using read() to copy it into a separate application buffer. The mapping alone gives no indication of whether a frame is ready. The queue operations determine when the program can use the bytes.

03

Streaming, reading, and returning frames

3 min read

Queue the mapped buffers with VIDIOC_QBUF, passing the capture type, memory method, and index for each one. Then call VIDIOC_STREAMON with the capture buffer type. The driver can fill the queued buffers as frames arrive. A completed buffer remains with the driver until the application receives it through VIDIOC_DQBUF.

On a blocking file descriptor, VIDIOC_DQBUF can wait for a completed frame. With O_NONBLOCK, it returns -1 with errno set to EAGAIN when there is no completed buffer available. A program can use poll() with a finite timeout to wait for readable events before attempting another dequeue. Treat a timeout as a period with no reported readiness and check the dequeue result whenever you call it.

On success, use the returned index to find the mapped address and bytesused to inspect the payload extent. The returned metadata also includes a frame sequence and a timestamp. Check flags for V4L2_BUF_FLAG_ERROR. If the flag is set, skip processing the suspect frame and return the buffer so capture can continue. For a usable frame, finish every read of the mapped bytes before calling VIDIOC_QBUF on that index. If a worker needs to keep the frame after requeueing, give it a separate copy while the application still owns the buffer.

Ownership of a mapped bufferApplication owns bufferQueued for captureCompleted in driverTransitionsVIDIOC_QBUFApplication ownsbufferQueued for captureCapture completesQueued for captureCompleted in driverVIDIOC_DQBUFCompleted in driverApplication ownsbufferApplication owns bufferQueued for captureCompleted in driverTransitionsVIDIOC_QBUFApplicationowns bufferQueued forcaptureCapture completesQueued forcaptureCompletedin driverVIDIOC_DQBUFCompletedin driverApplicationowns buffer
The same mapping persists while the buffer changes ownership on each cycle.

Once requeue succeeds, the driver can overwrite the mapped bytes. A saved pointer still contains the same address, but it can now refer to a buffer being filled with another frame. The buffer index identifies reusable storage. The sequence field identifies the frame's position in the capture sequence. If the program holds every dequeued buffer, the driver eventually runs out of available storage for incoming frames.

A bounded streaming command gives you a way to test capture before writing that loop. Use a node with a working active capture format. This command requests four mmap buffers, captures up to 30 frames on a successful run, and sends the payloads to /dev/null so no image file is created.

bash
v4l2-ctl -d /dev/video0 --stream-mmap=4 --stream-count=30 --stream-to=/dev/null

In your own program, finish outstanding reads and stop capture with VIDIOC_STREAMOFF. This removes buffers from the driver queues. Unmap each address using its saved length, then close the descriptor. To free the buffer allocation while keeping the device open, follow unmapping with VIDIOC_REQBUFS using a count of zero and the same buffer type and memory method.

The Jetson camera stack and GStreamer follows the frame beyond this capture loop and explains where V4L2 and Argus fit when you assemble a camera pipeline.

Key takeaways

  • The format returned by VIDIOC_S_FMT defines how the application interprets captured bytes.
  • VIDIOC_REQBUFS returns the actual buffer count, and VIDIOC_QUERYBUF supplies each buffer's mapping parameters.
  • A successful VIDIOC_DQBUF gives the application a buffer index and frame metadata. VIDIOC_QBUF returns the buffer to the driver.
  • The mmap mapping persists across frames. The application's right to access a buffer changes as the buffer moves through the queue.
Reflect
  1. Explain to a colleague, in two sentences: identify a V4L2 capture node and list its advertised formats.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close