Photons to Packets

A camera frame is not one instant: its rows are read over tens of milliseconds. Stamp it at the exposure midpoint and the camera-IMU offset stays fixed when auto-exposure moves.

Learn how a sensor makes a frame, where each row gets its time, how the frame travels over MIPI CSI-2, and how to stamp it so a robot can trust it.

Move the stamp between four places, then turn on auto-exposure. Watch which stamp error moves and which one stays still. Then we build, piece by piece, the sensor, the row clock, the frame timing, the lane budget and the sync test underneath.

You need a feel for milliseconds (one thousandth of a second) and a little C or Python for the code. We build the rest from zero.

A Physical AI Systems lesson for the camera track. It follows the sensor timing chapters of the Raspberry Pi camera documentation and the Linux IMX219 driver, the V4L2 and libcamera timestamp definitions, and the MIPI D-PHY and C-PHY roadmaps. Sources are listed in the Field Guide. It follows Buses on the Wire and Time and Sync.

Stamp a rolling-shutter frame

33 ms
10 ms
5 widths/s

A model, not a camera. Rows start 1/N of the readout time apart; each row collects light for the exposure time. The true instant is the middle of the exposure of the centre row. Auto-exposure here swings the exposure between 1 and 19 ms every 5 seconds. DQBUF adds an illustrative 8 ms for the driver and scheduler. Bar speed is in image widths per second.

Chapter 0

The Offset That Changed With the Lighting

See why one camera frame carries many times, and why the place you put its timestamp decides whether a robot can trust it

A small robot rolls through a warehouse. It has a camera and a motion sensor. The team tunes its tracking on a bright afternoon, and it works. At dusk the same robot starts to drift. The map slides, and the robot thinks it moved less than it did.

Nothing broke. The code did not change. The lights changed, and the camera answered by exposing each frame for longer. That one quiet choice moved a number the tracker thought was fixed. This chapter shows which number, and why.

Two sensors, two clocks

The robot has two kinds of eyes. The camera takes a picture, called a frame, about thirty times a second. The IMU (inertial measurement unit) is a tiny chip that feels how fast the robot turns and speeds up. It reports hundreds of times a second.

The tracker joins them. This is sensor fusion: it asks, “The IMU says the robot turned 2 degrees. Did the picture move by the right amount?” To answer, it must know when each picture was taken, in the IMU’s time. The label that says when is a timestamp.

The two sensors never agree perfectly on time. So the tracker learns one fixed gap between them, the camera-IMU time offset. Tools such as Kalibr (Furgale, Rehder and Siegwart, IROS 2013) estimate this gap as one constant number from a calibration run. The word that matters is constant. The tracker adds the same number to every frame, forever.

A frame is not an instant

Here is the trap. We talk about “the time of a frame” as if a frame were a snapshot at one moment. It is not. Most cheap sensors use a rolling shutter: they expose and read the picture one row of pixels at a time, from top to bottom. The top row sees the world a little earlier than the bottom row.

Each row also collects light for a while, called the exposure time. In a dark room the sensor lengthens it so the picture is not black. This is auto-exposure (AE). In a bright room it shortens it.

So a frame has two spans of time inside it. One is the readout time, the time from the first row to the last row. The other is the exposure time of each row. Call them R and E. Play with them now in the instrument at the top of the page. Set the readout to 33 ms and the exposure to 10 ms, as in the worked example below.

Where does the frame get its time?

Software has four easy places to read a clock. Each one lands at a different moment inside the frame. In the instrument they are the four buttons.

What we want is the true instant: the middle of the exposure of the centre row. That is the moment the picture’s middle truly “happened”. It sits at

ttrue
The moment the centre row is halfway through its exposure. This is the time the middle of the picture belongs to.
t0
The moment the first row starts to collect light (start of exposure).
R
The readout time. The centre row starts R/2 after the first row.
E
The exposure time of one row. Its middle is E/2 after it starts.

A worked example

Take R = 33 ms and E = 10 ms. The last row finishes its exposure at t0 + E + R, and the frame is complete then. So the end-of-frame stamp is t0 + 43 ms. The true instant is t0 + 16.5 + 5 = t0 + 21.5 ms. The stamp is late by 21.5 ms.

In general, the end-of-frame stamp is late by (E + R)/2. A fixed lateness is fine: the calibration absorbs it. The trouble is that E is in the formula. Now the lights dim and AE sets E = 2 ms. The lateness becomes (2 + 33)/2 = 17.5 ms. The “constant” offset moved by 4 ms, which is half of the change in exposure.

E: 10 → 2 ms    end-of-frame error: 21.5 → 17.5 ms    moved by (10 − 2)/2 = 4 ms

Over a full swing from 1 ms to 19 ms of exposure, the error moves by 9 ms. Here is why that hurts. Say the robot turns at 100 degrees per second and the camera sees 60 degrees across 1,920 pixels (toy numbers). A 9 ms error is 0.9 degrees of turn, about 29 pixels. The tracker blames that gap on its own scale, so the map drifts.

Read the swing off the hero

This is the same instrument as the one at the top, held still at the worked numbers. Press a stamp, then press Swing the exposure. The needle shows the error at exposure 1 ms and at exposure 19 ms.

Derived here, not measured: with readout R = 33 ms, error = stamp minus the centre-row exposure midpoint. Start: −(R + E)/2. Midpoint: −R/2. End of frame: (R + E)/2. DQBUF: (R + E)/2 + 8 ms, where 8 ms is illustrative.

The failure, as a symptom, a measurement, a fix

Symptom: tracking is fine in bright light and drifts in dim light, or the map “swims” when someone switches a lamp. Measurement: log the exposure value of every frame next to its timestamp. Run the calibration twice, once bright and once dim. If the offset differs between the two runs, the stamp depends on exposure. Fix: stamp every frame at the exposure midpoint, then add R/2 for the centre row. Chapter 6 builds that formula in full.

