Several sources, one record
Record video, audio and instrument readings on one machine, on one clock, so a trial's data can be lined up afterwards, and watch it live without touching the recording. A research lab example.
An experiment often has a camera, a microphone and an instrument or two, each with its own software, its own files and its own idea of the time. Lining them up afterwards becomes its own project: which video frame matches this sensor reading, and was anything lost?
With Tato, one stream reads every source on the machine, and every frame, audio block and reading is stamped by the same stream clock. The trial’s data lands in files you can analyze with your usual tools, and anyone can watch the trial live in Tato Studio’s Node visualizer without touching the recording.
CameraSource ─┬─ MotionDetector ─ motion ─────┐ │ ├─ TrialLogger ─▶ trial-….csvUdpSensor ─ readings ─────────────────────────┘ └─ H264Encoder ─▶ VideoRecorder ─▶ trial-….h264, trial-…-frames.csvMicrophoneSource ─▶ WavWriter ─▶ trial-….wavThe stream
Section titled “The stream”MotionDetector is the tutorial’s node. The other four are short nodes of your own. Each file node names its files in setup, by the time the trial started, so each play of the project writes a new set.
The instrument sends one reading per UDP datagram. A continuous node drains its socket a hundred times a second:
import socketfrom dataclasses import dataclass
from tatolab.stream import Output, Records, RuntimeContextFullAccess, RuntimeContextLimitedAccess, node
@dataclassclass UdpSensorConfig: port: int = 9000
@node.meta(category="Sources", description="Writes each UDP datagram that reaches a port as one reading.")@node.process(execution="continuous", interval_ms=10)class UdpSensor: readings = Output(Records, names=("text",))
def __init__(self, config: UdpSensorConfig) -> None: self.port = config.port
def setup(self, ctx: RuntimeContextFullAccess) -> None: self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.bind(("0.0.0.0", self.port)) self.socket.setblocking(False)
def process(self, ctx: RuntimeContextLimitedAccess) -> None: while True: try: datagram = self.socket.recv(65_535) except BlockingIOError: return ctx.outputs.write(self.readings, {"text": datagram.decode(errors="replace").strip()})
def teardown(self, ctx: RuntimeContextFullAccess) -> None: self.socket.close()Each reading is stamped with stream time when it’s written. The logger writes both inputs to one CSV, each row with its stamp:
import csvimport timefrom pathlib import Path
from tatolab.stream import Input, Records, RuntimeContextFullAccess, RuntimeContextLimitedAccess, node
@node.meta(category="Output", description="Writes motion and sensor readings to one CSV, each with its timestamp.")@node.processclass TrialLogger: motion = Input(Records, delivery="ordered", requires=("changed",)) readings = Input(Records, delivery="ordered", requires=("text",))
def setup(self, ctx: RuntimeContextFullAccess) -> None: name = time.strftime("trial-%Y%m%d-%H%M%S.csv") self.file = (Path(ctx.stream_project_directory) / name).open("x", newline="") self.writer = csv.writer(self.file) self.writer.writerow(["timestamp_ns", "source", "value"])
def process(self, ctx: RuntimeContextLimitedAccess) -> None: for port, source, key in ((self.motion, "motion", "changed"), (self.readings, "sensor", "text")): while True: record, timestamp_ns = ctx.inputs.read_with_timestamp(port) if record is None: break self.writer.writerow([timestamp_ns, source, record[key]]) self.file.flush()
def teardown(self, ctx: RuntimeContextFullAccess) -> None: self.file.close()VideoRecorder is the H264File node from Encode and save, with a second file: for each access unit it writes, it adds the unit’s timestamp, from read_with_timestamp, as a row of trial-…-frames.csv. WavWriter reads the microphone through a window contract at 48 kHz mono and appends each block to a file with Python’s wave module, after logging the first block’s timestamp_ns.
Mode x refuses a file that already exists, so nothing can ever overwrite a trial.
Run a trial
Section titled “Run a trial”From the project folder on the rig:
tatolab play # starts a trialtatolab stop # ends itEach play starts every node fresh, so each trial writes a new set of files, named by when it started. A stop ends the trial and closes its files, and the project stays stopped, across the runtime’s restarts too, until the next play. If the runtime restarts mid-trial, the project opens again playing, and a new set of files starts; the trial’s earlier files keep what was written. Copy each trial’s files off when it ends.
While a trial runs, anyone on the machine can watch it without touching the recording: open the camera’s or the detector’s output in Tato Studio’s Node visualizer, or ask an agent what the logs say. To watch from elsewhere, send the encoder’s output to a relay; see Share between streams.
Lining sources up
Section titled “Lining sources up”A shared clock makes lining up a matter of measuring offsets, not reconciling clocks. Each stamp is taken where the data reaches the machine: a USB camera’s frame when the driver receives it, after exposure and transfer; a UDP reading when the node writes it. So each device has its own delay:
- Measure each device’s delay once per rig, with an event every device sees: an LED flash with a click, say, or a pulse your instrument also records. There’s no hardware sync input.
- The video’s frames are listed with their stamps in
trial-…-frames.csv, in the order they’re in the.h264file, so placing a CSV row in the video is a lookup. The.h264file itself holds no timestamps. - The stamps are on the stream’s clock, not wall-clock time. If you need wall-clock time, log it once at the start of a trial next to a
ctx.timereading, and convert.
Rows from the two inputs arrive in whatever order the nodes produce them, so sort by timestamp first. With pandas:
import sys
import pandas as pd
trial = pd.read_csv(sys.argv[1]).sort_values("timestamp_ns")trial["seconds"] = (trial["timestamp_ns"] - trial["timestamp_ns"].iloc[0]) / 1e9motion = trial[trial["source"] == "motion"]print(motion.describe())Checking a record is complete
Section titled “Checking a record is complete”tatolab graph counts the messages each input dropped because it fell behind, but zero dropped messages doesn’t prove a record is complete. It doesn’t count frames a newest input passed over (as MotionDetector does, by design), frames the camera or USB bus lost, or datagrams lost on the network. To show a record is complete:
- check the recorded timestamps for gaps longer than one frame or one audio block;
- read anything you analyze per frame with an
orderedinput; - put a sequence number in your instrument’s datagrams, and check it in the CSV.
Today’s limits
Section titled “Today’s limits”- One machine’s clock. Timestamps from different machines aren’t on one clock.
- Cameras the operating system sees. On Linux,
CameraSourcereads uncompressed video only, and has no exposure, gain or frame-rate settings. Scientific cameras that need a vendor SDK need a source node around the SDK’s Python binding. - The microphone opens at the device’s default rate. A window contract converts what it delivers; high-rate or ultrasonic work needs a source node that opens the device itself.
- Not hard real-time. Tato doesn’t guarantee deadlines for closed-loop control.
Related guides
Section titled “Related guides”- Write a node: sources for your instruments.
- Audio: audio blocks and windows.
- Inspect a running stream: what
tatolab graphshows during a run.