Low-Latency Video

Turning off B-frames and lookahead can cut over a second from a “low-latency” stream, because the encoder was holding frames back. A faster network would have cut nothing.

Follow one camera frame from the lens to the viewer’s screen. Measure every stage on the way. Learn which stage a knob really moves.

Switch off B-frames, drag Lookahead to 0, switch off the Encoder queue, then pick CSI capture. Watch the total fall. Then we build, piece by piece, everything underneath: raw bit rate, codec blocks, key frames, rate control, hardware encoders, RTP packets, loss recovery and the jitter buffer.

You need a feel for milliseconds and frames per second. We build the rest from zero. Starting points: the V4L2 buffer queue and embedded systems.

Built from primary sources: the x264 help text, RFC 3550 and RFC 6184, RFC 9725 (WHIP), the NVIDIA Video Codec SDK documents, and Transitive Robotics’ “WebRTC Latency: A Breakdown” (read it). All sources are listed in the Field Guide.

Shrink the glass-to-glass stack

40
10 ms

A model, not a measurement. The sourced anchors: camera plus USB bus about 100 ms, H.264 encode and decode about 10 ms each, jitter buffer 7 to 10 ms, a remote network path adding about 40 ms (Transitive Robotics, measured at 30 fps and a 60 Hz screen). x264’s default lookahead is 40 frames (x264 0.165 help text), so 40 frames at 30 fps is 1,333 ms. The 20 ms CSI capture, the 2-frame hardware queue and the 30 ms network are illustrative values to be replaced by your own measurements.

Chapter 0

The Low-Latency Preset With 1.3 Seconds of Lookahead

See why a stream with a fast network can still show the world more than a second late, and which encoder setting is holding the frames

You sit at a console and steer a robot arm by watching its camera. You push the stick right. Nothing moves. A second later the arm moves, and the picture on your screen shows it a little more than a second after that. You ping the robot: 30 ms. The network is fine. Where did the second go?

The answer is almost never the network. The video encoder was holding your frames. It was waiting for future frames so it could compress better. This chapter shows how that waiting works, how to count it, and how to turn it off.

The clock that matters

A frame is one still picture from the camera. At 30 frames per second (fps) a new frame arrives every 33.3 ms. That gap is the frame period, and we call it T. It is the natural unit for latency in a video pipe: when a stage holds N frames, it adds N times T.

Glass-to-glass latency is the time from light hitting the camera lens to light leaving the viewer’s screen. It is the only latency the operator feels. Every stage in between adds to it: camera, encoder, network, buffer, decoder, display.

Why an encoder would hold a frame

An encoder turns raw pictures into a small stream of bits (Chapter 1 shows why that is needed). To make the stream small, it predicts each frame from other frames and stores only the difference. Chapter 3 covers this in full. Two ideas matter here.

A B-frame is a frame predicted from both a frame before it and a frame after it. Think of a gap in a sentence: you guess the missing word better when you can read the words on both sides. But a frame after it means the encoder must wait for the future frame to arrive from the camera. The encoder then reorders the frames: it sends the future frame first, then the B-frames that sit between.

If the encoder allows a run of b B-frames in a row, the first frame of the run waits for b more frames to arrive. The wait is b times T. With 3 B-frames at 30 fps, that is 100 ms.

Lookahead is a second reason to wait. Before the encoder spends bits on a frame, it looks at the next L frames to decide which frames should be key frames and how many bits each scene deserves. It cannot look at frames that have not arrived. So the first frame leaves only after L more frames are in. The wait is L times T.

The numbers, checked

The default lookahead of x264 (the widely used software H.264 encoder) is 40 frames. The help text of x264 version 0.165 says so: --rc-lookahead <integer> Number of frames for frametype lookahead [40]. It also lists --bframes with a default of 3 B-frames between P-frames. Here is the sum.

40 frames × 33.3 ms = 1,333 ms, then 3 × 33.3 ms = 100 ms for reorder

That is 1.4 seconds before one frame even reaches the packet stage. A network that is ten times faster cannot recover it. In the hero at the top, the default preset shows exactly this. The simple sum assumes the two waits stack. A real encoder may overlap them, so measure your own build.

Hardware encoders hold frames too, in a different way. A driver may keep 2 to 4 frames in an internal queue so the chip always has work. At 30 fps that is 67 to 133 ms. Those queue depths are illustrative: they depend on the driver and settings, and Chapter 5 shows how to read them from the NVIDIA documents and from your own timings.

Watch the encoder hold frames

Top lane: frames arrive from the camera every 33.3 ms. Bottom lane: frames leave the encoder. The gap between them is the hold. Set B-frames and lookahead, then press Play.

40

A simple model: the reorder wait and the lookahead wait add up, and every frame is held for the same time. The x264 defaults (40 frames, 3 B-frames) are from its help text. The hold is counted in frame periods at 30 fps.

Failure mode: the frames are late and the network is not

Symptom. The picture is more than a second behind, but the ping is low and the link is not full. Measurement. Look at the frame order the encoder produced. The tool ffprobe -show_frames prints two clocks for each frame. The PTS (presentation time stamp) says when to show the frame. The DTS (decode time stamp) says when to decode it. With B-frames the decoder must decode a frame before it shows it, so PTS and DTS drift apart.

We ran this on a 1-second test clip with -bf 3. The I-frame had PTS 132000 and DTS 126000 on the 90 kHz clock. That gap of 6000 ticks is 67 ms. The order of frame types in display order was I, B, B, B, P, B, B, B, P. With -tune zerolatency every frame had a PTS equal to its DTS and the types ran I, P, P, P, P. No reorder was left.

Fix. Turn off the waits. For x264 that means no B-frames and no lookahead. The preset -tune zerolatency sets exactly that. The x264 help text lists it as --bframes 0 --force-cfr --no-mbtree --sync-lookahead 0 --sliced-threads --rc-lookahead 0. In ffmpeg you write -c:v libx264 -tune zerolatency. For a hardware encoder, pick its low-latency mode (Chapter 5).

The road

The lesson follows the path of a frame, from the encoder out to the screen, and then measures the whole stack.

  1. Why compress: the raw bit rate of a camera, and why no link can carry it.
  2. Codec building blocks: blocks, prediction, quantisation, entropy coding.
  3. GOP structure: I, P and B frames, the key-frame spike, intra refresh.
  4. Rate control and the VBV buffer: how a stream stays inside a bit budget.
  5. Hardware encoders: NVENC, V4L2 and VAAPI, and their hidden queues.
  6. RTP and packetisation: sequence numbers, the 90 kHz clock, slicing.
  7. Loss recovery: NACK, FEC and PLI, chosen by round trip time.
  8. The jitter buffer: sized by a percentile, not by the round trip.
  9. Glass to glass: how to measure the stack and the ping anti-pattern.
  10. Field Guide: the numbers, a checklist, the core code, the sources.
A robot’s video shows the arm 1.3 s late. The ping to the robot is 30 ms and the link is half empty. What do you check first?

Chapter 1

Why Compress: 746 Mbps

Count the bits a plain camera makes every second and see why no robot link can carry them

You plug a 1080p camera into a laptop and open a viewer. It looks smooth and the cable is thin. It feels like video is cheap. Now ask a harder question. If you sent every pixel of every frame, untouched, over a wire, how many bits would you send each second?