Where the stamp is taken in the kernel, and how the kernel clock lines up with the IMU clock, is the job of Time and Sync. This lesson owns the other half: where inside the frame the stamp belongs.

The road

We follow the light from the sensor to your code. At each step a different number decides whether the frame time can be trusted.

  1. Photons to digital numbers: exposure, gain and noise, and how many bytes a frame holds.
  2. Rolling and global shutter: the line time that makes the readout, and the skew it draws.
  3. Frame timing: exposure, blanking, and the frame rate that silently drops.
  4. Binning, skipping, cropping and HDR: the modes that change readout and noise.
  5. MIPI CSI-2: how many lanes the frame needs, and the bandwidth cliff.
  6. The stamp: the four clocks, and the one formula that keeps the offset constant.
  7. Two cameras: hardware triggers and the strobe test.
  8. Field Guide: numbers, checklist, code, sources.
A tracker stamps frames at end of frame. Auto-exposure changes exposure from 10 ms to 2 ms. Readout stays 33 ms. By how much does the stamp error move?

Chapter 1

Photons to Digital Numbers

Follow light into one pixel, count it, and see why a dim scene gets grainy and a frame gets heavy

You take a photo of a dark room with your phone. The picture is speckled, like sand. In daylight the same phone gives a clean picture. The speckle is not a fault. It is physics, and it has a formula.

Every pixel starts as a tiny light bucket. Light arrives as photons, the smallest packets of light. A silicon photodiode turns each photon that hits it into at most one electron. The pixel collects these electrons in a small well for as long as the shutter lets it. That time is the exposure time, E.

From electrons to a number

At the end of the exposure, the sensor reads the well. The voltage goes through an amplifier, and then an ADC (analog-to-digital converter) turns it into an integer. That integer is the digital number (DN) of the pixel. A 10-bit ADC gives DN from 0 to 1,023. The raw picture is just a grid of these integers, one per pixel, with no colour yet. Each pixel sits behind a red, green or blue filter, and a later stage called the ISP turns this RAW grid into colour.

Two knobs set the DN. More exposure time collects more electrons. More gain multiplies the voltage before the ADC reads it. Both make the picture brighter. They do not make it equally clean.

Where the grain comes from

Photons arrive at random, like rain drops on a roof. In a short time you may count 90 drops, in the next 110. This random wobble is shot noise. Its size is the square root of the count. Collect S electrons and the wobble is about √S.

The electronics add a second wobble. It does not depend on the light. It is read noise, a few electrons for every read. Together:

SNR
Signal-to-noise ratio: how big the true signal is next to the random wobble. Bigger is cleaner.
S
The electrons collected in one pixel. It equals the light rate times the exposure time.
S under the root
The shot noise variance. The wobble grows with the root of S, so the signal grows faster.
σr2
Read noise variance, in electrons squared. It stays the same whatever the light.

In dim light S is small and the read noise dominates. In bright light the shot noise dominates, but the SNR is still high. Doubling S raises the SNR by about 3 dB (decibels: 20 times the base-10 logarithm of a ratio) when shot noise rules.

Exposure or gain?

Here is the choice an auto-exposure routine makes in every frame. The scene is dim. To reach a target brightness it can open the exposure, or it can raise the gain. Gain amplifies the signal and the noise already in it. It only helps against noise that comes after the amplifier, such as the ADC stage. More exposure collects more electrons, which is real signal.

A worked example, with toy numbers. A scene delivers 50 electrons per millisecond. The goal is a brightness equal to 10 ms at gain 1. Read noise is 3 electrons; the ADC stage adds 6 electrons at gain 1, which shrinks to 6/g when referred back before the amplifier.

All three paths land on the same brightness. Path A is cleaner by 2.9 dB than B and 6.0 dB than C. Try the choice yourself below.

Trade exposure against gain

The patch is a flat grey wall seen by a sensor. Move exposure down and gain up to keep the brightness. The bars compare your setting with the cleanest way to reach the same brightness.

50 e−/ms
10 ms
1×

Illustrative sensor, not a datasheet: full well 10,000 electrons mapped to 1,023 DN at gain 1, read noise 3 electrons, ADC-stage noise 6 electrons at gain 1 (6/g before the amplifier). The grain is drawn from these numbers with a fixed random seed. The longest exposure offered is 33 ms, one frame at 30 fps.

On real hardware. Point a Raspberry Pi camera at a flat grey card. Capture 20 RAW frames at gain 1, 2 and 4, scaling the exposure to hold the brightness. Compute the standard deviation of one pixel across the 20 frames and plot it against gain. The curve should match the device above.

Notice what the device does not hide. Longer exposure is cleaner, but it costs two things you know from Chapter 0: it blurs motion, and it moves the stamp. So real cameras raise exposure first, up to a motion limit, and add gain only past it.

How heavy is a frame?

Counting also decides bandwidth. A 10-bit pixel needs 10 bits. Wires carry whole bytes, so the standard RAW10 packed format puts 4 pixels into 5 bytes: four bytes carry the top 8 bits of each pixel, and a fifth byte carries the 2 leftover bits of all four (see the Linux V4L2 Y10P format page). That is exactly 10 bits per pixel, with nothing wasted.

1080p30 RAW10 packed: 1,920 × 1,080 × 10 bits × 30 = 622 Mbit/s = 77.8 MB/s   RGB8: 1,920 × 1,080 × 3 bytes × 30 = 186.6 MB/s

The RAW stream is 2.4 times lighter than full colour (186.6 / 77.8). That is why robots move RAW over the cable and let the ISP make colour near the processor. Chapter 5 turns these numbers into a lane count.

The failure, as a symptom, a measurement, a fix

Symptom: night frames are grainy and the detector misses things. Measurement: aim at a flat grey card, take 20 frames, and compute the standard deviation of one pixel across frames. Do it at several gain values. Plot noise against gain. Fix: if the plot shows the exposure was far below its motion limit while gain was high, raise the exposure first. If motion blur then hurts, add light, a wider lens aperture or a more sensitive sensor, not more gain.

