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.
janelkit Included with janelkit. Nothing extra to install. 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 for | Why | What 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 compositor | A 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 guarantees | The 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 else | Frames does not report when each image is presented, and one may take a refresh longer than another | Synchronize in hardware (the camera trigger), or measure the whole system’s latency and compensate |
| Showing every frame without losing any | Frames keeps the latest on purpose: if images arrive faster than they are drawn, they are skipped | A 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 timestamps | A player: QtMultimedia (in PySide6-Addons) or an external one |
| 4K at 60 fps, or many 1080p views | The cost grows with the pixels: at 1080p, push to delivery is already about 5 ms (11 ms at p95) on that laptop | Shrink 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.
# 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 assignmentCopyHow it works
- The state is read on the interface thread, before the await, and frozen into Options.
- cycle runs in a worker. Reading or assigning state there raises WrongThreadError, with the right way in the message.
- 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 ==).
# 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]CopyHow it works
- Lists, dictionaries and sets inside a state become reactive collections: changing them in place notifies.
- Tuples, NamedTuples and frozen dataclasses cannot change in place; assign a new one.
- 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.
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.
# main.py
import torch # noqa: F401 (loaded here, on the main thread)
from ultralytics import YOLO # noqa: F401
from janelkit import runCopyMeasure 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 period | 1 ms | 5 ms | 10 ms | 15 ms | 33 ms | 100 ms |
|---|---|---|---|---|---|---|
| Ticks per second | 971 | 200 | 100 | 67 | 30 | 10 |
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 ↗.