The answer is large enough to settle the whole design. It is why an encoder exists, and it is why an encoder is allowed to hold frames at all: it is trading a little delay for a huge saving in bits. First we count.

What one pixel is made of

A pixel is one dot of the picture. A colour pixel needs three numbers. A common scheme is YCbCr: Y is the luma, the brightness, and Cb and Cr are the two chroma numbers, the colour. Each number is a sample. The bit depth is how many bits one sample has: 8 bits gives 256 levels, 10 bits gives 1,024.

Your eye notices a sharp edge in brightness far more than a sharp edge in colour. So cameras keep every Y sample but share the colour. Chroma subsampling stores fewer Cb and Cr samples. The notation names the sharing. In 4:4:4 every pixel has its own Y, Cb and Cr: 3 samples per pixel. In 4:2:2 each row shares colour between two neighbours: 2 samples per pixel. In 4:2:0 each 2 by 2 square of four pixels shares one Cb and one Cr: four Y samples plus two colour samples is 6 samples for 4 pixels, which is 1.5 samples per pixel.

The formula

Multiply what the picture holds by how often it arrives. Width times height gives pixels per frame. Times the samples per pixel, times the bits per sample, times the frames per second.

bits per second = W × H × fps × bits per sample × samples per pixel

Work the common case, 1080p at 30 fps, 8 bits, 4:2:0, one step at a time.

  1. Pixels per frame: 1,920 × 1,080 = 2,073,600.
  2. Samples per frame: 2,073,600 × 1.5 = 3,110,400 samples, so 3,110,400 bytes at 8 bits. One raw frame is 3.11 megabytes.
  3. Bits per frame: 3,110,400 × 8 = 24,883,200 bits.
  4. Bits per second: 24,883,200 × 30 = 746,496,000, which is 746 Mbps.

Now a premium case: 4K at 60 fps, 10 bits, 4:2:0. That is 3,840 × 2,160 × 60 × 10 × 1.5 = 7,464,960,000 bits per second, 7.46 Gbps. It is ten times the first case.

Count the raw bits

Pick a camera format. The long bar is the raw bit rate on a log scale. The vertical lines are the nominal speeds of gigabit and 10-gigabit Ethernet. Then set a target stream rate and read the squeeze.

8 Mbps

The arithmetic is exact. The 8 Mbps starting target is an illustrative choice, not a standard. Ethernet speeds are nominal line rates; real throughput is lower once packet headers are counted.

On real hardware. On an STM32H7 Nucleo with a camera on the DCMI port (see MCU camera, DCMI and JPEG), count the bytes the DMA writes for one frame with a timer. Multiply by the frame rate and compare with the formula.

What the squeeze means

A target of 8 Mbps for the 1080p30 case is a squeeze of 746 / 8, about 93 to 1. Each frame has an average budget of 8,000,000 / 30 = 266,667 bits, about 33 kilobytes, out of 3.11 megabytes raw. A codec (coder and decoder) is the tool that makes this squeeze. Chapter 2 opens it up.

Two lessons follow. First, the codec is not optional. The plain 746 Mbps case fills three quarters of a nominal gigabit Ethernet link, and the 4K case fills three quarters of a 10-gigabit link that most robots do not have. A wireless link usually delivers well below its headline rate. Second, the squeeze has a price. The 93 to 1 comes from predicting, and prediction means looking at other frames, and looking at other frames means waiting for them. The compression gain and the latency cost come from the same place.

Here is a second way to read the same numbers, in time. A frame of 266,667 bits crosses a link that runs at 8 Mbps in 266,667 / 8,000,000 = 33.3 ms. That is exactly one frame period. So a stream at the link rate sends each average frame just as the next one is ready. A frame bigger than average takes longer, and the next frame must wait behind it. This is why average rate alone never tells you the delay. Chapter 3 turns it into a queue you can watch.

Chapter 0 showed that the wait can be huge by accident. The next chapters show which parts of the squeeze need the wait and which do not.

A camera makes 1080p at 60 fps, 8 bits, 4:2:0. What is its raw bit rate?

Chapter 2

Codec Building Blocks

Follow one small block of pixels through prediction, transform and quantisation, and see where the saved bits come from

Imagine you must describe a video call to a friend by phone, one frame at a time. Reading out 2 million pixel values is hopeless. So you say: “Same as the last frame, but the person moved two steps to the right.” Then you add: “Also, the left cheek is a little darker.” That is the whole idea of a video codec. Say what changed. Do not repeat what stayed.

This chapter opens the codec into its blocks. We use H.264 as the model, because it is the codec most robot cameras and WebRTC stacks speak. Every block has one job, and a few of them decide your latency.

Cut the picture into blocks

The encoder does not treat the frame as one image. It cuts it into a grid of blocks. In H.264 the basic unit is a macroblock, 16 by 16 pixels, and the encoder may split it into smaller pieces where the picture has detail. Each block gets its own decision. A flat sky uses a big block. A face edge uses small ones.

Predict the block

A prediction is the encoder’s guess for a block, built from pixels the decoder already has. There are two kinds. Intra prediction guesses from neighbouring pixels in the same frame, for example the average of the row above and the column to the left. Inter prediction guesses from an earlier frame: it finds the best matching patch there and points to it with a motion vector, a pair of numbers that says how far to shift.

The encoder then subtracts the guess from the real block. The difference is the residual. A good guess leaves a residual near zero. Zeros are cheap to send. This is where most of the 93 to 1 squeeze of Chapter 1 comes from.

Transform and quantise

The residual still holds 64 or 256 numbers. A transform (H.264 uses a small whole-number cousin of the discrete cosine transform, the DCT) re-writes the block as a few smooth patterns and a few fine ones. Smooth patterns usually carry most of the energy. Fine patterns are often tiny.

Quantisation then rounds each transform number to a multiple of a step size. Small numbers round to zero and vanish. This is the one step that throws information away, and it is the knob that sets quality. The QP (quantisation parameter, 0 to 51 in H.264) picks the step. The step size, Qstep, is 0.625 at QP 0 and doubles every 6 QP steps, which makes it 224 at QP 51. Six more QP means half as many bits per coefficient, roughly.

One more block finishes the chain. Entropy coding writes the remaining numbers with short codes for common values and long codes for rare ones, the way Morse code gave E a single dot. H.264 offers two such coders, CAVLC and CABAC. It costs no quality at all. Last, an in-loop filter (the deblocking filter) smooths the seams between blocks in the rebuilt frame, so later frames predict from a cleaner picture.

Send one block

The block holds a moving edge. Choose how to predict it, move the motion vector, then raise QP. Watch the residual, the bits, and the rebuilt block.

0
26

A toy, not H.264. The block is 8 by 8 and the picture content moves 2 pixels right between frames, so the best motion vector is −2. The transform is a real floating-point DCT, not H.264’s integer transform. The step is Qstep = 0.625 × 2QP/6, which follows H.264’s doubling every 6 QP. The bit count is a rough rule (about 2 + 2 log2(1 + |level|) bits per nonzero level and 0.15 per zero), not the CAVLC or CABAC tables.