For the bit-depth side of this story, the lesson on quantization noise shows why the ADC contributes its own wobble.

A dim scene needs 4 times the brightness. The exposure can be raised 4 times without blur. Which choice gives the cleaner picture?

Chapter 2

Rolling and Global Shutter: Readout Geometry

Compute the time of every row from two numbers on a datasheet, and see why fast motion makes a straight bar lean

Photograph a passing train from a platform with a phone. The carriages lean forward, as if the train were bending. Photograph a spinning fan blade and it curls like a banana. The train did not bend. The phone took the top of the picture earlier than the bottom.

A chip cannot read a few million pixels at once through a few wires. It reads them one row (also called a line) at a time. Each row is switched on, measured, and switched off, and then the next row follows. This is the rolling shutter. Its opposite is the global shutter, where every row collects light over the same window.

Two numbers give the row clock

How long does one row take? The datasheet (or the Linux driver) tells you two things. The pixel clock is how many pixel slots the sensor steps through per second. The line length is how many pixel slots one row takes, including a short pause at the end called horizontal blanking (time with no pixel output). Their ratio is the line time, the gap between the start of one row and the start of the next.

tline
The line time: the delay between two neighbouring rows starting.
LLP
Line length in pixel clocks, active pixels plus blanking.
fpix
The pixel clock, in pixel slots per second.
R
The readout time, from the first row to the last.
N
The number of rows read.

Take the Sony IMX219, the 8-megapixel sensor inside the Raspberry Pi Camera Module 2. In the Linux driver (drivers/media/i2c/imx219.c) the pixel rate is 182,400,000 per second on a 2-lane link. The minimum line length is 0x0d78, which is 3,448. The full-resolution mode has 3,280 × 2,464 pixels.

tline = 3,448 / 182.4 MHz = 18.90 µs    R = 2,464 × 18.90 µs = 46.6 ms

The driver’s own comment for that mode reads “8MPix 15fps mode”, and its default frame length is 3,526 lines: 3,526 × 18.90 µs = 66.7 ms, which is 15 frames per second. Of that 66.7 ms, 46.6 ms is the rows being read. Chapter 3 explains the rest.

Compute the readout, then break the bar

Pick a preset or move the three sliders. The picture shows what a vertical bar looks like when it moves sideways while the rows are read. Switch to global shutter and the lean goes away.

182.4 MHz
3,448 px
2,464
5 widths/s

The IMX219 numbers (182.4 MHz, 3,448, 2,464, 1,080 rows) come from the Linux driver. The fast sensor is a toy with 2 µs lines and 2,000 rows. The bar is drawn on a frame 1,920 px wide. Global shutter sensors still blur motion by speed times exposure, but they do not lean.

On real hardware. On a Raspberry Pi with a Camera Module 2, read imx219.c and compute the line time and readout. Film a phone screen showing a moving bar, grab a frame, and compare the lean in pixels with speed times readout.

The lean, as a number

A bar crosses the picture at speed v, measured in picture widths per second. During the readout R, it moves v × R widths. The top row sees the bar at one place, and the bottom row sees it that far along. With v = 5 widths per second and R = 46.6 ms, the lean is 5 × 0.0466 = 0.233 widths. On a 1,920 px frame that is 447 pixels. That is not a rounding error. That is a wrecked picture.

Real sensors span a wide range. Reviewers who time readouts report about 3.7 ms for the stills mode of a fast stacked full-frame camera, 8.7 ms for a mid-range video mode, and 24 to 36 ms for non-stacked designs (numbers from public readout databases such as the horshack project; the methods differ between testers, so treat them as rough). Slow video modes reach about 33 ms. The range runs from about 4 ms to 33 ms.

What the lean costs a robot

A robot geometry model assumes the camera is a pinhole that took the whole picture at one instant (see camera geometry and camera models and calibration). During fast motion a rolling shutter breaks that rule. Straight lines bend. Feature positions are off by tens of pixels. A pose solver then blames its own pose.

There are three honest fixes, in order of effort:

  1. Use a global shutter sensor. Every pixel stores its charge in a small memory next to it, and all rows share one exposure window. The cost is a bigger, more complex pixel. Such sensors are often lower in resolution or sensitivity for the price. The Raspberry Pi Global Shutter Camera uses the Sony IMX296.
  2. Use a fast sensor. A shorter readout shrinks the lean in proportion, so a fast mode needs less correction.
  3. Model it. Give each feature its own row time, t0 + i × tline, and let the solver move the camera during the readout. Oth, Furgale, Kneip and Siegwart treat this in “Rolling Shutter Camera Calibration” (CVPR 2013). Chapter 6 gives the timing formula you would plug in.

The failure, as a symptom, a measurement, a fix

Symptom: vertical edges lean when the robot turns fast, and the pose estimate jumps in sharp turns. Measurement: point the camera at a vertical door frame, pan it by hand, grab a frame, and measure the angle between the top and the bottom of the edge. Divide the pixel shift by the pan speed to get R. Fix: a global-shutter sensor, a faster mode, or a rolling-shutter-aware model.

A sensor has a pixel clock of 100 MHz, a line length of 2,000 pixels and 1,000 rows. What is its readout time?

Chapter 3

Frame Timing: Exposure, Blanking and Frame Rate

Find out which of three limits sets the real frame rate, and why asking for 30 fps can quietly give you 20

You tell the camera, “30 frames per second.” Then you set a long exposure to see in the dark. The video keeps playing, with no error. But it now runs at 20 frames per second, and the timestamps are further apart than your code assumed. Nobody told you.

A camera does not keep a frame rate. It keeps a frame duration, the time from one frame start to the next, and the rate is only 1 divided by that. Three limits decide the duration. The slowest one wins.

The first limit: what you asked for

A request of 30, 60 or 120 fps sets a target duration of 1/fps. The periods are worth knowing by heart:

30 fps: 33.3 ms    60 fps: 16.7 ms    120 fps: 8.33 ms

The second limit: the rows must be read

A frame cannot be shorter than its readout. The sensor also needs a few spare lines after the last active row, called vertical blanking (lines with no picture, used for housekeeping and for setting the frame length). The Linux IMX219 driver sets a minimum of 32 blanking lines. So the minimum duration is

FDmin
The shortest frame duration the sensor mode allows.
N
The number of active rows in the mode.
32
IMX219_VBLANK_MIN in the Linux driver: the fewest blanking lines.
tline
The line time from Chapter 2, 18.90 µs for the IMX219.

For the full 3,280 × 2,464 mode: (2,464 + 32) × 18.90 µs = 47.2 ms. The fastest this mode can run is 21.2 fps, so a request for 30 fps is impossible. The driver’s default is a frame length of 3,526 lines (66.7 ms, 15 fps). For the 1,920 × 1,080 crop: (1,080 + 32) × 18.90 µs = 21.0 ms, so up to 47.6 fps. Its default is 1,763 lines, which is 33.3 ms, exactly the “1080P 30fps cropped” of the driver comment.

The third limit: the exposure must fit

Exposure is set in whole lines. The sensor cannot expose longer than the frame it is in, minus a small margin. In the IMX219 driver the largest exposure is the frame length minus 4 lines (IMX219_EXPOSURE_OFFSET). So a frame with a 50 ms exposure needs a frame at least 50 ms + 4 lines long. The frame stretches to fit.

FD
The real frame duration. The largest of the three limits.
E
The exposure time you set. If it is longer than the frame, the frame grows.

Walk through one sweep on the 1,080-row mode with 30 fps asked. At E = 10 ms the three limits are 33.3, 21.0 and 10.08 ms, so the rate stays at 30 fps. At E = 33 ms the exposure limit is 33.08 ms, still just below 33.3 ms. At E = 40 ms it is 40.08 ms and the frame lasts 40.08 ms, which is about 25 fps. At E = 100 ms the frame lasts 100.08 ms and the rate is 10.0 fps. The rate does not fall off slowly. It holds flat, then follows the exposure the moment the exposure passes the frame period.

Two things follow for a robot. First, the knee sits at the frame period you asked for, so you can set the exposure cap yourself. Second, below the knee the exposure has no effect on timing, which is why frame-rate bugs only show up in the dark.

Now try it yourself. Ask for 30 fps in the 1,080p mode, then raise the exposure past 33 ms.

Find the limit that wins

Three frames are drawn on a time axis. Warm bars are the exposure of the first and last row. The blue slope is the readout. The gap is vertical blanking. The state chip names the limit that sets the rate.

30 fps
10 ms

Numbers from the Linux imx219 driver: 18.90 µs line time (3,448 px at 182.4 MHz), 32 minimum blanking lines, exposure at most the frame length minus 4 lines, modes of 1,080 and 2,464 active rows. The sensor mode shown does not change its line time. The binned modes are left out because their pixel-clock scaling is not settled by the driver alone.

On real hardware. On any libcamera board, fix the frame rate at 30 fps and sweep the exposure from 10 ms to 100 ms. Print FrameDuration from each frame’s metadata and find the exposure where the rate drops.

Why the timestamp cares

A tracker often assumes frames arrive every 1/30 s. If a longer exposure stretches the duration to 50 ms, any code that adds 33.3 ms per frame to build its own times will drift. Also, AE itself is bounded by the frame duration. Libcamera exposes this as a control pair: FrameDurationLimits as the range you allow, and FrameDuration as the value that actually happened for each frame, in microseconds, in the frame metadata. Use the metadata, not the request.

Ask 30 fps, exposure 50 ms on 1080p: FD = max(33.3, 21.0, 50.08) = 50.08 ms  →  20.0 fps

The failure, as a symptom, a measurement, a fix

Symptom: the video rate falls in dim rooms, and the IMU and camera streams drift apart in frame count. Measurement: read the sensor timestamp (or FrameDuration) of every frame and plot the gap to the previous frame against the exposure. A staircase that follows the exposure means the exposure limit is winning. Fix: cap the AE exposure at the frame period you need, and raise the gain or add light instead. In libcamera set FrameDurationLimits to a fixed value (for example 33,333 µs for both minimum and maximum) so that AE cannot stretch the frame.

A sensor mode needs at least 21 ms to read its rows. You ask for 60 fps (16.7 ms). What happens?

Chapter 4

Binning, Skipping, Cropping and HDR Modes

Compare the ways a sensor trades pixels for speed and cleanliness, and spot the one that adds a ghost

A robot needs 60 frames a second to follow a fast hand. The sensor has 8 million pixels, and reading all of them takes 47 ms. The robot does not need 8 million pixels. It needs speed. So it asks the sensor for a different mode: a recipe for which pixels to read and how to combine them.

Every mode changes three things at once: how long the readout takes, how noisy the pixels are, and how much of the world the frame sees. We call the last one the field of view (FOV). Here are the four common recipes.

Cropping

Cropping (also called windowing) reads only a rectangle in the middle. Fewer rows are read, so the readout shortens in proportion. Every pixel is as clean as before. The price is a narrower FOV: the picture looks zoomed in. The Linux IMX219 driver has a 1,920 × 1,080 crop: 1,080 rows take 1,080 × 18.90 µs = 20.4 ms, against 46.6 ms for all 2,464 rows.

Binning

Binning merges neighbouring pixels. In 2×2 binning, four pixels become one output pixel with four times the area. The output has a quarter of the pixels, and the whole FOV stays. With fewer pixels per row and fewer rows, the readout is shorter. The IMX219 binned mode outputs 1,640 × 1,232, from a 3,280 × 2,464 crop rectangle.

Binning also cleans the picture. If the sensor adds the four charges before reading (analog binning), the signal is 4 times larger while the read noise is paid once. If the chip adds the four numbers after the ADC (digital binning), each pixel paid its own read noise. The gains come from the SNR formula in Chapter 1:

The readout time of a binned mode depends on the sensor. A common rule is that it roughly halves, because there are half as many rows. The exact time follows the line time and line length that the mode sets. The IMX219 driver keeps a longer minimum line length for binned modes, 3,560 pixels against 3,448. Its comment calls the 1,640 × 1,232 mode a “2x2 binned 60fps mode”. When we multiply its 3,560 pixels and 1,706 lines at 182.4 MHz we get 33 ms, not 16.7 ms. We did not find a datasheet to settle this, so this lesson prints exact readout times only for the unbinned modes. Check your own sensor’s timing in the driver or the datasheet before you quote one.

Skipping

Skipping reads every second row and column and throws the rest away. It is the quick, cheap cousin of binning. Readout shortens in the same way, and the FOV stays. But it keeps no extra light, so the SNR does not improve. Thin lines can vanish or alias (turn into false patterns), because the dropped rows had information.

Staggered HDR

A bright window and a dark corner in the same picture break an ordinary sensor. A bright scene needs a short exposure, and a dark corner needs a long one. HDR (high dynamic range) takes both. In staggered HDR the sensor exposes each row twice in the same frame time, once long and once short, and merges them. The two exposures are not at the same time. Their middles are apart by about (Elong + Eshort)/2 when the short one follows right after the long one.

If something moves in that gap, the merged picture shows it twice. Take a 16 ms long exposure and a 2 ms short one. The middles are (16 + 2)/2 = 9 ms apart. A bar moving at 5 widths per second moves 5 × 0.009 = 0.045 widths between them: 86 pixels on a 1,920 pixel frame. That is the ghost.

Pick a mode, read the trade

The big rectangle is the whole sensor. The bright rectangle is what the mode sees. Bars show the readout time and the noise gain. Choose HDR and raise the bar speed to see two bars where there is one.

5 widths/s

Readout is rows times the 18.90 µs line time of the IMX219 for the full, crop and HDR modes. Binning and skipping are shown as half the rows at the same line time: a toy, because real binned modes change the line length (see the text). Noise gain is a derivation: +6 dB for shot-limited binning, up to +12 dB for read-limited charge binning. The HDR exposures (16 ms and 2 ms) are illustrative.

On real hardware. List the modes your sensor offers (on a Raspberry Pi, rpicam-hello --list-cameras). For each mode, time the readout with a moving bar or a strobe and compare with the rows times the line time.

The failure, as a symptom, a measurement, a fix

Symptom: in HDR mode, a swinging arm or a hand shows a double edge, and a tracker that locks on edges jumps between the two. Measurement: turn on HDR, shake a high-contrast object in front of the lens, and measure the double-edge gap in pixels. Divide the gap by the speed to get the time between exposures. Fix: turn HDR off when the robot moves fast, use a sensor mode that makes one exposure with extra pixel tricks (some sensors offer this), or shorten the gap. Always log which mode ran, since mode changes readout and the stamp formula.

You need more frame rate and cleaner dim-light pixels, and you can accept fewer pixels. Which mode helps both?

Chapter 5

MIPI CSI-2: Lanes and the Bandwidth Cliff

Count the bits per second a frame needs, divide by what one lane carries, and see why a mode works on four lanes and fails on two

A team swaps a 1080p camera for a 4K one on the same board. The new camera is the same make and the cable plugs in. The picture is black, or it shows torn stripes, and the kernel log fills with CSI errors. Nothing is broken. The cable is simply too small for the new pictures.

MIPI CSI-2 (Camera Serial Interface 2) is the standard link between a sensor and a processor in almost every phone, drone and robot. It has two layers. The upper layer is the protocol: it cuts the frame into packets, one packet per line. The lower layer is the PHY (physical layer): the wires and the electrical signalling that carry the bits.

What one line looks like on the wire

Each row of the picture becomes a long packet. It has a short header (a data type, the byte count of the line, and an error-check byte), then the pixel bytes, then a 16-bit CRC (cyclic redundancy check, a checksum that lets the receiver notice a flipped bit). A tiny short packet marks the start and end of each frame. For RAW10 the pixel bytes use the 4-pixels-in-5-bytes packing from Chapter 1. The header and the CRC add only a few bytes to a line of thousands, so the packet overhead is small. The big cost is time: the link idles during blanking, so it must run faster than the average.

Lanes: more wires in parallel

The PHY called D-PHY uses one clock pair and one to four data lanes. A lane is one differential pair of wires (two wires that carry opposite signals, which cancels noise). The bytes of each line are dealt out across the lanes like cards. More lanes mean more bits per second.

The other PHY, C-PHY, uses a trio of three wires per lane and puts the clock inside the signal. Each step on the wires is a symbol, and a clever mapping carries 16 bits in 7 symbols: 16/7 = 2.28 bits per symbol. So a C-PHY trio carries 2.28 times its symbol rate.

Rates per lane or trio, from the MIPI Alliance PHY roadmap (standard channel):

PHY versionSymbol rateBits per second per lane
D-PHY v1.22.5 Gsps2.5 Gbps
D-PHY v2.04.5 Gsps4.5 Gbps
D-PHY v3.09 Gsps9 Gbps
C-PHY v1.23.5 Gsps8.0 Gbps
C-PHY v2.16 Gsps13.7 Gbps

These are the top of the standard, not what your chip runs. Real sensors and receivers pick a lower rate. The IMX219 driver sets a link frequency of 456 MHz on 2 lanes. Data goes out on both edges of the clock, so that is 912 Mbit/s per lane. The two lanes carry 1.824 Gbit/s, and that equals the sensor’s 182.4 MHz pixel rate times 10 bits per pixel. The numbers close exactly.

(A note on the C-PHY rows: MIPI states 6 Gsps, equal to 13.7 Gbps, for v2.1 on a standard channel, and up to 8 Gsps on a short channel. The v1.2 row is the figure from the MIPI version table; check it against the specification before you quote it.)

