A camera driver hands your code frames through a queue of buffers. Every buffer left waiting is a frame of delay. Drain the queue to the newest frame and the delay drops to one frame period.
Learn how Linux moves a picture from the sensor to your robot code, and to the GPU, without losing it, mislabelling it or copying it.
Set the number of buffers and the speed of your controller. Watch the age of each frame it handles. Then switch on Drain to newest. Then we build, piece by piece, the whole path: the call sequence, the timestamps, the media graph, libcamera, the memory layout and the zero-copy hand-off.
You need a rough idea of what a queue is (things leave in the order they arrived) and a little C. We build the rest from zero.
Built from the primary sources: the Linux kernel V4L2 userspace API, the libcamera project, the NVIDIA Jetson documentation and a latency analysis by Transitive Robotics. Full list in the Field Guide.
A model, not a camera: a 30 frames per second producer (33.3 ms period), N buffers, and one consumer that takes a fixed time per frame. When no buffer is free, the model drops that frame and its sequence number still counts, as many drivers do. Age is the time from capture to the moment your code takes the frame, in frame periods. Real drivers differ.
On real hardware. On a Raspberry Pi 5 with a USB UVC webcam, write the Chapter 1 loop, log the age and the sequence of every frame, and run it with 2 buffers and with 6 while the loop sleeps 40 ms per frame.
Chapter 0
See why a frame that sat in a queue is an old frame, and measure its age with one subtraction
A small wheeled robot follows a ball across a table. The camera runs at 30 frames per second. The code finds the ball in each picture and steers toward it. On the bench it works well. On the floor it always swings wide at the end of a turn, and nothing in the logs looks wrong.
The code is correct. The pictures are old. Each frame the code reads was taken a fifth of a second ago, so the robot steers toward where the ball was. Nobody notices, because every frame arrives, in order, with no error.
Think of a frame as a letter. The camera posts one every 33 milliseconds. The driver puts each letter in a buffer, a block of memory big enough for one picture. Your code takes letters from a pile in the order they arrived, oldest first.
If your code keeps up, the pile stays empty and each letter is read the moment it lands. If your code falls behind, the pile grows. Every letter in the pile is one more that you must read before you reach the newest one. That is the whole problem.
The pile is a queue: first in, first out. Linux gives every camera driver such a queue. Chapter 1 shows the calls that use it. For now we only need one fact about how it behaves.
Each frame carries a timestamp, the moment the driver recorded for it. Chapter 3 explains exactly which moment. The age of a frame is the clock now, minus that timestamp. You can compute it in a few lines.
cstruct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); /* same clock as buf.timestamp when the V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC flag is set */ double age_ms = (now.tv_sec - buf.timestamp.tv_sec) * 1000.0 + (now.tv_nsec / 1e6) - (buf.timestamp.tv_usec / 1e3);
Log age_ms for every frame your controller uses. A healthy loop shows numbers near zero to one frame period. A loop with a backlog shows numbers that climb in steps of 33 ms. You find the problem by measuring, not by guessing.
Take a queue of 6 buffers and a controller that needs exactly one frame period per frame. One buffer is in your hands. Five are full and waiting. The oldest of the five was captured five periods ago.
age = 5 × 33.3 ms = 166.7 ms error = 0.50 m/s × 0.1667 s = 0.083 m (illustrative speed)
A ball moving at 0.5 meters per second travels 8.3 centimeters in that time. The controller sees the ball 8.3 cm behind where it truly is. Try the numbers yourself.
The solid disc is where the ball is now. The ring is where the controller thinks it is, from the frame it holds. Drag the number of full buffers waiting and the ball speed.
Illustrative: the ball speed and track are made up. The 33.3 ms frame period is exact for 30 frames per second. The model ignores exposure, readout and processing time, which only add to the age.
On real hardware. Take a Raspberry Pi 5 with a USB UVC webcam, which shows up as a plain V4L2 node. Add the age code from this chapter to a capture loop, run it with the queue left alone, and log the age of 300 frames.
Slide the waiting buffers to 0. The ring sits on the disc. That is the best case, and it is what draining the queue gives you. Slide to 5. The ring trails by 8 cm. At 2 m/s the same five frames cost 33 cm, about a foot.
A pile builds up in two ways. The first is steady: the controller is slower than the camera. If it needs 40 ms per frame, it falls behind by 6.7 ms every frame. The queue fills until it hits its limit.
The second is a hiccup. A garbage collection, a disk write or a busy CPU core pauses the controller for 250 ms. The camera keeps posting. About eight frames land in the pile while you are away (250 / 33.3 is 7.5). Afterwards you read the stale frames first.
Look at the hero again. With 2 buffers the queue is short, so frames are fresh, but the driver drops some. With 6 buffers nothing is dropped early, but frames grow old. A bigger queue never makes the controller faster. It only chooses where the loss shows up.
If you cannot keep up, you must lose something. You can lose the newest frames, which the driver drops when the queue is full. Or you can lose the oldest, which you skip on purpose. For control, the old frames are worthless. Skip them.
This is drain to newest: take every full buffer out of the queue, keep only the last, and hand the others straight back to the driver. Switch it on in the hero and the age falls under one frame. The rest of this lesson builds the machinery so you can write that loop with confidence.
Before this lesson, sensor to CSI shows how pixels leave the sensor, and writing the driver shows the kernel side of the queue. Virtual memory and DMA, the topic behind a buffer, is a separate lesson in this series that is not written yet. We explain what we need inline.
Chapter 1
Follow one buffer through eleven calls, from opening the camera to handing the buffer back
You plug in a camera and want pictures. On Linux a camera is a file. You open it, you ask it for memory, and you ask it to start. Then frames flow, and you must keep returning the memory you finished with.
V4L2 (Video for Linux 2) is the kernel interface for this. It is a set of ioctl calls: one system call, ioctl(fd, request, &struct), where the request number says what to do and the struct carries the details. The names all start with VIDIOC_.
Three things take part. The device node, such as /dev/video0, is the file you open. The driver is the kernel code behind it. And the buffers are blocks of memory that hold one frame each.
Buffers pass between you and the driver like a plate on a counter. A plate is either with the driver, which fills it with a picture, or with you, who reads it. The two calls that move plates are VIDIOC_QBUF (give a buffer to the driver) and VIDIOC_DQBUF (take a filled buffer back). The kernel documentation words them as enqueue an empty buffer in the driver’s incoming queue, and dequeue a filled buffer from its outgoing queue.
V4L2_MEMORY_MMAP), your own pointers (USERPTR) or shared file descriptors (DMABUF). The driver tells you how many it really made.mmap(), once per buffer, give you a pointer into each buffer.The kernel documentation says that for capture it is customary to enqueue all the mapped buffers first, and only then start. By default DQBUF blocks until a buffer is ready. With O_NONBLOCK it returns the error EAGAIN instead. That second behavior is the key to draining, in the next chapter.
Step through it. Watch the four buffers change state and read the call that causes each change.
Press Next call to run one ioctl. Dashed purple is a buffer the driver may fill. Teal is a buffer you hold. Then try the broken order with the toggle.
A model of the call order from the kernel documentation, with 4 buffers. In the broken order the model assumes the camera runs 3 frames before your code queues anything, and those 3 frames are lost. What a real driver does with no queued buffer depends on the driver.
On real hardware. On a Raspberry Pi 5 with a USB UVC webcam, run your capture program under strace -e trace=ioctl and read the order of the calls. Then move STREAMON before the queueing loop and compare the first sequence number you see.
This is the core of a capture program. Error checks are cut to keep the shape visible. The struct names are the real ones from <linux/videodev2.h>.
cint fd = open("/dev/video0", O_RDWR | O_NONBLOCK); struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE }; f.fmt.pix.width = 1920; f.fmt.pix.height = 1080; f.fmt.pix.pixelformat = V4L2_PIX_FMT_NV12; ioctl(fd, VIDIOC_S_FMT, &f); /* read f back: the driver may change it */ struct v4l2_requestbuffers rb = { .count = 4, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP }; ioctl(fd, VIDIOC_REQBUFS, &rb); /* rb.count is what you really got */ for (int i = 0; i < rb.count; i++) { struct v4l2_buffer b = { .type = rb.type, .memory = rb.memory, .index = i }; ioctl(fd, VIDIOC_QUERYBUF, &b); map[i] = mmap(NULL, b.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, b.m.offset); ioctl(fd, VIDIOC_QBUF, &b); /* give it to the driver */ } enum v4l2_buf_type t = V4L2_BUF_TYPE_VIDEO_CAPTURE; ioctl(fd, VIDIOC_STREAMON, &t); for (;;) { struct pollfd p = { .fd = fd, .events = POLLIN }; poll(&p, 1, 1000); struct v4l2_buffer b = { .type = rb.type, .memory = rb.memory }; if (ioctl(fd, VIDIOC_DQBUF, &b) == 0) { process(map[b.index], b.bytesused, b.sequence, &b.timestamp); ioctl(fd, VIDIOC_QBUF, &b); /* hand it back */ } }
The data flow is worth saying aloud. The pixels never move between the driver and your program. The driver writes into memory that you also mapped. The only things that cross the ioctl are small structs: an index, a length, a sequence number and a timestamp. Moving a buffer means moving permission to use it.
Suppose you call VIDIOC_STREAMON first and queue buffers after. The symptom is subtle. The program works, but the first few frames are missing, or the first sequence number you see is 3 and not 0. Nothing prints an error.
The measurement is the first b.sequence you dequeue. It should be 0 or 1 on a fresh stream. If it starts higher, the camera ran before the driver had anywhere to write. Turn on the toggle in the device and step to the end. The log shows three lost frames.
The fix is the order the documentation calls customary. Queue every buffer. Then start the stream. Some drivers also state a minimum number of queued buffers they need before they start. The kernel page says the driver may require a minimum number of buffers enqueued at all times. So never request fewer buffers than your driver needs, and read back rb.count.
MMAP is the default: the kernel allocates. USERPTR lets your program supply memory. DMABUF lets another device’s buffer be passed in as a file descriptor on each QBUF. Chapter 7 uses that last one to reach the GPU without a copy.VIDIOC_DQBUF returns buffer 2, what must your program do with it before the driver can use it again?Chapter 2
Choose how many buffers to request by seeing what each extra one saves and what it costs
A pot of soup must feed guests who arrive every 33 milliseconds. Your ladle is sometimes slow. Spare bowls on the counter let you survive a slow moment without turning guests away. But a guest who waits behind five full bowls eats cold soup.
Spare bowls are buffers. The number you pass in VIDIOC_REQBUFS is the count of bowls. Too few, and the driver has nowhere to write a new frame while you are busy. Too many, and a backlog can hide in the queue and age every frame you use.
One buffer is always in your hands while you process. The rest are in the driver’s hands, either empty or full. Call the count N. Then at most N − 1 buffers can be waiting for you.
That gives two simple results. They come straight from the queue model in the hero.
Robustness. Suppose your code stalls for L milliseconds. In that time L / 33.3 frames arrive. The N − 1 spare buffers absorb that many. The driver has to drop the rest.
frames dropped ≈ L / 33.3 − (N − 1) (when this is above zero)
For a 250 ms stall, 250 / 33.3 = 7.5 frames arrive. With N = 6 you have 5 spare buffers, so about 2.5 frames are dropped. The model gives 3. With N = 2 you have 1 spare, so about 6.5 are dropped. The model gives 7.
Latency. Every full buffer that waits is one more frame of age. The worst age is N − 1 periods if you read in arrival order. If your code is also slower than the camera, the queue stays full and the age sits at that worst case.
age ≈ (N − 1) × (controller time per frame) (when the controller is slower than the camera)
With N = 6 and 40 ms per frame, that is 5 × 40 = 200 ms, which is 6 frame periods. The hero shows a little less, about 5.4, because the queue is not full at every moment. A steady backlog is the case where a bigger N hurts most.
For each count from 1 to 8, the model runs your controller through a stall. Red bars are frames the driver dropped. The yellow line is the average age of frames in the 2.5 seconds after the stall.
Model: a 30 frames per second producer, one stall starting at 2.0 s, a fixed controller time per frame. Age is measured when your code takes a frame. Drops are frames the driver had no free buffer for. Your own numbers will differ with your driver and load.
On real hardware. On a Raspberry Pi 5 with a USB UVC webcam, run the capture loop with 2, 4, 6 and 8 buffers (v4l2-ctl --stream-mmap=N sets the count for a quick test). Add one usleep(250000) in the loop and count the sequence gaps for each count.
Slide the stall to 100 ms. Four buffers already give zero drops. Slide it to 400 ms. Even 8 buffers drop 5 frames. Now look at the yellow line. It climbs with every buffer you add, because the extra buffers keep stale frames for your code to read.
Turn on Drain to newest. The yellow line falls to nearly zero for every N. The red bars stay the same, because the driver still has the same number of spare buffers. Draining fixes age. It does not fix a stall. That asks for more buffers.
The kernel documentation’s own mmap example asks for 20 buffers and then checks that it got at least five. It is a worked example, not a rule. A handful is common practice for a robot loop: about 4 to 6, which is the usual rule of thumb. It gives room for a short stall while keeping the worst age to a few frames. And you drain to keep it from mattering.
The driver may also give you a different count than you asked for. It may need a minimum to run. Read back the count in rb.count and size your code from that number, not from your request.
Open the device with O_NONBLOCK. Then keep calling VIDIOC_DQBUF. Each success is another full buffer. The first EAGAIN says the outgoing queue is empty. Keep the last buffer. Return every earlier one at once.
cstruct v4l2_buffer newest = {0}, b; int have = 0; for (;;) { memset(&b, 0, sizeof b); b.type = TYPE; b.memory = V4L2_MEMORY_MMAP; if (ioctl(fd, VIDIOC_DQBUF, &b) < 0) break; /* EAGAIN: queue is empty */ if (have) ioctl(fd, VIDIOC_QBUF, &newest); /* old one goes straight back */ newest = b; have = 1; } if (have) { if (last_seq && newest.sequence != last_seq + 1) log_gap(last_seq, newest.sequence); /* dropped or skipped frames */ last_seq = newest.sequence; use(map[newest.index], newest.bytesused); ioctl(fd, VIDIOC_QBUF, &newest); }
The symptom is a control loop that twitches once in a while. The logs look clean, because a dropped frame produces no error. The program just never sees that frame.
The measurement is the sequence field. The kernel documents it as set by the driver, counting frames in sequence. A jump from 1041 to 1045 means three frames did not reach you. They were dropped by the driver or skipped by your drain. The code above logs each gap.
The fix depends on the cause. Gaps right after a pause point to too few buffers. Gaps every frame point to a controller slower than the camera. Skipped frames from a drain are on purpose, so count them separately and do not alarm on them.
Chapter 3
Read which moment and which clock a frame’s stamp uses, so you can fuse it with a motion sensor
Your robot has a camera and an IMU (inertial measurement unit, a chip that measures turning and acceleration). A filter combines them. It asks: when was this picture taken? It compares that time with the IMU’s sample times. If the camera’s answer is wrong by 25 ms, the filter blends a picture with the wrong motion.
A timestamp is only useful if you know two things. Which moment of the frame does it mark? And which clock does it count on? V4L2 lets the driver choose both, and tells you the choice in the flags of each buffer.
A camera frame is not one instant. The sensor first exposes: light falls on the pixels for some milliseconds. Then it reads out: it sends the pixel values to the receiver, row by row. The whole frame takes tens of milliseconds from the first photon to the last pixel.
V4L2 names two choices. V4L2_BUF_FLAG_TSTAMP_SRC_EOF means end of frame: the stamp is taken when the last pixel of the frame has been received. Its value is 0, so it is what you get if no source flag is set. V4L2_BUF_FLAG_TSTAMP_SRC_SOE means start of exposure: the stamp is taken when exposure of the frame began.
The kernel states the rule bluntly: the driver decides at which part of the frame and with which clock the timestamp is taken. So you must read the flags. Never assume.
A clock is a counter of nanoseconds. Linux offers several. CLOCK_MONOTONIC counts up from some start point and never jumps backward. CLOCK_BOOTTIME is the same, except it also counts the time the machine spent suspended. The flag V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC (0x2000) says the stamp comes from CLOCK_MONOTONIC, and the application can read the same clock with clock_gettime().
libcamera made its own choice. Its SensorTimestamp control reports when the first row of the sensor active array was exposed, so it is start of exposure. Its value is a nanosecond counter tied to CLOCK_BOOTTIME. The control definition is a target. A pipeline may report a nearby moment, so check how your own board fills it.
That gives two conventions you will meet. A plain V4L2 capture has the source flag at 0, which means end of frame, and many drivers set the monotonic clock flag. A libcamera frame carries a start-of-exposure stamp on the boot-time clock. Both are correct. They are not the same thing.
Take a frame that starts exposing at time 0. Exposure lasts 10 ms. Readout lasts 20 ms. These are illustrative numbers. The middle of the exposure, the best single time for the picture, is at 5 ms. The end of frame is at 30 ms.
EOF stamp = 30 ms SOE stamp = 0 ms mid-exposure = 5 ms
If you treat an EOF stamp as the exposure time, you are off by 30 − 5 = 25 ms. At a turn rate of 90 degrees per second, 25 ms is 2.25 degrees of heading error. If you treat an SOE stamp as the middle, you are off by 5 ms. Better, but not zero. The sensor’s exposure time is in the frame metadata, so a careful driver can add half of it.
The clock mismatch is worse. Say the system slept for 120 seconds since boot. A boot-time clock includes that sleep. A monotonic clock does not. The same instant gets two numbers 120,000 ms apart. Fuse them naively and the filter sees a camera that is two minutes from the IMU.
Choose the source and the clock the camera stamp uses. The IMU stamps on CLOCK_MONOTONIC. The decoded flag word and the error against the true mid-exposure update below.
Illustrative frame: 10 ms exposure and 20 ms readout. The flag values (0x2000 monotonic, 0x10000 start of exposure, 0 end of frame) are from the kernel V4L2 buffer documentation. The suspend slider only matters with a boot-time clock.
On real hardware. On a Raspberry Pi 5 with a CSI camera, print b.timestamp beside clock_gettime on both CLOCK_MONOTONIC and CLOCK_BOOTTIME, and print b.flags. The one that matches tells you the clock.
Choose end of frame and monotonic. The stamp sits 25 ms after the true middle of the exposure. Switch to start of exposure. The gap shrinks to 5 ms. Now switch to boot time and drag the suspend slider. The error jumps from milliseconds to minutes.
The symptom is an estimator that works on the bench and drifts in the field, or one that fails after the robot wakes from sleep. The camera and IMU look fine alone.
The measurement takes two lines. Print the camera stamp and clock_gettime(CLOCK_MONOTONIC) and clock_gettime(CLOCK_BOOTTIME) at the same moment. The camera stamp will be close to one of them. If it is close to neither, the driver uses another clock, or an older unknown type.
cunsigned clk = b.flags & V4L2_BUF_FLAG_TIMESTAMP_MASK; /* which clock */ unsigned src = b.flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK; /* which moment */ if (clk != V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) log_warn("camera clock is not MONOTONIC"); double t_s = b.timestamp.tv_sec + b.timestamp.tv_usec * 1e-6; if (src == V4L2_BUF_FLAG_TSTAMP_SRC_EOF) t_s -= readout_s + exposure_s / 2; /* to mid-exposure */
The fix has three parts. Read the flags on every stream. Put every sensor on one clock, or convert with a measured offset. And move the stamp to the same point in each frame, ideally mid-exposure. Time synchronization across sensors is a larger topic that a later lesson in this series will cover.
Chapter 4
Read a camera as a graph of chips, and fix the one link whose format does not match
You wire a camera to a board and run the capture program from Chapter 1. It opens /dev/video0, sets a format, asks for buffers, and then VIDIOC_STREAMON fails with the error EPIPE. Every call before it worked. Nothing says what is wrong.
The cause is that the path from the sensor to memory is not one device. On a modern board it is a chain: a sensor, a CSI-2 receiver, often an ISP, and then the video node. Someone has to configure each stage. That someone is you.
A simple USB webcam hides everything behind one node. A board camera does not. The sensor chip sits on an I2C bus and a CSI-2 link. The receiver is a block inside the system chip. The ISP (image signal processor) turns raw sensor values into a usable picture. Each is its own piece of hardware, with its own driver.
The kernel documentation says it directly: device topologies are getting increasingly complex and cannot always be represented by a tree. The media controller API exists to describe and set up such devices.
The media controller shows the hardware as a graph with three kinds of piece.
/dev/v4l-subdev0, where you can set its controls and the format on each of its pads.On a typical board the graph reads: sensor, then receiver, then ISP, then the video node you opened in Chapter 1. The program media-ctl prints and edits this graph. It is the first tool to run when a camera does not start.
The command media-ctl -p -d /dev/media0 prints every entity with its pads, its formats and its links. Learn to read it. Each pad shows a format such as SRGGB10_1X10/1920x1080. Each link shows whether it is enabled.
Here is the key fact. Formats are not passed along a link for you. The documentation says that you must make sure connected pads have compatible formats, and that identical formats on the two ends of a link are guaranteed compatible. If the configuration is invalid, you get EPIPE when you start the stream. The VIDIOC_STREAMON page gives the same reason: the driver uses pad-level format configuration and the pipeline setup is invalid.
So there are two checks. Is every link on the path enabled? Do the pad formats at both ends of every link match? If either check fails, STREAMON returns -EPIPE.
The graph starts broken. Press Run STREAMON, read the error, then change a pad format or a link until it runs. Each button cycles one setting.
An example graph, not your board: entity and format names differ per board. The model checks the two rules from the kernel documentation: every link on the path must be enabled, and the two pad formats at a link must be identical. The last link ends at a fixed NV12 node.
On real hardware. On a Raspberry Pi 5 with a Camera Module, run media-ctl -p -d /dev/media0, then repeat on each other /dev/media* node, since the board has several. Follow the sensor to the video node and compare pad formats.
This is the real workflow. Read the graph, find the first link whose two ends differ, and set a pad to match. In a shell it looks like this.
shmedia-ctl -p -d /dev/media0 # print the graph media-ctl -d /dev/media0 -V '"imx219":0 [fmt:SRGGB10_1X10/1920x1080]' # set a pad format media-ctl -d /dev/media0 -V '"csi2":0 [fmt:SRGGB10_1X10/1920x1080]' media-ctl -d /dev/media0 -l '"imx219":0 -> "csi2":0 [1]' # enable a link
Under the tool, each call is an ioctl on a sub-device node. Setting a pad format is VIDIOC_SUBDEV_S_FMT with a struct that names the pad and carries width, height and a media bus code. The media bus code says how the bits travel on the wire between chips, such as 10-bit Bayer raw. It is a different list from the pixel formats of Chapter 6.
The symptom is VIDIOC_STREAMON returning -1 with errno set to EPIPE (“Broken pipe”). The error text looks odd for a camera. It simply means the pipeline is invalid.
The measurement is media-ctl -p. Walk from the sensor to the video node. Check that each link is marked enabled. Compare the format on the two pads of each link by eye. The first difference is the culprit. The kernel log often names the failing link as well.
The fix is to set the pads in order, from the sensor outward, and then set the video node’s format with VIDIOC_S_FMT. A common cause is a sensor mode change. Switching the sensor to a smaller crop changes its output size, and the receiver is still set to the old one.
One more point on drivers. A sensor driver exposes its controls (exposure, gain) on its sub-device node. In a camera stack built on the media controller, you tune the sensor there, not on the video node. libcamera, in the next chapter, does all of this for you.
VIDIOC_STREAMON returns EPIPE. What do you check first?Chapter 5
Let one library run the media graph and the auto-exposure loop, and learn why you read metadata, not your own request
Chapter 4 ended with a shell full of media-ctl commands. Every board needs a different set. Then comes exposure: a raw sensor gives dark or washed-out pictures until someone adjusts its exposure time and gain, frame after frame. A webcam does this inside the camera. A raw CSI-2 sensor does not. Something on the board must.
libcamera is the user-space library that does this work on Linux. It sits above V4L2 and the media controller, and gives your program a small API: open a camera, queue requests, receive frames.
The libcamera architecture document describes three parts that matter to you.
The pipeline handler knows one family of hardware. The documentation says it manages the complex pipelines exposed by the kernel drivers through the Media Controller and V4L2 APIs. It sets the links and pad formats from Chapter 4 for you, and it creates the camera objects for the devices it finds on the system. One handler exists per kind of board.
The IPA module (image processing algorithms) runs the 3A: auto-exposure, auto-white balance and auto-focus. The documentation says IPA modules run on the CPU and control the hardware image processing from parameters supplied by the layers above. It also says they are needed only where the host CPU controls the ISP. A sensor with its own built-in ISP does not use one. Modules built into libcamera run in its process. External ones run in a sandbox and talk only through the pipeline handler.
The application is yours. It sees a camera, a configuration and requests. Raspberry Pi’s Pi 5 is a concrete case: its image processor, the PiSP, got an upstream pipeline handler and IPA through a libcamera patch series.
With libcamera you do not dequeue raw buffers. You queue requests. A request is a package: the buffer to fill, plus a list of controls (settings, such as the exposure time you want). When the frame is done, the request comes back with the same buffer, now full, plus metadata: what the camera actually did for that frame.
c++camera->requestCompleted.connect(this, &App::onDone); auto req = camera->createRequest(); req->addBuffer(stream, buffer); req->controls().set(controls::ExposureTime, 20000); /* microseconds: what I ask for */ camera->queueRequest(req.get()); void App::onDone(Request *r) { auto exp = r->metadata().get(controls::ExposureTime); /* what the frame really used */ auto ts = r->metadata().get(controls::SensorTimestamp); /* Chapter 3 */ use(r->buffers()); r->reuse(Request::ReuseBuffers); camera->queueRequest(r); /* the buffer goes back, like QBUF */ }
This is Chapter 1 again with a richer envelope. queueRequest plays the part of QBUF. The completion signal plays the part of DQBUF. The new thing is the pairing: the controls you set and the metadata you get are tied to one frame, not to a moment in time.
The signal is delivered in the camera manager’s thread. Keep the handler short. Hand the frame to your own thread, as you would after a DQBUF. Every long task there delays the next frame, which is the queue problem of Chapters 0 and 2 again.
A sensor does not change the instant you write a register. A new exposure time usually takes effect a few frames later, because the sensor is already exposing the frame in progress. The delay depends on the sensor. The model below uses two frames as a plain example.
Now picture an auto-exposure loop. It looks at the brightness of frame n and decides the next exposure. To do that it needs to know what exposure frame n had. It has two sources. It can remember the value it last requested. Or it can read the frame’s metadata.
The worked example: the scene gives brightness 6.4 per millisecond of exposure. The target is 128, so the right exposure is 20 ms. The loop starts at 10 ms, with brightness 64. The correction rule is: new exposure = assumed exposure × 128 / brightness.
metadata: 10 ms × 128 / 64 = 20 ms then 20 ms × 128 / 128 = 20 ms, and it stays
With the metadata, the loop knows frame 2 still had 10 ms, so it asks for 20 ms and waits. Without it, the loop believes its last request was applied at once. It doubles again, then again, and the brightness swings far past the target.
The chart shows image brightness for 16 frames. The target is 128. Choose what the loop believes the exposure was, and set how many frames the sensor takes to obey.
A toy loop: brightness is 6.4 per ms of exposure, the target is 128, exposure is limited to 1 to 40 ms, and the delay is a made-up number of frames. Real sensors have their own delays, and libcamera’s IPA modules account for them.
On real hardware. On a Raspberry Pi 5 with a Camera Module, write the handler from this chapter to log the requested ExposureTime and the metadata ExposureTime for 30 frames after a change of light. Find the delay in frames.
Set the delay to 2 and choose Trust my request. The brightness swings between 32 and 256 and never settles. Switch to Read the metadata. It climbs once to 128 and stays. Set the delay to 0. Both choices work, which is why this bug hides on a fast bench sensor.
The symptom is exposure that hunts: pictures that pulse bright and dark in a slow rhythm after a lighting change. The code looks fine, since each step is a sensible correction.
The measurement is a log of three numbers per frame: the exposure you requested for it, the exposure in its metadata, and its measured brightness. If the metadata trails the request by a constant number of frames, you have found the delay. Any correction that ignores it will oscillate.
The fix is to read the metadata of the frame you are correcting from, and to let libcamera’s IPA do the auto-exposure unless you have a reason to take it over. If you do take over, keep the control and its metadata in one structure, keyed by the frame.
Chapter 6
Find any pixel in a buffer with one multiplication, and see what happens when you use the width instead of the stride
Your code reads a frame from a new camera and shows it. The picture is there, but each row is shifted a little further right than the one above, so straight edges lean like a sloping roof. On another resolution the picture is fine. On a third it is green.
The driver did nothing wrong. Your code made a guess about how the picture sits in memory, and the guess was wrong for this camera. This chapter gives you the rule so you never guess.
Memory is one long line of bytes. A picture is a grid. To store a grid in a line, you write the first row, then the second, and so on. That is row-major order. The pixel in column x of row y sits at offset y × (row length) + x.
The question is the row length. The obvious answer is the width. The real answer is the stride, also called bytesperline: the distance in bytes between the start of one row and the start of the next. The kernel documentation defines it as the distance between the leftmost pixels in two adjacent lines.
Stride can be larger than the width. The documentation says drivers may ignore the value you ask for and return the width times the bytes per pixel, or a larger value required by the hardware. The extra bytes at the end of each row are padding. The video hardware may even access them, so they must be real, readable memory.
A DMA engine and an ISP read memory in bursts, in chunks of 32, 64 or 128 bytes. A row that starts on a chunk boundary is fast. So the hardware rounds each row up. The alignment number depends on the chip; 64 bytes is a common choice, but read your driver’s answer, do not assume.
stride = ceil(width / A) × A e.g. width 1366, A = 64: ceil(21.34) × 64 = 22 × 64 = 1408 bytes
For 1366 pixels of 8-bit luma, each row has 1366 bytes of picture and 42 bytes of padding. A width of 1920 is 30 × 64, so it needs no padding. That is why the lean showed up on one resolution and not another.
Most cameras and encoders use a format that stores brightness and color apart. The reason: eyes are far more sensitive to brightness than to color, so color can be stored at lower resolution. NV12 is the common case.
The kernel documentation describes NV12 as two planes. The first plane holds the luma (brightness, called Y), one 8-bit value per pixel. The second plane holds the chroma (color, called Cb and Cr), subsampled by 2 in each direction and interleaved in pairs. The two planes are contiguous in memory. The chroma line stride equals the luma line stride.
Count the bytes. The Y plane has width × height bytes. The chroma plane has half as many rows, and each row is as long as a luma row. So it adds half again. That is 1.5 bytes per pixel.
Y at row r: base + r × stride chroma starts at base + stride × height total = stride × height × 1.5
Pick a resolution and an alignment. The left grid is the buffer, with striped padding at the end of each row. The right grid is the picture your code builds. Switch on the wrong assumption.
The byte counts are exact for 8-bit NV12 (1.5 bytes per pixel) and for 24-bit RGB (3 bytes per pixel), with each row rounded up to the alignment you pick. The grids are drawn at a small schematic scale (48 columns by 24 rows), so the lean is the right shape but not the right size. Real alignment values come from your driver.
On real hardware. On a Raspberry Pi 5 with a USB UVC webcam, run v4l2-ctl -d /dev/video0 --set-fmt-video=width=1366,height=768,pixelformat=NV12 --get-fmt-video and read bytesperline and sizeimage. If the camera lacks NV12, list its formats with --list-formats-ext and use one it offers.
Choose 1366 × 768 at 64 bytes and press the toggle. The picture leans right. The padding bytes, 42 per row, are read as pixels and push every later row. Choose 1920 × 1080: nothing leans, because the stride equals the width. The bug stays hidden until the resolution changes.
Format choice also sets how many bytes cross every bus and memory. At 1920 × 1080 and 30 frames per second, 24-bit RGB is 6,220,800 bytes per frame, which is 186.6 million bytes per second. NV12 is 3,110,400 bytes per frame, which is 93.3 million per second. Half. Chapter 7 shows why that matters when a copy sits in the path.
cstruct v4l2_pix_format *p = &fmt.fmt.pix; /* read back after S_FMT */ size_t stride = p->bytesperline; /* NOT width */ uint8_t *y = base; /* luma plane */ uint8_t *uv = base + stride * p->height; /* interleaved Cb Cr */ uint8_t px = y[row * stride + col]; /* luma at (col,row) */ uint8_t cb = uv[(row / 2) * stride + (col & ~1)]; /* chroma for that pixel */ /* p->sizeimage is the whole buffer, set by the driver */
The symptom is one of two. A sloping picture means you used the width as the row length. A green picture means the chroma plane was not where you looked, or held zeros. A buffer of all zeros, read as brightness and color, is green. Both come from the same mistake.
The measurement is a print of four numbers after VIDIOC_S_FMT: width, height, bytesperline and sizeimage. If bytesperline is larger than the width times the bytes per pixel, you have padding. If sizeimage is larger than bytesperline times height times 1.5 for NV12, there is padding between or after planes as well.
The fix is to use the returned numbers everywhere and never compute them from the width. Pass the stride to every library that takes pixels: OpenCV, a GPU upload, an encoder. They all accept one. And a note on the multi-planar variant: NV12M puts luma and chroma in separate memory regions, so each plane gets its own pointer and its own stride.
Chapter 7
Pass a file descriptor to the GPU instead of the pixels, and count the bytes you stop moving
Eight cameras feed a robot’s perception stack. The GPU is idle half the time, yet the CPU is pinned at 100 percent. A profile shows where the time goes: not in your code, not in the network, but in memcpy. The CPU is busy moving pictures from one place in memory to another.
Every frame is already in memory. The camera wrote it there by DMA. The GPU needs to read it. The question is whether the GPU can read it where it is.
The simple way to get a frame to the GPU has two copies. First, your code copies the frame out of the V4L2 buffer into memory your CUDA code owns. Second, cudaMemcpy copies it to GPU memory. Each copy reads every byte and writes every byte. A frame of 3.1 MB costs 3.1 MB read and 3.1 MB written, twice.
bytes copied per second = width × height × bytes per pixel × 30 × cameras × copies
For 4K NV12, one frame is 3840 × 2160 × 1.5 = 12,441,600 bytes. At 30 frames per second that is 373.2 MB/s per camera for each copy. With 8 cameras and 2 copies, the CPU path moves 373.2 × 8 × 2 = 5,972 MB/s. Assume one core can copy 2 GB/s (an illustrative number). Then the copies alone keep three cores busy.
Linux has a mechanism for sharing a buffer between devices without copying it: dma-buf. The kernel documentation says the dma-buf subsystem is the framework for sharing buffers for hardware (DMA) access across multiple device drivers and subsystems. The buffer is exposed to user space as a file descriptor, a small integer, so it can be passed around. The driver that made it is the exporter. A driver that uses it is an importer.
V4L2 supports both roles. For a buffer allocated with V4L2_MEMORY_MMAP, VIDIOC_EXPBUF turns it into a dma-buf file descriptor. The documentation says the application may pass it to other DMABUF-aware devices. In the other direction, with V4L2_MEMORY_DMABUF the application passes a file descriptor on each VIDIOC_QBUF. The page says this I/O method is dedicated to sharing DMA buffers between devices, and that only the file descriptors are exchanged.
That last point is the whole idea. The pixels stay where the camera wrote them. What moves is a four-byte integer.
The GPU needs a way to adopt the memory. On NVIDIA Jetson, the Multimedia API works with NvBufSurface, a handle to a buffer the hardware can use. The documented sample pattern: NvBufSurfaceFromFd() gets the surface from the dma-buf file descriptor, and NvBufSurfaceMapEglImage() creates an EGLImage. An EGLImage is a graphics-API object that wraps existing memory so that graphics and compute code can use it. CUDA then registers that image and reads it as a frame.
cstruct v4l2_exportbuffer eb = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .index = i, .flags = O_CLOEXEC | O_RDWR }; ioctl(cam_fd, VIDIOC_EXPBUF, &eb); /* eb.fd is a dma-buf: a small integer */ NvBufSurface *surf = NULL; NvBufSurfaceFromFd(eb.fd, (void **)&surf); /* adopt the same memory */ NvBufSurfaceMapEglImage(surf, 0); /* wrap it as an EGLImage */ CUgraphicsResource res; CUeglFrame frame; cuGraphicsEGLRegisterImage(&res, surf->surfaceList[0].mappedAddr.eglImage, CU_GRAPHICS_REGISTER_FLAGS_NONE); cuGraphicsResourceGetMappedEglFrame(&frame, res, 0, 0); /* frame.frame.pPitch[0] is a GPU-visible pointer */ /* run the kernel on frame; then QBUF the buffer back as in Chapter 1 */
Do this setup once per buffer, not once per frame. After setup, each new frame is just a buffer index you already know. The queue from Chapter 1 still rules: you DQBUF, hand the index to the GPU, and QBUF when the GPU finishes. Hold a buffer longer and the queue shrinks, which Chapter 2 already priced.
Choose a resolution, a format and a number of cameras. Flip between the copy path and the import path and watch the bytes the CPU moves each second.
The bytes are exact: width × height × bytes per pixel × 30 Hz × cameras × copies. The 2 GB/s a core can copy, and two copies on the copy path, are illustrative assumptions. A real system differs with its memory bandwidth and whether the GPU shares memory with the CPU.
On real hardware. On a Jetson Orin Nano developer kit with a CSI camera, run the copy path and then the import path while tegrastats reports CPU load. Run perf top on the copy path and look for memcpy.
Leave 4K NV12 at 8 cameras and switch from copy to import. About 6 GB/s of CPU copying goes to zero, and the bar falls from three cores to none. Now drop to 1 camera at 720p. The copy path costs only about 83 MB/s, a fraction of one core. Copies are cheap when the load is small. They end a design when the load grows.
The symptom is a pipeline that cannot reach its frame rate, with a GPU that is not busy. Adding cameras makes it worse in proportion. The CPU, not the GPU, is the limit.
The measurement is a profiler. Run perf top or perf record on the process. If memcpy or a copy routine leads the list, you are copy-bound. Also check top: one thread at 100 percent in the capture path points to the same cause.
The fix is to import the dma-buf. Reports on NVIDIA’s developer forums show two cautions. Zero-copy through an EGLImage has been reported to work inside one process, and sharing the file descriptor with a second process has failed on some releases. And creating the EGLImage has failed on a machine with no display attached. Test your own platform and release, and keep a copy fallback.
One more rule. If the CPU also touches the buffer, the CPU and the device must agree on who last wrote it. The dma-buf interface has a sync call for that. Without it you can read stale bytes from a CPU cache.
VIDIOC_EXPBUF and its descriptor goes to the GPU. What crosses from the camera path to the GPU path for each frame?Chapter 8
Keep the numbers, the checklist and the core code, and match a symptom to its cause in one step
A camera on Linux is a queue of buffers. Each buffer you leave waiting is a frame of age. Drain the queue and your control loop sees a frame at most one period old. Read the flags to learn what the stamp means. Walk the media graph when streaming fails. Use the stride, never the width. And pass a file descriptor, not pixels, when the GPU is the next stop.
Pick what you see. The panel gives the likely cause, the measurement that proves it, and the fix.
Each row repeats a chapter of this lesson. The causes are the common ones, not the only ones. Your driver and board may add their own.
| Quantity | Value | Where it comes from |
|---|---|---|
| Frame period at 30 fps | 33.3 ms | 1000 / 30 |
| Age of the oldest waiting frame | about (N − 1) × controller time | This lesson’s queue model, Chapter 2. With N = 6 and 40 ms: 5.4 frames in the model |
| Frames dropped in a stall of L ms | about L / 33.3 − (N − 1) | The same model. L = 250 and N = 6 gives 3 in the model |
| Drain to newest | age at most one period | Model: 0.4 frames at N = 6 and 40 ms |
| Timestamp flags | MONOTONIC 0x2000, SOE 0x10000, EOF 0 | Linux kernel V4L2 buffer documentation |
| libcamera SensorTimestamp | start of exposure, CLOCK_BOOTTIME ns | libcamera patch that promoted the control |
| STREAMON returns EPIPE | invalid pad-level pipeline configuration | Linux kernel VIDIOC_STREAMON page |
| Stride, 1366 wide at 64-byte alignment | 1408 bytes | ceil(1366 / 64) × 64 |
| 1080p, 30 Hz, RGB8 | 186.6 MB/s | 1920 × 1080 × 3 × 30 |
| 1080p, 30 Hz, NV12 | 93.3 MB/s | 1920 × 1080 × 1.5 × 30 |
| 4K NV12, per camera and copy | 373.2 MB/s | 3840 × 2160 × 1.5 × 30 |
| USB webcam capture path | about 100 ms of a 110 to 170 ms glass-to-glass budget | Transitive Robotics latency analysis: camera and USB bus are the vast majority |
The last row deserves a plain reading. The Transitive Robotics analysis measured WebRTC video from robots. It found that the camera and the USB bus took about 100 ms. H.264 encoding and decoding added about 10 ms each or less, and the WebRTC jitter buffer added 7 to 10 ms. The totals ran from about 110 ms on one host to about 170 ms through a remote relay, which added about 40 ms of network delay. A USB webcam is not a real-time sensor. If your loop needs low delay, use a CSI-2 sensor, measure its glass-to-glass delay yourself, and keep the queue short.
S_FMT and REQBUFS gave you: size, bytesperline, sizeimage, count.STREAMON.media-ctl -p and compare the pad formats on every link.perf shows memcpy hot, import the dma-buf.This is the queue model behind the hero, as a short Python program. Run it, change the arguments, and compare with the devices. It is the first of three exercises worth doing: this simulator, a media-graph validator that finds the mismatched link, and a stride calculator that turns a format into plane offsets.
pythondef sim(n, p_ms, drain=False, span_ms=8000, fps=30): per = 1000 / fps q, held = [None] * n, None # q[i]: None = empty, else (seq, t_capture) seq, next_cap, busy_until = 0, per / 2, 0 drops, ages = [], [] for t in range(span_ms + 1): if t >= next_cap: # the camera delivers a frame seq += 1 free = [i for i in range(n) if q[i] is None and i != held] if free: q[free[0]] = (seq, t) else: drops.append(t) # no empty buffer: the frame is lost next_cap += per if held is not None and t >= busy_until: q[held], held = None, None # QBUF: give the buffer back if held is None: full = sorted((q[i][0], i) for i in range(n) if q[i]) if full: pick = full[-1][1] if drain else full[0][1] if drain: for _, i in full[:-1]: q[i] = None # old frames go straight back held, busy_until = pick, t + p_ms ages.append((t, (t - q[pick][1]) / per)) late = [a for t, a in ages if t >= 2000] return sum(late) / len(late), sum(1 for t in drops if t >= 2000) print(sim(6, 40), sim(6, 40, True), sim(2, 40)) # (5.40, 30) (0.40, 0) (0.60, 30): mean age in frames, drops from 2 s to 8 s
This lesson covers the Linux side of the camera. Before it comes sensor to CSI, the wires and the receiver. The kernel side of the queue is in writing the driver. After the GPU hand-off comes the whole inference delay, in the inference latency stack. For the scheduling that keeps your loop on time, see real-time Linux. For the wider picture, try embedded Linux, sensor and actuator integration, real-time performance and the Kalman filter, which is where a camera stamp meets an IMU. Two topics are named here and not written yet: how rings and queues drop data, and virtual memory and DMA.
Every claim above comes from a page we opened: the Linux kernel V4L2 userspace documentation for QBUF and DQBUF, buffers and timestamps, STREAMON, memory mapping, DMABUF import, EXPBUF, sub-devices, pixel format fields and NV12; the kernel dma-buf page; the libcamera architecture page and the SensorTimestamp patch; the Pi 5 (PiSP) support series; the Jetson Multimedia API sample; and Transitive Robotics, WebRTC latency: a breakdown.
Our queue model, the exposure loop and the copy-core counts are teaching models, labelled as such where they appear. Only the cited pages are sources for facts about Linux, libcamera and Jetson.
Now press Present or Teach and explain the queue out loud from memory: why six buffers made frames old, what drain does, and what crosses to the GPU. Then go back to the queue at the top and run it once more.