On real hardware. On a Jetson or a Raspberry Pi, encode the same clip at -qp 20, -qp 30 and -qp 40 and compare the file sizes. Each +6 should cut the size by a large step, not a small one.

Reference frames and the state the decoder keeps

Inter prediction has a price. The decoder must keep the frames it predicts from. These are the reference frames. The decoder builds each new frame from them, then stores the new frame as a reference for later ones. So the decoder carries state: a small set of pictures that both sides must agree on. If one side loses a frame, the two sides disagree, and every later frame is wrong until a frame that needs no reference arrives. Chapter 3 shows that frame, and Chapter 7 shows how a receiver asks for it.

Predicting from the past only is cheap in time. The encoder can send a frame as soon as it is captured. Predicting from the future is the B-frame trick of Chapter 0, and it is the one that makes the encoder wait.

Where the failures show

Symptom 1. The picture shows square blocks, with visible edges, in dark or smooth areas. Measurement. Read the QP of the frame (ffprobe shows it with -show_frames on some builds, or the encoder log). A QP near 40 or higher gives a step of 40 or more. Fix. Give the encoder more bits or a smaller QP ceiling.

Symptom 2. The picture is crisp but the stream stalls when the scene moves. Measurement. Plot bytes per frame over time; busy frames are several times larger. A low QP spends many bits on a hard frame, and the link cannot carry them in one frame period. Fix. Cap the rate (Chapter 4) so the encoder raises QP instead of overflowing the pipe.

The trade is the same one the hero shows in time: you can have quality now by spending bits now. The next two chapters decide how a stream spends those bits from one frame to the next.

Which block of the codec throws information away, and which knob controls how much?

Chapter 3

GOP Structure: I, P, B and Intra Refresh

Find out why a healthy stream can freeze once every second, and how to spread the big frame so the link never chokes

A robot streams video over a Wi-Fi link. The average rate is 4 Mbps and the link carries 5. By the numbers there is room to spare. Yet every second the picture freezes for a moment, then jumps. The freeze keeps a steady beat. What beats once a second?

The answer is the key frame. Some frames cost far more bits than others. When one huge frame meets a link that was sized for the average, the link cannot pass it in one frame period, and everything behind it waits.

Three kinds of frame

An I-frame (intra frame) is coded on its own. It refers to no other frame, like a photograph. It is big. A P-frame (predicted frame) refers to earlier frames only and stores the change. It is small. A B-frame, as Chapter 0 said, refers to a frame before and a frame after. It is the smallest, and it is the one that forces the wait.

A GOP (group of pictures) runs from one I-frame up to the next. A typical shape is I P P P P … with N frames in all. The decoder needs an I-frame to start: join a stream in the middle, or lose data, and every P-frame after the damage is a change applied to a picture the decoder does not have. Only a new I-frame repairs that. That is why encoders insert one regularly. The x264 default is a new key frame at most every 250 frames, which is 8.3 seconds at 30 fps.

Size is the cost. A common rule of thumb is that an I-frame is 5 to 10 times the size of a P-frame. We use 8 times as an illustrative figure in the device below, to make the spike visible.

The arithmetic of the spike

Let the stream average R = 4 Mbps at 30 fps, with a GOP of N = 30 frames and an I-frame 8 times a P-frame. One GOP holds one I-frame and 29 P-frames: 8 + 29 = 37 P-sized units. The average frame has R / fps = 133,333 bits. So 30 average frames equal 37 P-units, and one P-unit is:

p = 133,333 × 30 / 37 = 108,108 bits (13.5 kB), so an I-frame = 8p = 864,865 bits (108 kB)

Now the link. At 5 Mbps and 30 fps it drains 166,667 bits per frame period. A P-frame (108,108 bits) fits with room to spare: 58,559 bits of slack. The I-frame does not fit: 864,865 − 166,667 = 698,198 bits stay in the queue. At 5 Mbps that backlog is 140 ms of waiting. The next P-frames each drain only 58,559 bits of it, so the queue clears after about 12 frame periods, around 400 ms. If the viewer’s playout budget is 100 ms, every frame that waits longer than that is late: a freeze, once per GOP.

Send two GOPs through a link

Top: the size of each frame against what the link drains in one period. Bottom: how long each frame waits in the queue, against a 100 ms budget. Shrink the link, change the GOP, then switch on intra refresh.

5.0 Mbps

Illustrative stream: 4 Mbps average at 30 fps, an I-frame 8 times a P-frame (the 5 to 10 times rule of thumb), one queue in front of the link, a 100 ms budget. With intra refresh every frame has the average size. Real intra refresh costs a little extra efficiency, which is ignored here.

On real hardware. On a Jetson dev kit, stream with x264enc or the hardware encoder at a fixed GOP, log bytes per frame from the encoder output, and plot it. You should see the spike at every GOP boundary.

Intra refresh: spread the I-frame

Intra refresh removes the spike by never sending a whole I-frame. Instead each P-frame carries a thin column of blocks coded as intra. The column moves across the picture, one step per frame. After N frames the whole picture has been refreshed once. A decoder that joins late or loses data heals within N frames, and every frame has about the same size. The x264 option is --intra-refresh, described as “Use Periodic Intra Refresh instead of IDR frames”.

The trade: the repair is slower than a single I-frame (it takes up to N frames to finish) and the picture needs a little more data overall. For teleoperation, steady frame sizes usually win.

Slices and the key-frame loop

A slice is a piece of one frame that can be decoded alone. If a frame has four slices and one packet is lost, the other three still decode. Chapter 6 uses this. There is also a trap worth knowing now. When a receiver loses data it asks the sender for a new key frame (a PLI request, Chapter 7). The new key frame is a spike. The spike overflows the queue. The overflow loses more packets. The loss triggers another request. A stream can chase its own tail this way.

Failure mode

Symptom. The picture freezes at a regular beat. Measurement. Plot the size of every encoded frame against the time of each freeze. The freezes sit right after the largest frames. Fix. Use intra refresh, or cap the rate with a small VBV (Chapter 4) so the I-frame is squeezed, or pace the packets so a big frame leaves as a smooth stream and not a burst.

A stream has a 4 Mbps average on a 5 Mbps link but freezes every second. What most likely explains the beat?

Chapter 4

Rate Control and the VBV Buffer

See how one buffer-size setting trades picture quality against seconds of delay

You fill a bathtub from a tap and drain it through a pipe. The tap is the encoder: it sometimes pours a lot, when the scene is busy. The pipe is the network link: it drains at one steady speed. The tub in between is a buffer. A big tub smooths out the busy moments. But water in a big tub takes longer to leave, and a viewer feels that wait as delay.

Rate control is the part of the encoder that decides how much water to pour for each frame. This chapter shows the tub, its size, and the single trade it sets.

Who decides how many bits a frame gets

Chapter 2 gave the encoder one quality knob, the QP. Rate control adjusts that knob frame by frame to hit a goal. The common goals are:

  1. CQP (constant QP): hold the QP fixed. The quality is steady and the bit rate swings with the scene.
  2. CRF (constant rate factor, in x264): hold the perceived quality steady and let the rate swing. The x264 help text gives it a default of 23 on a scale of −12 to 51.
  3. VBR (variable bit rate): hit an average over a long time, and allow swings in between.
  4. CBR (constant bit rate): stay close to one rate all the time. This is the friend of a fixed-speed link.

