GUIDE / REAL TIME

Real-time applications

What latency to expect from video, and the patterns that keep a live application correct and responsive: the processing cycle, state after an await, and views that are not seen.

Core janelkit Included with janelkit. Nothing extra to install.
CHAPTER 22 / 29~4 min read · try examples at your own pace
Alpha / 0.2 — These pages document JanelKit 0.2 and its packages. Each series (0.1, 0.2…) may change the public API, always with migration notes: see Changes and migration. The website uses Svelte; the desktop examples use Python and JanelKit, not JavaScript.

What you will learn

  • What latency <video> gives, and the cases it is not built for.
  • How to structure a processing cycle so heavy work never touches state.
  • Why state can look half-updated after an await, and how to avoid it.
  • How to stop work that nobody sees, and how to measure a cycle.

What latency to expect

From push until the image is drawn takes one refresh of the monitor plus a few milliseconds. From 640 × 480 to 1080p that is 13 to 17 ms at the median and 21 to 32 ms at the 95th percentile, measured with a real window on a 2013 laptop with a 60 Hz screen, on Windows with Direct3D 11; Linux and macOS have not been measured. Almost all of it is waiting for the next refresh: up to 16.7 ms at 60 Hz. What your camera and your code take comes on top.

That is enough to watch cameras or processed video live, from 15 to 60 fps and up to 1080p, with boxes, labels and clicks over it: inspection, monitoring, labeling, calibration, machine dashboards. Several views at once work too, because each push costs on the thread that calls it, not on the interface thread.

Not built forWhyWhat to do
Less than one refresh between image and screen (VR or AR headsets, following a hand with no delay)Drawing waits for the monitor refresh and goes through the system compositorA graphics engine that presents directly, outside JanelKit
A control loop that decides from what is on screen, or hard deadlines (every 5 ms without fail)Python, its garbage collector and the interface handlers can delay the interface thread, and the operating system gives no timing guaranteesThe control in its own thread or process, reading the camera directly; the interface only shows and configures
Knowing the exact refresh in which each frame appears, or syncing the screen with something elseFrames does not report when each image is presented, and one may take a refresh longer than anotherSynchronize in hardware (the camera trigger), or measure the whole system’s latency and compensate
Showing every frame without losing anyFrames keeps the latest on purpose: if images arrive faster than they are drawn, they are skippedA queue of your own in the camera thread to record or analyze every frame; Frames only for the view
Playing video with synchronized audio<video> shows loose images: it does not decode, and has no audio or timestampsA player: QtMultimedia (in PySide6-Addons) or an external one
4K at 60 fps, or many 1080p viewsThe cost grows with the pixels: at 1080p, push to delivery is already about 5 ms (11 ms at p95) on that laptopShrink the image to the size it is shown at before push (cv2.resize)

Common mistakes

  • Push from the camera thread or inside background(), not from a timer on the interface thread: there, the copy and conversion of each image cost the interface.
  • Keep handlers and effects short: while the interface thread is busy, the next image waits to be delivered.

The cycle: runner, Options and Snapshot

Heavy work, such as reading the cameras and running the model, goes to a thread with background(). That code never touches state: it receives everything it needs in an object built before the await (Options), and returns an immutable result (Snapshot) that the tick applies when it comes back. The runner does not import janelkit, so it is tested without a window.

python
# core/runner.py: does not import janelkit, so it is tested without a window.
from typing import NamedTuple

class Options(NamedTuple):
    threshold: float
    cameras: tuple[int, ...]

class Snapshot(NamedTuple):
    frames: dict
    detections: tuple

def cycle(images, options: Options) -> Snapshot: ...

# pages/Live.janel, in the script:
@interval(15)
async def tick():
    options = runner.Options(threshold.value, tuple(cameras.value))     # read state here
    snapshot = await background(runner.cycle, hub.read_all(), options)  # the model, in a thread
    for index, image in snapshot.frames.items():
        previews[index].push(image)
    detections.value = snapshot.detections                               # one assignment
Copy

How it works

  1. The state is read on the interface thread, before the await, and frozen into Options.
  2. cycle runs in a worker. Reading or assigning state there raises WrongThreadError, with the right way in the message.
  3. An async interval skips ticks while the previous run has not finished: a 50 ms cycle with interval(15) runs about 17 times per second, without piling up.

