Live streams

Publishing streams

Send encrypted live data from Python, the native plugin, or any language.

Credentials

Publishing needs a Kymoscope API key: create one in your account and put it in your script. It says who publishes and what your plan allows (cameras, viewers at once, data rate). Only its auth part is sent to Kymoscope. Who may watch is a separate choice: the stream password you set (below), or a project. See Who can watch a stream.

Your own streams open in any browser you sign in to, with nothing to type. Each browser holds a device key pair whose private half never leaves it; the sender seals the stream key to every device of your account (on register and every heartbeat, via the wrap_keys action), and the server only stores those sealed keys. You can see and revoke devices in your account. To let someone else watch, give them the stream password (password=); never the API key, which also lets them publish as you.

Python

Install the kymoscope package from PyPI (Python 3.9 or later).

Shell
pip install kymoscope
Python
import math, time
from kymoscope import LiveStream

API_KEY = "kymoscope_..."   # Account -> API & real-time streaming, or a project's API key
# mode/hz/channels declare what it sends; state_path keeps this sender's identity, so a restart needs no new approval
with LiveStream(API_KEY, "Rig A", mode="live", hz=60, channels=1, state_path="kymoscope-state.json") as stream:
    print("stream id:", stream.stream_id)
    while True:
        t = time.time()           # absolute (Unix seconds)
        stream.send([{"t": t, "signals": [
            {"name": "speed", "unit": "m/s", "value": 50 + 10 * math.sin(t)},
        ]}])
        time.sleep(1 / 60)

Every stream declares what it sends, and Kymoscope admits it against your plan when it starts: mode is "live" (watched as it comes) or "record" (also kept in the cloud); hz and channels are its samples a second and channel count, or sources=[{"hz": 10, "channels": 2}, {"hz": 1, "channels": 40}] for channels at different rates. At start it prints what it was given and what is left:

Shell
Kymoscope: 'Rig A' admitted (live, 60 Hz × 1 ch = 7 kbit/s). Left: 8 Mbit/s of 8 Mbit/s live.

A stream your plan can't take is refused at start with the reason (RegistrationError). While it runs, a notice (for example, recording stopped because storage is full) goes to on_status (stderr by default). See Limits and usage. Senders before 1.0 are refused: update with pip install -U kymoscope.

  • The package registers the stream, encrypts, keeps the stream alive and renews its credentials.
  • It only sends while at least one viewer is connected, unless it keeps a buffer (below).
  • A viewer who joins sees every channel at once, including one that rarely changes.
  • The API key decides where the stream goes: a key created in a project’s API keys tab publishes into that project, where only its members see it; a personal key publishes a personal stream.
  • password="…" is the stream password viewers type (12 characters or more; a shorter one raises an error unless you pass allow_short_password=True). Without one, the API key’s secret is used and the log asks for a password.
  • visibility is "private" (the default: listed, behind the password) or "open" (anyone watches with nothing typed; not end-to-end encrypted; no password).
  • Leaving the with block (or close()) keeps the stream registered, so a restart with the same state_path resumes it. If the stream is no longer in the key’s project (you switched to a project key, or someone moved the stream out), the restart leaves it as it is and starts a new stream of the same name in the key’s project. Pass delete_on_exit=True (or close(delete=True)) to delete it.