CQP and CRF alone put no ceiling on a frame. Chapter 3 showed what an unbounded key frame does to a queue. To put a ceiling, the encoder needs a model of the pipe it feeds.

The VBV model

The VBV (video buffering verifier, also called the HRD, hypothetical reference decoder) is that model. It is an imaginary tub with a size B in bits that drains at the stream rate R in bits per second. After each frame the encoder adds that frame’s bits to the tub. The rule is that the tub must never overflow. Because of the rule, the encoder may not make a frame bigger than the room that is left. If the scene needs more bits than the room allows, the encoder must raise the QP and make the picture rougher for a while.

The delay is the other side of the same tub. A frame that goes in on top of a full tub waits for everything under it to drain. The most it can wait is:

worst added delay = B / R

The x264 help text shows how this looks in practice. Its example for constant bit rate is x264 --vbv-bufsize 2000 --bitrate 1000, described as “Constant bitrate at 1000kbps with a 2 second-buffer”. The buffer is 2,000 kbit and the rate is 1,000 kbit/s, so B / R is 2 seconds. A teleoperation stream that copies that example can sit two seconds behind. The x264 defaults are --vbv-maxrate 0 and --vbv-bufsize 0, which means no VBV at all.

A worked example

Take R = 4 Mbps at 30 fps, so the tub drains 133,333 bits per frame period. Say the picture is calm and each frame needs 133,333 bits at the wanted quality. Then a burst arrives: for 8 frames the scene needs 3 times as many bits, 400,000 bits per frame. Each burst frame brings 400,000 − 133,333 = 266,667 extra bits that the pipe cannot drain in one period. Over 8 frames that is 2,133,333 bits of excess.

How big must the tub be to hold the burst without cutting quality? The excess takes 2,133,333 / 4,000,000 = 0.533 seconds to drain, so B must hold at least 533 ms of bit rate, about 2.13 Mbit. Add the 33 ms that the tub already holds in calm times and you need about 570 ms. A bigger tub than that does nothing for this burst. A smaller tub forces the QP up. A tub of 100 ms (400,000 bits) fits only about one burst frame beyond the average, so the rest of the burst gets squeezed.

Size the buffer

The scene needs 3 times the bits for 8 frames, starting at frame 30. Slide the buffer size. Top: the wait the tub adds. Bottom: how many QP steps the encoder must add to fit.

2,000 ms

A model. The encoder wants a size per frame, drains the tub every period, and cuts any frame that would overflow it. Extra QP is 6 × log2(wanted bits / allowed bits), which follows Chapter 2’s rule that six QP steps roughly halve the bits. The 3 times burst and the 4 Mbps rate are illustrative.

On real hardware. On a Jetson Nano or Orin dev kit, run the same clip with and without a small VBV and read the encoder’s bytes per frame log. With the small VBV the largest frame should shrink and the QP should rise on busy scenes.

Slide the tub down and the wait shrinks with it, while the quality dip during the burst grows. Slide it up past about 570 ms and the dip disappears, but you have bought up to 533 ms of waiting for a burst that may never come. This is the trade: a small VBV gives low latency and quality that pumps up and down; a large VBV gives smooth quality and adds delay.

What teleoperation wants

A teleoperation stream cares more about delay than about a perfect picture during a burst. Start with a buffer of one to two frame periods of the stream rate. At 4 Mbps and 30 fps that is 133,333 to 266,667 bits, which is 33 to 67 ms of added wait. Raise it only if the quality dips hurt the task. In x264 terms, use a CBR-style setup with --bitrate and a small --vbv-bufsize, and turn on --nal-hrd cbr only if a downstream device needs the HRD signalled.

Failure mode

Symptom. The delay climbs by seconds when the camera sees a busy scene and falls back when it calms. Measurement. Log the bytes of each frame and add them to a running tub that drains at the stream rate. The tub level divided by the rate is the delay. Fix. Reduce the VBV buffer size until the worst level, divided by the rate, fits your latency budget.

An encoder runs at 2 Mbps with a 4 Mbit VBV buffer. What is the largest delay the buffer can add?

Chapter 5

Hardware Encoders: NVENC, V4L2 M2M, VAAPI

Learn why a chip that encodes a frame in about a millisecond can still return it two frames later, and which switches stop that

You move the encoder from the CPU to a hardware block on a Jetson board. CPU use drops from 90% to 5%. You expect the delay to drop too. It barely changes. A trace shows the chip needs about a millisecond per frame, yet each frame comes out about 100 ms after it went in. The chip is not slow. It is waiting.

A hardware encoder is a fixed-function circuit that does only one job: turn raw frames into H.264, H.265 or AV1. It is fast and uses little power. But the software around it is built to keep the circuit busy, and keeping it busy means keeping frames waiting in line.

Three families, one idea

NVENC is the encoder block on NVIDIA GPUs and Jetson modules. You reach it through the NVIDIA Video Codec SDK or through a wrapper such as GStreamer or ffmpeg. V4L2 M2M is the Linux kernel’s memory-to-memory interface for codec chips (Rockchip, Raspberry Pi, i.MX and Jetson all expose one). You queue raw frames into one queue named OUTPUT and you read the bitstream from another queue named CAPTURE. The kernel documentation says it plainly: “the order of encoded frames dequeued from the CAPTURE queue may differ from the order of queuing raw frames”, and “buffers queued to OUTPUT may not become available to dequeue instantly”. VAAPI is the video acceleration interface for Intel and AMD GPUs on Linux. All three share the same shape: frames go into a queue, a bitstream comes out of another, and a delay sits between.

If the buffer queue idea is new, the V4L2 buffer queue lesson builds it from zero. Here we only need one fact from it: a buffer you queued is not yours again until the driver gives it back.

Where the frames wait

  1. Lookahead. The NVENC programming guide says that when lookahead is on, “frames are queued up in the encoder” and the encode call “will return NV_ENC_ERR_NEED_MORE_INPUT”. The depth can be set up to 32 frames. The encoder withholds output on purpose.
  2. B-frame reorder. As in Chapter 0, each B-frame run adds its length times the frame period.
  3. The asynchronous pool. The guide says the output buffers should number “at least 4 + number of B frames” for asynchronous output. Deeper pools raise throughput. They do not lower the delay of one frame.
  4. The wrapper. Plugins and example programs often hold a few frames before they ask for output. A developer-forum report says the NVENC sample buffers three frames. Another says ffmpeg stayed two frames behind with B-frames off. These are anecdotes: measure your own build.

Throughput is not latency

The NVIDIA application note lists performance as frames per second. For 1080p H.264 on an Ada GPU with preset P1, CBR and the low-latency tuning, one NVENC engine reaches 910 fps. That is about 1.1 ms per frame, for throughput. It is how fast the circuit runs when the line is full. It says nothing about how long one frame spends in the line. If your pool keeps 3 frames in front of the chip at 30 fps, each frame waits 3 × 33.3 = 100 ms and then takes 1.1 ms to encode.

The settings that remove the wait

