← Portfolio

When drawing cannot keep up with the camera

Tech note · Concurrency, equipment UI · Related project New particle-removal tool SW

What looked wrong

On the new tool, during long continuous capture the display fell further and further behind, memory kept growing, and in the end the program froze. Capture itself was fine. The problem was on the side that drew the received frames on screen.

Cause: a small slowness piles up without end

Say the camera sends a frame every 33 ms (30 fps) and drawing takes 36 ms on average. The gap is only 3 ms per frame, but if every received frame is drawn in turn, the number of frames not yet drawn keeps growing in proportion to time. When processing is slower than arrival, the queue can never shrink.

Frames not yet drawn over continuous capture time. Drawing every frame piles up over 700 in 5 minutes; drawing only the latest stays at 1 or fewer
Synthetic simulation: 30 fps capture, 36 ms average drawing time. Drawing every frame in order piles up over 700 frames in 5 minutes; drawing only the latest stays at 1 or fewer. The code is fig_stable in tools/make_figures.py

A bigger buffer only delays the freeze. The piled-up frames take memory, and the screen shows a moment further and further in the past.

The fix: only the latest frame, one at a time

The screen does not need to show every frame. What people look at is the current state. So when a new frame arrives, the previous frame that has not been drawn yet is dropped, and only one draw runs at a time.

// Concept code (C#). Keep only the most recent frame and a "drawing" flag
Frame? latest;
int drawing;

void OnFrame(Frame f)                      // camera thread
{
    Interlocked.Exchange(ref latest, f)?.Dispose();          // drop the previous frame that was not drawn
    if (Interlocked.CompareExchange(ref drawing, 1, 0) == 0)  // if not drawing, schedule a draw
        ui.BeginInvoke(Draw);
}

void Draw()                                 // UI thread
{
    var f = Interlocked.Exchange(ref latest, null);
    if (f != null) { Render(f); f.Dispose(); }
    Volatile.Write(ref drawing, 0);
    // if a new frame arrived while drawing, run once more
    if (Volatile.Read(ref latest) != null && Interlocked.CompareExchange(ref drawing, 1, 0) == 0)
        ui.BeginInvoke(Draw);
}

Takeaway

A queue whose processing is slower than arrival will overflow sooner or later, whatever the buffer size. First decide “can this data be dropped?”, and on the paths where it can, keep only the latest value. Also check that the worst-case processing time, not the average, is shorter than the arrival interval.

To calculate it yourself from your own settings or timing logs, use the Frame backlog simulator. Run the "Slow drawing" example for 5 minutes and hundreds of frames pile up, as in the figure above.

The figure and code were made from scratch to explain the principle. They are not code from the equipment.