At high rates (up to your plan's 1 kHz per source), send blocks by column with send_columns: lists, arrays or numpy arrays, a few times a second. Values travel as float32 (float64 for the channels you name), times as float64; large blocks are split for you. If you send faster than the stream declared, send_columns waits instead of losing data.

Python
import time
import numpy as np

RATE = 1_000                      # Hz (your plan's maximum per source)
t0 = time.time()
n = 0
with LiveStream(API_KEY, "Test bench", mode="live", hz=RATE, channels=2) as stream:
    while True:
        time.sleep(1 / 30)        # ~30 blocks a second
        due = int((time.time() - t0) * RATE) - n
        t = t0 + (n + np.arange(due)) / RATE
        stream.send_columns(t, {"accel_x": read_accel_x(due), "strain": read_strain(due)},
                            units={"accel_x": "g", "strain": "µε"})
        n += due

With many channels that change one at a time (thousands of tags, each on change), send events with send_events(names, index, t, values, units=None): event k is channel names[index[k]] at time t[k] with values[k], and names is the stream's whole channel list. No times × channels block is built, so a stream can carry up to 100,000 channels. Declare how many values a second it sends with events_per_sec; pass the same names list on every call while it doesn't change.

Python
import time

names = [f"TT-{i}.PV" for i in range(50_000)]
with LiveStream(API_KEY, "Line 2", mode="live",
                sources=[{"hz": 10, "channels": len(names), "events_per_sec": 5_000}]) as stream:
    while True:
        time.sleep(0.05)
        index, t, values = read_changes()          # which channels changed, when, and their new values
        stream.send_events(names, index, t, values)

Add a camera to the stream

Python
with LiveStream(API_KEY, "Rig A", mode="live", hz=60, channels=1) as stream:
    stream.add_camera("Front", "video=Integrated Camera", input_format="dshow", mode="live", quality="720p", fps=30)
    ...

add_camera needs ffmpeg on PATH and declares its own mode, quality and fps. The camera is a channel of the stream and opens with it. See Cameras.

Record to files

Python
with LiveStream(API_KEY, "Rig A", mode="record", hz=1000, channels=8, state_path="kymoscope-state.json",
                split_every="1h", buffer_path="kymoscope-buffer", buffer_max_mb=2048) as stream:
    ...

A record stream is recorded by this sender (kymoscope 1.1 or later): cut into files every split_every on the clock (default: from the declared rate, files of about 150 MB), written under buffer_path/rec (default ~/.kymoscope/buffer), uploaded and deleted locally once stored. Through an outage or a restart the files wait on disk, up to buffer_max_mb (default 2048; past it the oldest pieces go and the sender says so). storage= and retention_days= are for a project that records to its own storage. stream.pause_recording() ends the current file and records nothing until stream.resume_recording(), for example while a machine is stopped. The settings are the same in every sender: see Recording.

Keep live data when the connection drops

With buffer_path (a folder), a live stream keeps what it couldn't send through an outage that starts while someone watches: the encrypted messages wait on disk and are sent in order when the relay is back and someone watches. With nobody watching when the relay becomes unreachable, nothing is kept; a crash can send a few messages twice. buffer_max_mb caps the disk used; when it is full, new samples are dropped and counted in stream.buffer_dropped. buffer_min_free_mb (default 0, off) also stops buffering when the disk has less free space than that. Send absolute times (time.time()), so data sent after a restart lands in the right place.

Run alerts on this machine

Shell
pip install "kymoscope[rules]"
Python
with LiveStream(API_KEY, "Press 2", mode="live", hz=10, channels=1, state_path="kymoscope-state.json",
                rules=True, on_alert=print) as stream:
    ...
  • rules=True runs the project's alerts set to run on the sending machine on every block you send, watched or not, before it is encrypted (blocks sent with historical=True count as late). It asks for them again every minute. Needs the rules extra (numpy).
  • Your data stays on this machine: Kymoscope gets which alert, the stream, the times of each start and end and the episode's duration and peak (sealed with the project key in end-to-end encrypted projects), plus a check-in every minute. They wait in a queue on disk (buffer_path/alerts, else next to state_path, else ~/.kymoscope/alerts) that survives an outage or a restart.
  • on_alert is called here for every change, with a dict: rule, ruleId, ruleVersion, severity, stream (its id), kind (raised, cleared or lost), t, raisedAt, late, peak and values (the alert's channels at t).

See Alerts with nobody watching for the whole setup.

The stream sends the compact format by default; block_format=False sends the classic format for viewers on SDK versions before 0.2.0 or self-hosted relays before 0.2.0 (buffer_path and record always use the compact one).

Any language (personal streams)

The protocol for personal streams is small enough to implement anywhere with HTTPS, WebSocket, PBKDF2 and AES-GCM. It does not publish into end-to-end encrypted projects (the server answers sender_update_required); use the kymoscope Python package or the native plugins for those.

  1. Mint a publisher token. POST https://api.kymoscope.com/functions/v1/stream-token with header x-api-key set to the auth part of the key only (everything before the .); never send the secret part. The response has token (a pt. token, 15 minutes), userId, relayUrl, maxBytesPerSec and maxViewers (the bandwidth and viewers per stream agreed for your account), maxMessageBytes (the relay’s message size limit) and maxRateHz (for senders of 0x02 batches). The token only works with the publishing endpoints below; it is not an account session.
  2. Derive the key. salt is 16 random bytes (base64). The key is PBKDF2-HMAC-SHA256(secret, salt, 600,000 iterations, 32 bytes), where secret is the part of the API key after the . (or a password, if you prefer one). key_check is AES-256-GCM of the bytes "kymoscope-live-key-check-v1" including the quotes: { iv, ciphertext }, both base64, ciphertext with the 16-byte tag appended.
  3. Register the stream. POST https://api.kymoscope.com/functions/v1/stream-publisher with Authorization: Bearer <pt. token> and body { "action": "register", name, salt, key_check, visibility, profile }, where profile is { "mode": "live" | "record", "hz": 100, "channels": 8 } (see Limits and usage). Declare live: a record stream also declares split_every (seconds) and uploads its own files (see Recording), which the kymoscope package does for you. The response has stream (id, share_code), usage.message (what was admitted and what is left: print it) and ticket, a pp. publish ticket valid for 10 minutes for this stream only. A profile your plan can't take is refused with 403 over_plan and a message to show as is; no profile is 400 sender_update_required. The API key decides where the stream goes: a project’s key into that project, a personal key a personal stream. Re-registering the same stream_id keeps the stream where it is (for example after someone moved it in the app) while you may still publish there. Given the stream_id of a stream outside the key’s project, register leaves it untouched and returns a new one in the key’s project, so always keep the id the response returns; heartbeat, delete and wrap_keys answer 403 key_project_mismatch for the other one. After a delete, the next register goes where the API key belongs, so to keep a placement made in the app, don’t delete the stream on exit.
  4. Connect. Open wss://<relay>/v1/streams/<id>/publish with Sec-WebSocket-Protocol: kymoscope-live.v1, bearer.<pp. ticket>. The relay sends {"type":"viewers","count":n}; send only while n > 0, and send the text ping every 30 seconds.
  5. Send batches. One binary message per batch: [kind][12-byte IV][AES-256-GCM(plaintext, aad = kind) ‖ tag], where the plaintext is either msgpack({frames:[{t, signals}]}) (kind 0x02) or a block of samples by column (kind 0x03, below). Pace your sending to what the stream declared (bursts of up to 2 seconds are fine): messages past it are dropped.
  6. Stay listed and authorised. Every ~10 s call stream-publisher with { "action": "heartbeat", stream_id }; it returns a fresh ticket, and sometimes a notice ({ code, message }, for example recording stopped because storage is full) to write to your log. Before the socket’s ticket expires, send {"type":"auth","token":"<new ticket>"} as text, or the relay closes it with code 4401. On exit call { "action": "delete", stream_id }, and mint a new pt. token before the old one expires.

Column blocks (kind 0x03), for high sample rates. Little-endian; every block names its channels, so a viewer joining mid-stream needs nothing else:

Column block layout
u8   version = 1
u8   reserved = 0
u16  channel count C
u32  sample count n
C x  u8 bytes per value (4 = float32, 8 = float64), u8 name length, u8 unit length,
     name (UTF-8), unit (UTF-8)
zero padding to a multiple of 8 bytes
n x  float64 time (non-decreasing)
per channel: n values, zero-padded to a multiple of 8 bytes   (NaN = missing)

Native Le Mans Ultimate plugin

A self-contained C++ DLL streams the simulator’s telemetry (around 80 channels at 60 Hz) with the same protocol, using only Windows APIs. It is a working reference for embedded or native publishers. The Assetto Corsa plugin works the same way. With Mode=record they record only while the car is driven, one file per stint, cut further by SplitEvery; live never stops. The files wait in the KymoscopeRecordings folder next to the plugin until they are uploaded.

KymoscopeLiveTelemetry.ini
[Kymoscope]
ApiKey=kymoscope_...
Name=Le Mans Ultimate
Mode=record
Hz=100
SplitEvery=1h          ; optional: from the rate (about 150 MB a file)
BufferMaxMB=2048       ; optional
; StorageFolder=\\server\recordings  (only for a project that records to its own storage)

StorageFolder, or StorageEndpoint, StorageRegion, StorageBucket, StoragePrefix, StorageAccessKey and StorageSecretKey, and RetentionDays are read only when the project records to its own storage. See Recording.