NVIDIA names the intent. The guide recommends low latency tuning with CBR for cloud gaming, streaming and video conferencing, and ultra-low latency tuning with CBR when the channel is strictly bandwidth-constrained. The other tuning options are high quality and lossless. Then you turn off B-frames and lookahead, keep the number of buffered frames at the minimum your code allows, and use lowDelayKeyFrameScale to limit how large an I-frame can be against a P-frame (Chapter 3). For error repair without a key-frame spike, the guide offers intra refresh through intraRefreshCnt: a smaller count refreshes faster and lowers quality.

Count the wait around a 1 ms encoder

Each row is one frame. Blue is capture. Yellow is the wait before output. The tiny green tick is the encode work. Pick a tuning style, then change the queue depth.

3

A sketch. The encode work of 1.1 ms comes from 1 / 910 fps, the application note’s throughput for 1080p H.264 on Ada with P1, CBR and low-latency tuning. The three tuning styles use illustrative settings (2 B-frames and 8 lookahead frames for the first, none for the other two), not the SDK’s internal numbers.

On real hardware. On a Jetson Orin dev kit (see Jetson bring-up), put a timestamp on each raw buffer, read the timestamp on the coded buffer, and print the difference. Most memory-to-memory drivers copy it across. Repeat with B-frames on and off.

The chip, and what the datasheets say

Capability tables answer a different question: how many streams, at what size. Two secondary spec pages for the Jetson AGX Thor list video encode as up to six 4Kp60 streams in H.265 and H.264, and decode as up to four 8Kp30 streams or ten 4Kp60 streams, including AV1 decode. AV1 appears on the decode side only in those tables, while one vendor listing groups AV1 with encode. Treat AV1 encode on Thor as unverified until you run it on the device. We did not find NVIDIA’s own datasheet page in this search, so check it before you plan around these counts.

Failure mode

Symptom. A hardware encoder gives 50 to 130 ms more delay than the chip’s speed explains. Measurement. Timestamp in, timestamp out, as above. If the difference grows by one frame period each time you raise the queue depth, the wait is in the queue. Fix. Put the encoder in its low-latency tuning, disable B-frames and lookahead, and shrink the pool to the smallest depth that does not stall capture.

A hardware encoder reaches 910 fps in the application note, yet your stream shows 100 ms between a frame going in and coming out. Which reading is right?

Chapter 6

RTP, RTCP and Packetisation

Cut one coded frame into numbered packets and see why one lost packet can ruin the whole frame

The encoder hands you a 108 kB key frame. The network will not carry 108 kB in one piece. The usual limit for one packet is about 1,500 bytes. So the frame must be cut into around a hundred packets, sent, and rebuilt in the right order at the far end. Each packet needs a label so the receiver can do that. This chapter is about the labels.

RTP (real-time transport protocol, RFC 3550) is the standard label system for live media. It rides on UDP, so a packet that is lost stays lost unless something else repairs it (Chapter 7). RTCP is its companion: a slow side channel where each end reports what it sees.

What is in an RTP header

Four fields matter for video.

  1. Sequence number. It goes up by one for every packet sent. A gap in the numbers tells the receiver a packet is missing. RFC 3550 says its first value should be random.
  2. Timestamp. It says when the media was sampled, not when the packet was sent. All packets of one frame share one timestamp. For video the clock runs at 90,000 ticks per second: RFC 6184, the H.264 payload format, says “A 90 kHz clock rate MUST be used.” At 30 fps one frame is 90,000 / 30 = 3,000 ticks. The first value should also be random.
  3. Marker bit. For H.264, RFC 6184 sets it on “the very last packet of the access unit”, so the receiver knows the frame is complete.
  4. SSRC and payload type. These name the stream and the codec.

The 3,000 tick step is not special to RTP. When we ran ffprobe on a 30 fps clip earlier, the frames in a transport stream also stepped by 3,000 on the 90 kHz clock. The same clock is used so audio and video can be lined up later.

Cutting a frame

An H.264 frame is a set of NAL units (network abstraction layer units): self-contained chunks such as a slice of picture data. RFC 6184 does not limit how large a NAL unit may be. When one is too big for a packet it is cut with a fragmentation unit, called FU-A, which is NAL type 28. Each fragment carries two extra header bytes. A packet then holds: 12 bytes of RTP header, 2 bytes of FU-A header and the data.

Take a packet size of 1,200 bytes (an illustrative choice, below the usual path limit so headers and tunnels still fit). The data per packet is 1,200 − 12 − 2 = 1,186 bytes. The key frame of Chapter 3 is 864,865 bits, which is 108,108 bytes. It needs 108,108 / 1,186 = 91.2, so 92 packets. The P-frame of Chapter 3 is 108,108 bits, which is 13,514 bytes. It needs 12 packets.

Packetise a frame and lose some

Each square is a packet with a sequence number. The last one carries the marker bit. Press Send frame to draw new random losses. Then cut the frame into 4 slices.

108 kB
1.0%

Illustrative: 1,200-byte packets, 1,186 bytes of data after the 12-byte RTP header and the 2-byte FU-A header; losses are independent random draws. The header fields and the 90 kHz clock follow RFC 3550 and RFC 6184.

On real hardware. On a Raspberry Pi or a Jetson, run gst-launch-1.0 ... rtph264pay mtu=1200 ! udpsink and capture it in Wireshark. Check that the timestamp step is 3,000, the sequence numbers are continuous and the marker bit is set on one packet per frame.

One lost packet

A frame is complete only if all its packets arrive. If each packet is lost with probability p, a frame of n packets arrives whole with probability (1 − p)n. At p = 1% the key frame of 92 packets arrives whole with 0.9992 = 39.7% probability. The P-frame of 12 packets arrives with 0.9912 = 88.6%. A single 1% loss on the link makes most key frames unusable. Because P-frames build on earlier frames, one broken key frame spoils all the frames that follow it until the next repair.

Slicing softens this. If the frame is cut into 4 slices, each in its own packets, then a loss spoils only its own slice. With 23 packets per slice, each slice arrives with 0.9923 = 79.4% probability, and on average 79.4% of the picture survives. The decoder can often conceal the missing slice from the previous frame. The all-or-nothing odds stay the same (still 39.7% that nothing is lost), but a loss no longer costs the whole frame.

The reports: RTCP

Every second or so, the sender sends a Sender Report (SR) and the receiver sends a Receiver Report (RR). The receiver’s report holds the fraction lost, the total lost, the highest sequence number received, the interarrival jitter (Chapter 8) and the time of the last SR it saw. That last field gives the sender a round trip time: “rtt = sendertime2 − sendertime1 − DLSR”, where DLSR is the delay at the receiver. The WebRTC for the Curious book works an example that comes to 265 ms. Modern senders also use header extensions (for example transport-wide congestion control) to learn about each packet’s arrival time and to steer the bit rate.

Failure modes

Symptom. Playback is jittery or loses sync with audio, but the network is quiet. Measurement. Compare RTP timestamps with arrival times. If the timestamps were taken from the wall clock at send time, a clock step (NTP correcting the time) makes a jump that looks like jitter. Fix. Stamp each frame with the capture time, from a steady clock, converted to 90 kHz ticks.

Symptom. Large frames fail much more often than small ones. Measurement. Count packets per frame against frames lost. Fix. Slice the frame, cap the key-frame size (Chapter 3), and repair losses (Chapter 7).