What you should see

The window keeps responding while the model works. tick.skipped grows if the cycle does not fit in its period, and tick.last_duration tells you how long the last one took.

State after an await is not grouped

Inside a handler or a tick, everything you change goes in one batch: effects and the interface update once, at the end. After an await, that is no longer true: each assignment notifies on its own. An effect that reads count and label runs after the first assignment, sees the new count with the old label, and runs again after the second. Group the assignments with batch(), or assign a single value, such as a NamedTuple with everything.

Assigning the whole state in every cycle costs nothing when it did not change: assigning a value equal to the current one notifies nobody (they are compared with ==).

python
# Ordinary Python: what notifies, and when.
from typing import NamedTuple
from janelkit import batch, effect, state

class Status(NamedTuple):
    count: int
    label: str

items = state([1, 2])
status = state(Status(0, "idle"))
seen = []
effect(lambda: seen.append((len(items.value), status.value.label)))

items.value.append(3)                                  # a reactive list notifies
status.value = status.value._replace(label="busy")     # a tuple is replaced, not changed
status.value = Status(0, "busy")                       # equal to the current value: no one is notified
with batch():                                          # two writes, one notification
    items.value.append(4)
    status.value = Status(1, "done")
assert seen == [(2, "idle"), (3, "idle"), (3, "busy"), (4, "done")]

original = [1]
copy = state(original)                                 # state copies lists, dicts and sets
original.append(2)
assert copy.value == [1]
Copy

How it works

  1. Lists, dictionaries and sets inside a state become reactive collections: changing them in place notifies.
  2. Tuples, NamedTuples and frozen dataclasses cannot change in place; assign a new one.
  3. Your own objects and NumPy arrays do not notify when changed in place: call s.notify(), or assign a new value. A NumPy array always counts as a change, because its == does not return a bool.

Common mistakes

  • Do not change the list you passed to state() and expect an update: state keeps a reactive copy. Change the one in s.value.

Views that are not seen keep working

A view that is kept but not shown, such as an inactive section of janelkit-router, a covered page or a {#hidden} block, stops updating its template, but its script keeps running, timers included. To avoid work nobody sees, make the timer depend on whether the component is seen. when= accepts any reactive condition: when=hub.ready, or when=lambda: visible.value and hub.ready.value. An effect can read visible too, for example to release a camera while the view is hidden.

python
from janelkit import interval, is_visible

visible = is_visible()

@interval(15, when=visible)          # does not count while the component is not seen
async def tick():
    ...
Copy

Learn moreTimers ↗

Import heavy native libraries at startup

PyTorch, ultralytics, MediaPipe or TensorFlow load large native libraries when imported. Import them on the main thread and early, in main.py before run(); in background(), only create the models. A first import inside background(), while OpenCV reads cameras in other threads, has been seen to crash the process with a memory access violation on Windows.

python
# main.py
import torch                    # noqa: F401 (loaded here, on the main thread)
from ultralytics import YOLO    # noqa: F401
from janelkit import run
Copy

Measure a cycle

The timer already measures itself: tick.last_duration is the duration in seconds of the last complete run, async part included; tick.runs counts the runs and tick.skipped the ticks skipped because the previous run was still going. If skipped grows, the cycle does not fit in its period.

To measure by hand on Windows, use time.perf_counter(): time.monotonic() advances in steps of 15.6 ms there, too coarse for a 15 ms cycle. JanelKit’s timer uses a precise Qt timer below one second; with an idle window, interval(15) ticks about 67 times per second and interval(5) about 200.

Requested period1 ms5 ms10 ms15 ms33 ms100 ms
Ticks per second971200100673010

Key points

  • Video latency is one monitor refresh plus a few milliseconds; it is not for hard deadlines or sub-refresh needs.
  • Heavy work runs in background() with Options in and a Snapshot out; it never touches state.
  • After an await, group assignments with batch() or assign one value.
  • Pause hidden work with when=is_visible(), and measure with last_duration, runs and skipped.

English documentation based on the JanelKit source. For additional details, browse the source docs ↗.