The budget

The frame needs B bits per second on average. The link carries data only while rows are being sent, so it must go faster than B by the inverse of its busy fraction.

Breq
The bits per second the link must carry while it is busy.
W × H
Active pixels per frame, such as 3,840 × 2,160.
b
Bits per pixel on the wire: 8, 10 or 12 for RAW.
fps
Frames per second.
o
Protocol overhead: headers, CRC, packet gaps. A few percent.
d
The share of time the link idles in blanking.
n, r
The lane count and the rate of one lane. Round n up.

Two worked examples, with no overhead and no idle time (the best case):

Add 20% blanking and 5% overhead (toy values) and 4K30 RAW10 needs 2.49 × 1.05 / 0.8 = 3.27 Gbit/s. Two lanes at 2.5 still pass. Drive it on one lane at 2.5 and it falls off a cliff.

Fit the frame into the lanes

Pick a mode, a PHY and a lane count. The pipes fill with the bits the mode needs. When the demand is bigger than the pipes, the state turns red: that is the bandwidth cliff.

20%

Rates are the top of each standard from the MIPI PHY roadmap, not the rate any given chip runs. Protocol overhead is fixed at an illustrative 5%. Idle share is a toy knob: real blanking depends on the sensor mode. C-PHY rates are bits per trio. The 12 MP mode is 4,000 × 3,000 pixels.

On real hardware. Read your sensor’s device tree node: data-lanes is the lane count the board expects. Compute Breq for your mode, compare it with the lanes times the link rate, and check whether the receiver reports CRC errors when you ask for more.

The failure, as a symptom, a measurement, a fix

Symptom: on two lanes the stream shows CRC errors, torn stripes, or the driver refuses the mode. Measurement: compute Breq from the mode and compare it with 2 × r. Then read the receiver’s error counters, which usually separate start-of-transmission sync errors, ECC errors (the header check) and CRC errors (the payload check). Sync errors point at a lane that never locks. CRC errors point at a lane that locks but flips bits. Fix: first the arithmetic, a lower frame rate, a binned mode or a lower bit depth. Then the wiring: the lane count in the device tree, data-lanes and lane-polarities must match the board, and clock-noncontinuous must match the sensor’s clock behaviour.

The board side of this link, and how the SoC fabric moves the bytes into memory, belongs to the SoC lessons: see Jetson platform bring-up. The memory fabric inside a system on chip is a topic for a later lesson of this series, and the bytes it moves are the ones we just counted.

A mode needs 5.97 Gbit/s of payload. Your receiver has D-PHY v1.2 lanes at 2.5 Gbit/s. The smallest lane count that can carry it on paper is?

Chapter 6

The Stamp: Four Clocks and One Formula

Read the timestamp your kernel or camera library gives you, work out where in the frame it sits, and move it to the true instant

You now know the three numbers that shape a frame: the line time, the readout R and the exposure E. Chapter 0 asked where to put the stamp. This chapter answers it with code you can run on a real camera. The question is practical: given what the driver hands you, how do you get the time of any row?

What the system gives you

Three sources are common on Linux.

Chapter 0 listed four stamps. The mapping is: start of exposure is SensorTimestamp (or a V4L2 SOE stamp). End of frame is a V4L2 EOF stamp. DQBUF is your own clock read after the call. The midpoint is not given by anyone. You compute it.

The formula

Let tSOE be the start of exposure of the first row. Row i (counting from 0) starts exposing tline × i later, and its exposure is E long. So the middle of its exposure is

ti
The time to assign to a feature seen in row i. Give each feature its own.
tSOE
When the first row started to expose, on the clock you share with the IMU.
i
The row index of the feature. The centre row is N/2.
tline
The line time from Chapter 2.
E
The exposure time of this frame, from the frame metadata, not from your request.

If the driver only gives an end-of-frame stamp, rebuild the start: the last row finishes at tEOF, so tSOE = tEOF − R − E. (This ignores the short transfer delay over the link. Measure it with the strobe test in Chapter 7.) Then use the formula.

Why this fixes Chapter 0: the formula contains E/2, which moves with exposure exactly as the true instant does. Nothing in the result depends on a hidden exposure term. The calibration offset between camera and IMU is then a constant, as the fusion tool assumes.

R = 33 ms   E = 4, 10, 20 ms   EOF stamps t0 + 37, 43, 53   centre-row truth: tEOF − (E + R)/2 = t0 + 18.5, 21.5, 26.5

The raw stamps move 6 ms and 10 ms between frames, while the truth moves 3 and 5 ms. The difference is the error that drifts with exposure.

Watch each stamp over sixteen frames

Each line is the error of one stamp against the true instant, frame by frame, while the light changes. A flat line is a stamp you can calibrate. A wandering line is not. Choose a lighting story.

33 ms

Exposure per frame is a made-up lighting story between 2 and 20 ms. Stamps follow Chapter 0: start −(R + E)/2, midpoint −R/2, end of frame (R + E)/2, DQBUF (R + E)/2 + 8 ms with the jitter toggle adding a seeded ±4 ms. The corrected line is tSOE + R/2 + E/2, which is the truth by construction.

On real hardware. On a Jetson or a Raspberry Pi 5, log the V4L2 stamp flags, the libcamera SensorTimestamp and your DQBUF clock for 200 frames while you cover and uncover the lens. Plot the three differences against exposure.

The core, as real code

Here is how you read the stamp and its meaning in C against V4L2, and in C++ against libcamera. Both are the real function and flag names.

c/* V4L2: dequeue a frame, then ask what the timestamp means */
struct v4l2_buffer buf = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP };
ioctl(fd, VIDIOC_DQBUF, &buf);

unsigned src = buf.flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK;   /* EOF or SOE */
unsigned clk = buf.flags & V4L2_BUF_FLAG_TIMESTAMP_MASK;      /* which clock */
double   t   = buf.timestamp.tv_sec + buf.timestamp.tv_usec * 1e-6;