A 92-packet key frame crosses a link that loses each packet 1% of the time. About how often does it arrive complete?

Chapter 7

Loss Recovery: NACK vs FEC vs PLI

Choose how to repair a lost packet by comparing the round trip with the time the viewer is willing to wait

A robot works in a mine and its video crosses a cellular link with a 300 ms round trip. Packets get lost now and then. The receiver does the textbook thing: it asks for each lost packet again. Every request is answered. The bandwidth bill goes up. The picture still freezes. Why?

Because the answer arrives after the viewer needed it. A repair that comes too late is worth nothing, yet it still costs bandwidth. The right repair depends on how the round trip compares with the time the receiver can afford to wait.

Three tools

A NACK (negative acknowledgement) is a small message from the receiver: “I am missing packet 4017, please send it again.” WebRTC for the Curious defines it as a request that “re-transmits a single RTP packet”. It costs almost no bandwidth when losses are rare. But it costs one round trip, plus the time to notice the gap.

FEC (forward error correction) means the sender adds repair data before any loss happens. The simplest kind is an XOR parity packet. Take k data packets and XOR them into one extra packet. If any one of the k + 1 packets goes missing, the receiver XORs the others and gets it back. It costs bandwidth all the time, 1 / k extra, and it makes the receiver wait to collect the block. It costs no round trip. The same book notes FEC can have lower latency than NACK when loss is steady, because NACK adds a round trip.

A PLI (picture loss indication) is the last resort. The receiver says: “I cannot decode, send me a fresh key frame.” The book describes it as used when partial frames reached the decoder but could not be decoded. It always works, but Chapter 3 showed what it costs: a key frame is a spike, and the frame freezes until the spike arrives.

The deadline

Call the playout slack the time between a packet’s arrival on a good path and the moment its frame must be shown. It is roughly the jitter buffer target (Chapter 8) plus what is left of one frame period. Say the slack is 100 ms. Now compare each tool with it.

  1. NACK repairs at about RTT + 5 ms after the packet should have arrived (a few ms to notice the gap). It works only if RTT + 5 ms ≤ slack.
  2. FEC repairs after the block is complete. With 12 packets per frame spread over a 33.3 ms period, packets come about every 2.8 ms, so a block of k = 5 completes after about 14 ms. It works if that time ≤ slack, and it does not depend on the RTT at all.
  3. PLI repairs after RTT plus the time to send a key frame. At 5 Mbps the 864,865-bit key frame of Chapter 3 needs 173 ms on the link. With a 30 ms RTT that is 203 ms.

Pick the repair

Each bar is the time until the repair arrives. The vertical line is the deadline. Green bars beat it. Raise the round trip time and watch NACK cross the line.

30 ms
100 ms
2.0%

A model with illustrative inputs: 12 packets per frame spread over one 33.3 ms frame period, 5 ms to notice a gap, a 5 Mbps link for the key frame, single XOR parity. Packet loss is independent and random. Real links lose packets in bursts, which hurts XOR parity more than this model shows.

On real hardware. On two Linux machines, add delay and loss with tc qdisc add dev eth0 root netem delay 150ms loss 2% and stream between them. Watch the NACK count in chrome://webrtc-internals or your RTCP logs, and see at what delay the picture stops recovering.

Reading the numbers

With the starting settings, all three tools fit inside the slack, except that PLI at 203 ms does not. Push the round trip up to 150 ms and NACK needs 155 ms against a 100 ms slack: it is now late. Every retransmission is sent anyway. The sender spends bandwidth, the receiver throws the packet away, and the frame stays frozen. This is the failure the story opened with.

FEC at k = 5 spends 20% extra bandwidth and repairs any single loss in a block of six packets. Its leftover loss is p × (1 − (1 − p)k). At p = 2% that is 0.02 × (1 − 0.985) = 0.02 × 0.0961 = 0.19%, down from 2%. Raise the loss and the leftover climbs fast, because two losses in one block cannot be repaired by one parity packet.

The rule of thumb

  1. If RTT + 5 ms fits inside the slack, use NACK. It is the cheapest.
  2. If the RTT is longer than the slack, use FEC, or accept the loss and hide it with slices and concealment.
  3. Keep PLI for the rare case when a frame cannot be decoded. Never let it be the main repair, because it triggers the key-frame spike of Chapter 3.

Failure mode

Symptom. More retransmissions, a higher bit rate, and the same freezes. Measurement. Count the retransmitted packets that arrive after their frame was already shown. In WebRTC the statistics show packets discarded as late. Fix. On a long link switch to FEC, or lower the key-frame rate and slice the frames.

The round trip time is 300 ms and the receiver can wait 100 ms. Which repair has any chance of working?

Chapter 8

The Jitter Buffer: Size by Percentile, Not RTT

Size the last waiting room before the screen from the worst delays you must cover, and see why the average hides them

A robot streams over Wi-Fi. The ping says 8 ms, steady. The picture stutters every few seconds anyway. The network is fast and the viewer still sees freezes. What did the ping miss?

The ping measured the average. The stutter comes from a few packets that arrive late in a bunch, for example when the radio retries a lost frame. The component that decides what to do with a late packet is the jitter buffer, and how big it is decides everything.

What jitter is

Frames leave the sender every 33.3 ms. They do not arrive 33.3 ms apart. Each takes a slightly different time on the way. Jitter is that variation in delay. The receiver wants to show frames at an even pace, so it holds each frame in a short queue and plays it at a fixed schedule. That queue is the jitter buffer. A frame that arrives before its slot waits. A frame that arrives after its slot is late. The viewer sees a freeze, or the receiver drops the frame.

Measure the variation with the relative transit time. For packet i, take its arrival time minus its RTP timestamp (converted to milliseconds). Subtract the smallest such value you have seen. What remains is how much later than the best case this packet was. RFC 3550 writes the difference between two packets as D(i, j) = (Rj − Ri) − (Sj − Si), with R the arrival time and S the timestamp, both in timestamp units.

How big should the buffer be?

The buffer must cover the delays you want to survive. A buffer of B ms plays a frame late only when its relative transit exceeds B. So the late rate is the share of frames above B. That is a percentile question: if you want 1% late, set B to the 99th percentile of the relative transit time. Percentile means the value below which that share of samples fall.

Two tempting rules fail. Setting B from the average round trip ignores the bursts. And setting it from RTCP’s jitter field fails for a quieter reason. RFC 3550 defines that field as a smoothed average: J(i) = J(i−1) + (|D(i−1, i)| − J(i−1)) / 16. It is a running mean of the size of the changes, so it moves slowly and a few big bursts hardly lift it. It is a good health meter. It is a poor size for a buffer.

A worked case

The device below uses a fixed made-up series of 300 frames, 10 seconds at 30 fps. Most frames are 1.5 to 8 ms later than the best case. About every two seconds a burst of 3 to 6 frames is 25 to 70 ms later still. Computed from that series:

  1. Mean relative transit: 5.2 ms. A buffer of 5 ms covers the average and misses every burst.
  2. 95th percentile: 30.9 ms. 99th percentile: 65.8 ms. The maximum is 70 ms.
  3. RTCP jitter J after 300 frames: 2.4 ms, less than the mean.

A buffer sized by the mean (5 ms) turns every frame in a burst into a late frame. A buffer at the 99th percentile (66 ms) covers nearly all of them, and pays 66 ms of delay for it. That is the trade of this chapter, in one line: each extra millisecond of buffer buys fewer late frames and costs one millisecond of glass-to-glass latency.

Run the jitter buffer

Each dot is a frame, placed by how late it arrived compared with the best case. The line is the buffer. Dots above it are late. Choose how the buffer is sized.

30 ms
99.0

An illustrative, seeded series, the same on every visit. For scale: Transitive Robotics saw a WebRTC jitter buffer of about 7 ms on a local connection and about 10 ms on a remote one, in chrome://webrtc-internals, on a quiet path. The late counts here come from the percentile arithmetic, not from a real radio.

On real hardware. Record the arrival time and RTP timestamp of every packet on a Raspberry Pi or Jetson receiver while a phone hotspot is busy. Plot the relative transit time, and compute its mean, its 95th and 99th percentile, and the RTCP J value.

Adaptive buffers

A fixed buffer is wrong whenever the network changes. A real receiver measures the relative transit time continuously and moves the buffer to a percentile of the recent window. Our adaptive mode does that over the last 100 frames. When a burst arrives the target rises. When the path is quiet it falls back, and the delay shrinks. Reducing the buffer takes care: playing a little faster, or dropping a frame, is how a real buffer sheds delay without a visible jump.

What late means

A late frame has two outcomes. The receiver can wait, and the picture freezes while the delay grows. Or it can drop the frame, and the next frame carries on. For teleoperation, dropping is usually right: the operator wants the newest picture, not a complete history. A frame dropped from the middle of a P-frame chain still hurts the decoder. So this choice ties back to the key-frame and repair story of Chapters 3 and 7.

Failure mode

Symptom. Freezes on Wi-Fi although the ping and the RTT are low. Measurement. Look at the arrival deltas as a histogram and at the high percentiles, not only at RTCP jitter or the mean. Fix. Use an adaptive buffer that follows a high percentile of the recent delay variation, and set the percentile to the late rate you can live with.

A path has a mean relative transit of 5 ms and a 99th percentile of 66 ms. You size the buffer at 5 ms. What happens?

Chapter 9

Glass-to-Glass: Measuring and the Anti-Pattern

Measure the whole stack with a camera pointed at its own screen, and see why a ping tells you almost nothing

A teammate says: “Our video latency is 30 ms. I pinged the robot.” You open the viewer and wave your hand. Your hand moves on the screen well after you moved it. You do not need a stopwatch to know that 30 ms is wrong. You need a method that sees what the operator sees.

Every chapter so far added one stage to a stack. Now we measure the stack as a whole, then split it back into stages. The method comes from Transitive Robotics, who published a careful measurement of a WebRTC video pipeline.

The infinite mirror

Point the camera at a screen. On that screen, show the live feed from the same camera, and draw a high-precision clock on top of it. The screen now shows the clock, plus a picture of itself as the camera saw it a moment ago, plus a picture of that picture, and so on. This is an infinite mirror. The clock shown in the first inner picture is older than the clock on the outside by exactly the glass-to-glass latency. Read two timecodes, subtract them, and you have one latency sample. Transitive’s example screenshot gave samples of 132, 132, 136 and 132 ms.

The method has a built-in blur. The camera takes a picture only every 33.3 ms at 30 fps. The screen refreshes only every 16.7 ms at 60 Hz. Each reading therefore includes a wait for the next camera exposure (0 to 33.3 ms) and a wait for the next screen refresh (0 to 16.7 ms). Take many samples, and expect their spread to be as wide as those two waits together. Transitive noted exactly these two limits.

Read the infinite mirror

The nested boxes are the screen inside the camera inside the screen. Each deeper box shows an older time. Set the pipeline latency, then press Take a sample several times.

110 ms

A model. Each sample equals the pipeline latency plus a random wait of 0 to 33.3 ms for the next camera exposure plus a random wait of 0 to 16.7 ms for the next screen refresh, so many samples average 25 ms above the pipeline latency. The timecodes and the random draws are generated in your browser.

On real hardware. On a Jetson or Raspberry Pi, show a millisecond clock on a 60 Hz monitor, point a USB camera at it, and photograph the monitor with a phone at high shutter speed. Read the two clocks in the photo and subtract.

The measured stack

Transitive ran three USB cameras on Ubuntu 24.04 with software H.264, at 30 fps into a 60 Hz screen. The totals were approximate:

  1. Direct (no H.264, no WebRTC): about 110 ms.
  2. Direct with H.264 (encode and decode only): about 130 ms.
  3. Local WebRTC: about 130 ms, with a jitter buffer of about 7 ms.
  4. Remote WebRTC through a relay (client in California, relay in Oregon, ping 30 ms): about 170 ms, jitter buffer about 10 ms, and about 40 ms more than the local case, of which 30 ms is the ping delay.

The breakdown they report: camera plus USB bus about 100 ms, encode about 10 ms, decode about 10 ms, and WebRTC itself about 10 ms. Notice what is missing from the list: the biggest stage in the whole stack was the camera and its USB bus. The encoder, the network and the buffer together were smaller than the camera. Chapter 0’s 1.3 seconds was an accident of defaults. Once the accident is removed, the next target is the front of the stack.

Compare the four measured stacks

Pick a case. The stacked bar shows the stages. The thin grey bar is what a ping of the same path would tell you.

Totals and stages from Transitive Robotics, “WebRTC Latency: A Breakdown”: camera plus USB about 100 ms, H.264 encode and decode about 10 ms each, jitter buffer about 7 ms local and 10 ms remote, and 30 ms of network ping delay inside the 40 ms the remote case adds. The “other” piece is the total minus the listed stages. All figures are approximate and are for software H.264 on USB cameras.

The ping anti-pattern

A ping measures the round trip of a tiny packet across the network. In the remote case it was 30 ms, which is 18% of the 170 ms total. It says nothing about the 100 ms camera, the encoder queue, the jitter buffer, the decode or the display. Quoting it as the video latency is the most common error in this field.

What to use instead depends on the question. The RTCP round trip time (Chapter 6) measures the media path, including receiver delay. A one-way delay needs both ends on the same clock. One forum report describes the method: stamp each frame when the V4L2 buffer is produced, carry the stamp in an RTP header extension, and compare it with the receiver’s clock at display, with both machines synchronised by chrony. That is the live version of the infinite mirror.

The ITU-T G.114 recommendation gives a scale for conversation. It treats 150 ms one way as a target for interactive use and 400 ms one way as a planning limit that should not be exceeded, and it notes that highly interactive tasks suffer at lower delays. A teleoperation loop is more demanding than a phone call.

Two display details

The display adds a wait of 0 to 16.7 ms on a 60 Hz screen, because a new frame can only appear at a refresh. Turning off vsync removes that wait and brings tearing. And when the camera clock and the display clock are not locked, a 30 fps stream drifts against a 60 Hz screen. Now and then one frame stays for three refreshes and the next for one. The eye sees that as judder.

Failure mode