/* libcamera: metadata of a completed request */
auto ts = request->metadata().get(controls::SensorTimestamp);  /* ns, CLOCK_BOOTTIME */
auto ex = request->metadata().get(controls::ExposureTime);     /* us */
auto fd = request->metadata().get(controls::FrameDuration);     /* us */

Note the three returned values are optional: a pipeline may not fill them. Check before you use them.

The failure, as a symptom, a measurement, a fix

Symptom: visual-inertial odometry shows a scale that drifts, or an offset that changes after a lighting change. Measurement: record four numbers per frame: the DQBUF time, the V4L2 EOF stamp, the libcamera SensorTimestamp, and the computed midpoint. Plot the differences between them against the exposure. The lines that move with exposure are the ones that break your offset. Fix: stamp every frame with the midpoint formula using the metadata exposure, and recalibrate once. The kernel side, how the stamp is taken and mapped to the IMU clock, is in Time and Sync. How a robot uses the time is in Sensors and Sensor and actuator integration.

The driver gives only an end-of-frame stamp. R = 40 ms, E = 6 ms. What is the time of the centre row’s exposure midpoint?

Chapter 7

Two Cameras: Hardware Triggers and the Strobe Test

Measure how far apart two cameras really are with one flash of light, and see what a software start can never promise

A robot has two cameras side by side, a stereo pair, to measure depth. Its code starts both cameras, one line after the other. The depth looks fine when the robot stands still. When it turns, the depth wobbles and objects seem to swim in front of the wall.

Stereo depth works by matching a point in the left picture with the same point in the right one. The match only means something if both pictures saw the world at the same moment. If one camera is 8 ms late, a point that moves at 2 m/s has moved 16 mm between them. The depth solver reads that gap as distance.

Why a software start is loose

Each camera runs its own clock and its own frame cycle. A software start sends a command to camera A, then to camera B. Each camera begins its first frame when its own cycle next allows, so the gap between the two first frames is anywhere from 0 up to one frame period. At 60 fps that is a random 0 to 16.7 ms. At 30 fps it is 0 to 33.3 ms. The offset is chosen by chance at every start.

It then drifts. Two crystals never run at exactly the same speed. If they differ by 20 parts per million (a toy but typical-order value), the cameras slide apart by 20 µs every second. That is 1 ms after 50 seconds, and a whole frame period after about 14 minutes at 60 fps. A sync that was perfect at start-up is wrong an hour later.

The fix: one camera leads, the others follow

Many sensors have a pin for frame synchronisation. One camera is the master: it outputs a pulse at the start of every frame. The other cameras are slaves: they start a frame only when that pulse arrives. The pulse is a wire, so it is fast, and it re-aligns every frame, so there is no drift. Vendors name the pin differently, for example a vertical sync (Sony sensors often call it XVS) or a frame-sync input (FSIN on many modules). Look up the name and the mode in your sensor’s datasheet.

Some systems cannot run a wire. The Raspberry Pi libcamera tools offer a software scheme: one process is the --sync server and others are --sync client. The server broadcasts timing messages, and the clients nudge their frame cycle to match. The Raspberry Pi documentation says frame starts should then match within “several tens of microseconds” for the same camera model on one board. It needs all cameras to run at the same fixed frame rate.

Equal midpoints, not equal starts

One trap remains. If camera A exposes for 10 ms and camera B for 4 ms, and both frames start on the trigger, then the midpoints are 5 ms and 2 ms after it: 3 ms apart. Chapter 6 told you to use midpoints. For stereo, aim for equal midpoints: delay the trigger of the shorter exposure by half the difference, (EA − EB)/2 = 3 ms. Or use the same fixed exposure on both and keep AE off.

The strobe test

How do you check any of this? Not with software logs: they share the same doubt. Use light. Fire an LED flash that is very short, say 100 µs. Both cameras see it. A rolling-shutter camera only records the flash in the rows that were exposing at that instant. So each picture holds a bright band, and the row number of the band tells you when the flash happened inside that camera’s frame.

The band’s centre row is r = (ts − tstart − E/2) / tline. If both cameras have the same line time, the difference between their band rows times the line time is the offset between the two cameras.

camera A band at row 520, camera B band at row 130, line time 12 µs: offset = (520 − 130) × 12 µs = 4.7 ms

Run the strobe test

Press Start both to start the two cameras the software way. The strobe fires once. Read the offset from the two bright bands. Slide the time forward to watch drift. Then try the hardware trigger.

20 ppm
0 min

A toy rig: 60 fps, a sensor with 1,080 rows and a 12 µs line time (13 ms readout), 2 ms exposure on both cameras, and a strobe 6 ms after camera A starts. The software start offset is a repeatable pseudo-random number between 0 and one frame period. The hardware offset of 0.05 ms is illustrative; read your datasheet for the real figure. Drift is the clock difference times the elapsed time.

On real hardware. Drive an LED from a timer on an STM32 Nucleo with a 100 µs pulse. Aim two cameras at it, grab one frame from each, find the bands, and convert the row difference to time. Repeat after ten minutes.

Read the same test as a recipe. Aim both cameras at one LED. Pulse it for a time shorter than a few lines. Grab one frame from each. Find the bright band in each. Convert the row difference to time. Repeat after ten minutes. A flat offset means your trigger works. A rising offset means the clocks are free.

The failure, as a symptom, a measurement, a fix

Symptom: stereo depth or multi-camera tracking wobbles during motion but not at rest. Measurement: plot the difference between the two cameras’ frame timestamps over a long run. A sawtooth or a steady slope shows free clocks. Then confirm with the strobe, since timestamps may lie. Fix: wire a hardware trigger from a master, make exposures equal or align their midpoints, and re-run the strobe test after any change of mode or frame rate.

Two cameras show the strobe in bright bands at rows 700 and 300. Both have a 12 µs line time. What is the offset?

Chapter 8

Field Guide

Keep the numbers, the checklist and the code you need when a camera lies about time