Symptom. Someone reports low latency while the operator complains. Measurement. Ask which clock the number came from. A ping, an RTCP round trip and a glass-to-glass reading are three different things. Fix. Measure glass to glass with the mirror, then split the stack stage by stage.

Which measurement tells you how late the operator’s picture is?

Chapter 10

Field Guide

Keep the numbers, the checklist and the core code for the next time a stream is late

Glass-to-glass latency is a stack of stages, and each stage has its own knob. The encoder holds frames for B-frames and lookahead, so turn them off first. The link must carry the largest frame, so spread the key frame and keep the VBV small. Repairs must beat the deadline, so choose NACK or FEC by round trip. The jitter buffer must cover a high percentile, not the mean. And measure the whole stack with a camera pointed at its own screen, never with a ping.

The numbers and terms

ItemValueSource and note
x264 rc-lookahead (default)40 frames = 1,333 ms at 30 fpsx264 0.165 help text; zerolatency sets it to 0
x264 bframes (default)3 B-frames = 100 ms of reorder at 30 fpsx264 0.165 help text; zerolatency sets 0
x264 keyint (default)250 frames = 8.3 s at 30 fpsx264 0.165 help text
Raw 1080p30, 4:2:0, 8-bit746 Mbps (3.11 MB per frame)Arithmetic: 1,920 x 1,080 x 30 x 8 x 1.5
Raw 4K60, 4:2:0, 10-bit7.46 GbpsArithmetic: 3,840 x 2,160 x 60 x 10 x 1.5
H.264 Qstep0.625 at QP 0, doubles every 6 QP, 224 at QP 51Richardson, The H.264 Advanced Video Compression Standard
RTP video clock90 kHz; 3,000 ticks per frame at 30 fpsRFC 6184 section 5.1
Marker bit (H.264)set on the last packet of the access unitRFC 6184 section 5.1
Interarrival jitterJ += (|D| - J) / 16RFC 3550 section 6.4.1
NVENC 1080p H.264, Ada, P1, CBR, low latency910 fps per engine (throughput, not latency)NVIDIA Video Codec SDK application note
NVENC lookaheadup to 32 frames; output withheld while it fillsNVENC programming guide, section 8.2
Jetson AGX Thor videoencode up to 6 x 4Kp60 (H.265, H.264); decode up to 4 x 8Kp30 or 10 x 4Kp60; AV1 decode listed, AV1 encode notSecondary pages (RidgeRun wiki, Peridio). Verify on the device and in NVIDIA’s datasheet
Camera plus USB busabout 100 msTransitive Robotics, measured
H.264 encode, decode, jitter bufferabout 10 ms, 10 ms, 7 to 10 ms (software H.264)Transitive Robotics, measured
Glass-to-glass, four cases110, 130, 130, 170 msTransitive Robotics: direct, direct H.264, local WebRTC, remote WebRTC
Conversation delay150 ms target, 400 ms planning limit, one wayITU-T G.114 (2003 text and a draft revision). Highly interactive tasks suffer at lower delays
WHIPpublished as RFC 9725, March 2025, Standards Trackrfc-editor.org
Media over QUIC transportdraft-ietf-moq-transport-23 on 2 Nov 2026, still a draftIETF datatracker. An earlier note cited -20: the number moves
AV1 hardwareMeta’s 24 Sep 2025 white paper says many phones lack AV1 hardware; one quoted estimate is about 10% of Android with hardware AV1 decodeMeta engineering blog and trade press. AV1 SVC in WebRTC and AV1 encode on Thor: not verified here

A checklist for a late stream

The core as code

The encoder settings as an ffmpeg command. The flags were checked by running them on a synthetic 720p30 source.

bash
# x264, low latency: no B-frames, no lookahead, a 2-frame VBV at 4 Mbps, key frame every second
ffmpeg -f v4l2 -video_size 1280x720 -framerate 30 -i /dev/video0 \
  -c:v libx264 -preset ultrafast -tune zerolatency -bf 0 -g 30 \
  -b:v 4M -maxrate 4M -bufsize 266k -f rtp rtp://127.0.0.1:5004

The adaptive jitter buffer of Chapter 8 in 25 lines of Python. It takes an RTP timestamp in milliseconds and an arrival time. It returns when to play the frame, the buffer target, and whether the frame was late.

python
from collections import deque

def make_buffer(percentile=0.99, window=100):
    """Adaptive jitter buffer. Feed one (rtp_ts_ms, arrival_ms) pair per frame."""
    hist = deque(maxlen=window)
    base = None                     # smallest (arrival - timestamp) seen: the best-case path
    def push(rtp_ts_ms, arrival_ms):
        nonlocal base
        transit = arrival_ms - rtp_ts_ms
        base = transit if base is None else min(base, transit)
        rel = transit - base        # how much later than the best case
        s = sorted(hist)            # the recent past sets the target
        target = s[min(len(s) - 1, int(percentile * len(s)))] if s else 0.0
        hist.append(rel)
        play_at = rtp_ts_ms + base + target       # when to show this frame
        return play_at, target, rel > target      # rel > target: it missed its slot
    return push

push = make_buffer(0.99)
late = 0
for i in range(300):
    ts = i * 1000 / 30
    arrive = ts + 20 + (60 if i % 70 < 4 else 2)
    _, target, is_late = push(ts, arrive)
    late += is_late
print(round(target, 1), "ms target,", late, "late of 300")

Where this sits

This lesson covered the video path from the encoder to the screen. The camera and bus stage, the largest in the measured stacks, starts with the V4L2 buffer queue. The transport choices for a whole robot link continue in teleoperation transport. For a Jetson in the field see Jetson bring-up. The ring buffers that sit between capture and encode, and how they drop frames, are a separate real-time topic in the Physical AI series. The same ideas apply to sound in neural audio codecs, and what a model does with the frames afterwards is in video understanding. The voice-agent stack has its own latency budget and is a planned topic. For the timing basics see robot real-time performance and sensor and actuator integration.

Sources

  1. Transitive Robotics, WebRTC Latency: A Breakdown, and the related Open Robotics forum discussion.
  2. x264 0.165 help text (x264 --fullhelp), run locally, and ffmpeg/ffprobe runs on a test clip.
  3. RFC 3550 (RTP), RFC 6184 (H.264 RTP payload), RFC 9725 (WHIP).
  4. NVIDIA Video Codec SDK: NVENC Video Encoder API Programming Guide and NVENC Application Note.
  5. Linux kernel documentation, V4L2 stateful video encoder interface.
  6. WebRTC for the Curious, media communication chapter.
  7. Iain Richardson, The H.264 Advanced Video Compression Standard, 2nd edition.
  8. ITU-T Recommendation G.114, one-way transmission time.
  9. Meta Engineering, video streaming with the AV1 codec on mobile devices (24 Sep 2025); IETF datatracker for draft-ietf-moq-transport.
The takeaway. Latency hides in stages that wait. Find the stack, measure each stage, and switch off every wait you did not choose.

Next, say the whole story aloud in your own words with Teach, or go back to the hero at the top and shrink the stack again, this time knowing why each knob works.

Low-Latency Video: Encode, Packetise, Recover
Transitive Robotics, WebRTC Latency: A Breakdown · Back to Gleams