The whole lesson is two lines. A frame spans R + E milliseconds, so stamp the centre row at tSOE + R/2 + E/2, and the offset stays constant when auto-exposure moves. The link needs lanes = ⌈ W × H × b × fps × (1 + o) / (1 − d) / r ⌉, and the frame duration is the largest of the rate you asked for, the readout and the exposure.

The numbers and terms

QuantityValueWhere it comes from
IMX219 pixel rate, 2 lanes182.4 MHzLinux imx219.c, IMX219_PIXEL_RATE
IMX219 line length, minimum3,448 pxLinux imx219.c, IMX219_LLP_MIN
IMX219 line time18.90 µs3,448 / 182.4 MHz
Full mode readout, 2,464 rows46.6 ms2,464 × 18.90 µs
Full mode default frame, 3,526 lines66.7 ms, 15 fpsdriver fll_def and its comment
1080p crop default frame, 1,763 lines33.3 ms, 30 fpsdriver fll_def and its comment
Minimum blanking, exposure margin32 and 4 linesIMX219_VBLANK_MIN, IMX219_EXPOSURE_OFFSET
Frame periods33.3 / 16.7 / 8.33 ms1/30, 1/60, 1/120 s
End-of-frame stamp error(R + E)/2 latederived in Chapter 0; 21.5 ms at R 33, E 10
RAW10 packing4 px in 5 bytesLinux V4L2 Y10P format page
1080p30 RAW10 against RGB877.8 against 186.6 MB/sarithmetic, Chapter 1
D-PHY per lane (v1.2, v2.0, v3.0)2.5, 4.5, 9 GbpsMIPI PHY roadmap, standard channel
C-PHY per trio (v1.2, v2.1)8.0, 13.7 GbpsMIPI C-PHY version table; 16 bits in 7 symbols
4K30 RAW10, 4K60 RAW122.49, 5.97 Gbit/s3,840 × 2,160 × bits × fps
Software-started cameras0 to 16.7 ms at 60 fpsone frame period; drifts with clock difference
Raspberry Pi software syncseveral tens of µsRaspberry Pi documentation, same camera model
Vision Pro photon-to-photon12 msApple specification

Two numbers are left out on purpose. The MIPI A-PHY (the long-reach automotive PHY) rates were not opened for this lesson, so check the MIPI A-PHY page before you quote one. And the Kalibr paper estimates a camera-IMU offset as a constant; we did not find a printed figure of 20 to 40 ms that changes with the lighting, so we do not claim one. The mechanism, though, is derived above.

The checklist

  1. Write down the sensor, the mode, the line time and the rows. Compute R.
  2. Log the exposure and the frame duration from the frame metadata of every frame, not the request.
  3. Find out which stamp your driver gives: EOF, SOE, or libcamera SensorTimestamp.
  4. Convert it to the centre-row exposure midpoint with the formula.
  5. Calibrate the camera-IMU offset twice, bright and dim. The two must agree.
  6. Compute the lane budget for every mode you plan to ship, with margin.
  7. Check device tree lanes, polarity and clock mode against the board.
  8. Cap exposure so that the frame rate cannot silently drop.
  9. For two or more cameras, wire a hardware trigger and run the strobe test.
  10. Re-run the strobe test after any change of mode, frame rate or firmware.

The model as code

pythonimport math

def line_time(llp, pixel_clock_hz):
    return llp / pixel_clock_hz                      # seconds per row

def frame_duration(fps, rows, t_line, E, vblank_min=32, exp_margin=4):
    return max(1 / fps,                              # what you asked for
               (rows + vblank_min) * t_line,         # the rows must be read
               E + exp_margin * t_line)              # the exposure must fit

def centre_row_time(t_soe, rows, t_line, E):
    return t_soe + (rows / 2) * t_line + E / 2       # the true instant

def stamp_errors(R, E, dq_latency=0.008):
    return {"start": -(R + E) / 2, "mid": -R / 2,
            "eof": (R + E) / 2, "dqbuf": (R + E) / 2 + dq_latency}

def lanes_needed(w, h, bits, fps, lane_bps, idle=0.0, overhead=0.0):
    need = w * h * bits * fps * (1 + overhead) / (1 - idle)
    return need, math.ceil(need / lane_bps)

tl = line_time(3448, 182.4e6)                          # 18.90 us
print(frame_duration(30, 1080, tl, 0.050) * 1e3)    # 50.08 ms: the rate silently drops
print(stamp_errors(0.033, 0.010))                    # eof: +21.5 ms
print(lanes_needed(3840, 2160, 12, 60, 2.5e9))        # (5.97e9, 3)

Three exercises for a real board (STM32, Raspberry Pi or Jetson): compute the line time from your driver, plot per-frame stamp error against exposure for a darkening room, and run the strobe test on two cameras. Each chapter above ends its device with an “On real hardware” note.

On real hardware

Where it sits, and where to go next

This lesson owns the inside of the frame. Time and Sync owns clocks between devices, and Sensors places the camera in a robot’s sensor set. Camera geometry and camera models and calibration explain the lens side. Quantization noise extends Chapter 1. The Kalman filter is the usual consumer of a trustworthy timestamp. For the board that hosts the receiver, see Jetson platform bring-up. The SoC interconnect that moves the bytes after the lanes is the subject of a later lesson of this series.

The takeaway. A frame is a span of time, not a moment. Know R and E for every frame, put the stamp at the exposure midpoint of the row you use, and check the link and the cameras with arithmetic first and light second.

Sources and credit

Which pair of numbers per frame lets you convert an end-of-frame stamp to the centre-row exposure midpoint?

Now press Present or Teach and explain one frame out loud, from memory: why its rows have different times, where the stamp should go, and how many lanes it needs. Then go back to the instrument and turn on auto-exposure again.

Photons to Packets: Sensor Timing, Rolling Shutter and MIPI CSI-2
Buses on the Wire · Time and Sync · Back to Gleams