Proposal: feature negotiation between two labstream peers¶
Status: proposal. The header, the seq feature, and the resume
feature are implemented on main. The dgram section is a spec with no
code. The other features are not implemented.
docs/roadmap.md gives the order of the features. SPEC.md gets a section
for a feature only after the feature is accepted.
The purpose¶
Some improvements need a change to the data channel. Examples are sequence numbers that make sample loss visible, and a shared-memory transport for two processes on one machine. liblsl does not know these changes.
This page defines how a labstream inlet and a labstream outlet agree to use such a feature. The agreement must leave every other pair unchanged:
| Outlet | Inlet | Result |
|---|---|---|
| liblsl | liblsl | plain LSL, as today |
| liblsl | labstream | plain LSL |
| labstream | liblsl | plain LSL |
| labstream 0.1.2 or earlier | labstream | plain LSL |
| labstream | labstream | plain LSL, plus each feature that both ends accept |
What liblsl does with an extra header¶
These facts come from conformance/liblsl/ at e651023c.
- The feed server reads each request header line, and acts only on the keys
that it knows. An unknown key has no effect
(
src/tcp_server.cpp:605-633). - The feed client reads each answer header line the same way, and acts only
on the keys that it knows (
src/data_receiver.cpp:215-253). - Both sides cut a header line at the first
;, and convert the line to lowercase before they compare the key (src/tcp_server.cpp:610-613,src/data_receiver.cpp:220-223). - Both sides read a header line into a buffer of 16384 bytes
(
src/tcp_server.cpp:604,src/data_receiver.cpp:193). - The labstream parser cuts and converts the same way
(
crates/labstream-proto/src/header.rs:103-107).
As a result, a liblsl outlet ignores an extra request header, and a liblsl
inlet ignores an extra answer header. Item 3 limits the syntax of the header.
A value must not contain ;, and a value must not depend on letter case.
The header¶
The request¶
A labstream inlet adds one header line to its feed request:
The name of the header is Labstream-Features. This name is final. A later
version of labstream must not change it, because peers of different versions
must agree on it.
The value is a list of tokens with one space between two tokens. Each token has this form:
token = name "/" version [ "=" param ]
name = 1*( a-z / 0-9 / "-" )
version = 1*( 0-9 )
param = 1*( 0-9 / a-f )
A parameter is hexadecimal, because the header line loses its letter case.
The whole line must stay below 16384 bytes. An inlet can offer more than one
version of a feature, for example seq/1 seq/2.
The answer¶
A labstream outlet that reads the request header adds one line to its answer:
The answer holds only tokens whose name and version come from the request.
For each name, it holds at most one version. A feature can define a
parameter for its answer token. The resume section gives an example.
The rules¶
- An inlet sends the request header only when it supports one or more features.
- An outlet sends the answer header only when the request held one.
- An outlet ignores a token that it does not know, or that does not match the syntax.
- An inlet ignores an answer token that it did not offer.
- A feature is on only when the inlet offered it and the outlet answered it.
- If the answer has no
Labstream-Featuresline, no feature is on. A liblsl outlet and an older labstream outlet give this result. - The configuration key
labstream.Featureslists the features that this process can use, for example{seq}. The default lists every feature that the library has, except a feature that its section names as off by default (dgram). An inlet offers only the listed features, and an outlet answers only the listed features. The value{}turns every feature off. liblsl does not read this key.
Where the framing changes¶
After the answer headers, the outlet sends two test pattern samples (SPEC.md 6). These two samples always use the plain framing of SPEC.md 7. The inlet compares them exactly as today.
A feature can change the framing only from the first byte after the second test pattern sample. Thus the test pattern stays a check of the codec, and a fault in a feature cannot hide a fault in the codec.
The scope of an agreement¶
An agreement holds for one connection. A recovery opens a new connection with a new request, so the set of features can change. An outlet that restarts as a liblsl program gives an example.
The inlet must report the features of the current connection, and must show when the set changes. This works the same way as the clock reset after a recovery. The API names are an open question.
The first features¶
Each feature below gets its own section and its own conformance checks before any code. The text here gives only the requirements that affect the negotiation.
seq: sequence numbers¶
Status: implemented on main
(crates/labstream-proto/src/seq.rs). The token is seq/1.
The purpose¶
LSL has no sign of a lost sample (SPEC.md 8.7). An application can only
guess a loss from a gap in the timestamps. seq gives each sample a number,
so the inlet can count the samples that it did not receive.
The numbers¶
- The outlet gives each pushed sample the next number of one counter. The counter starts at 0 when the outlet opens.
- One counter serves the whole outlet, not one counter for each connection. A sample that the outlet pushes with no consumer also takes a number.
- The two real causes of loss are a full consumer queue in the outlet (SPEC.md 8.7) and the gap between a lost connection and the next one. A counter for each connection starts again after a recovery, so it shows neither cause. That is the reason for rule 2.
The record¶
When seq/1 is on, a numbering record can stand between two samples. It
has 9 bytes:
- The tag values 1 and 2 start a sample (
src/sample.h:19-20, SPEC.md 7.1). The tag0xFEis not a sample tag, so a reader can tell a record from a sample by its first byte. - The number is always little-endian. The
Byte-Orderof the connection does not apply to it. - On each connection, the first record comes directly after the second test pattern sample. The outlet writes it at once, before any sample, with the number that the next sample will get. Each connection thus starts with an absolute number, and a gap before the connection shows at once, also on a stream that sends no more samples.
- After that, the outlet writes a record only before a sample whose number is not one more than the number of the sample before it. A connection with no loss carries one record and no more.
- A record is not a sample. It does not count toward
Max-Chunk-Length. - A record that is cut at the end of a read is not an error. The reader waits for the rest of the bytes, as for a cut sample.
The count¶
The inlet keeps the number that it expects next.
- The first record after the inlet opens sets the expected number, and counts no loss. The inlet has no number from before that point.
- A later record with a number above the expected number adds the difference to the count of lost samples.
- A later record with a number below the expected number counts no loss. The inlet adds one to a separate count of numbers that went back, and takes the new number. The arithmetic must not underflow.
- Each sample adds one to the expected number.
- A recovery to the same outlet (the same
uid) keeps the expected number. The first record of the new connection then shows the gap. Live test:a_gap_shows_at_once_on_a_quiet_stream. - A recovery to a new outlet (a new
uid) starts again at rule 1, because the new outlet has a new counter. Live test:a_new_outlet_starts_a_new_count.
What the inlet reports¶
Inlet::samples_lost()inlabstream-netandInlet::lost()inlabstreamgive the count of lost samples since the inlet opened.- The value is
Nonewhen the current connection does not useseq. A liblsl outlet gives this result.Nonemeans "unknown". It does not mean "no loss". - Version 1 gives a count only. It does not give the position of each gap. An application that must place a gap still uses the timestamps.
- The inlet queue also drops the oldest sample when the application reads
too slowly. This drop happens after the count, so
seqdoes not see it.Inlet::samples_dropped()inlabstream-netandInlet::dropped()inlabstreamreport it, as before. The total loss is the sum of the two values.
resume: send the samples of a dropout again¶
Status: implemented on main. The token is resume/1. It is on by
default: labstream.Features is {seq, resume}. docs/roadmap.md gives
the success criterion.
The purpose¶
A connection can end while the outlet stays alive. Examples are a cable
pull, a Wi-Fi dropout, or a reset of a switch. The inlet then connects again
to the same outlet. Each sample that the outlet pushed between the two
connections is lost. seq counts this loss. resume prevents it.
What liblsl does¶
These facts come from conformance/liblsl/ at e651023c.
- The outlet makes a new consumer queue for each feed connection, after
the headers (
src/tcp_server.cpp:746). - A new consumer queue is empty. Its constructor registers it with the send
buffer (
src/consumer_queue.cpp:10-20). - A push goes only to the queues that are registered at that time
(
src/send_buffer.cpp:20-23). - The destructor of a consumer queue removes it from the send buffer
(
src/consumer_queue.cpp:22-24).
Thus no queue holds a sample that the outlet pushes between the end of one connection and the start of the next. liblsl has no history for each outlet.
The scope¶
resumecovers a lost connection to a live outlet. The outlet has the sameuidbefore and after the dropout.resumedoes not cover a restart of the outlet. A liblsl outlet gets a newuidwhen it starts (src/tcp_server.cpp:329). A labstream outlet makes a newuidwhen the description has none (crates/labstream-net/src/outlet.rs:142-143).- A feed request with a wrong
uidgets404 Not found(src/tcp_server.cpp:585-588). Thus a resume request cannot reach a different outlet. - An application can start a new labstream outlet with an old
uid. A relay or a replay of a recording can do this. The new outlet has a new epoch, so negotiation rule 8 detects the new run.
The rules for the negotiation¶
resume/1is on only whenseq/1is also on for the same connection. The numbers ofseqidentify the samples to send again.- Each outlet makes an epoch when it opens: 64 random bits from the
random source of the operating system (
random_bytesincrates/labstream-net/src/lib.rs). The epoch identifies one run of the outlet. A new outlet with an olduidgets a new epoch. - The parameter of
resume/1has two parts with no separator: the epoch in exactly 16 hexadecimal digits, then a sample number in 1 to 16 hexadecimal digits. Example:resume/1=9c3e51a0d2b7f4e81f4a0gives the epoch9c3e51a0d2b7f4e8and the number1f4a0. A parameter thus has 17 to 32 digits, and the number always fits in 64 bits. - On the first connection, the inlet offers
resume/1with no parameter. - On a recovery to the same
uid, the inlet offersresume/1=<epoch><R>. The epoch comes from the last answer.Ris the next number that theseqcount expects. Example:Labstream-Features: seq/1 resume/1=9c3e51a0d2b7f4e81f4a0. - If the inlet has no epoch, or the
seqcount has no expected number, it offersresume/1with no parameter. A recovery to a newuidalso offers no parameter (seqcount rule 6). - The outlet answers
resume/1=<epoch><N>. The epoch is its own epoch.Nis the number of the first live sample of the connection. The answer always holds both parts, also for an offer with no parameter. - If the inlet knows an epoch, and the answer gives a different epoch,
the outlet is a new run. The inlet then resets the
seqcount (seqcount rule 6), the timestamp deducer, and the clock offset, as for a newuid. If the inlet knows no epoch, it cannot see a new run, and it keeps its state, as withseq/1only. The inlet keeps the epoch of each answer for the next recovery. - The outlet ignores a
resume/1token with a parameter of fewer than 17 or more than 32 digits. If the offer holds more than oneresume/1token, the outlet ignores all of them. The connection then has noresume, andseqcan stay on. - If the answer holds
resume/1with no parameter, or with a parameter that rule 3 does not allow, the inlet setsresumeoff for that connection. - A blocking outlet (
transp_sync_blocking) has no queue and no history. It does not answerresume/1. - Today
answer()incrates/labstream-proto/src/features.rsignores each offered token with a parameter, and the answer copies the offered token. Forresume, the outlet accepts a parameter, and the answer holds a different parameter.agreed()already compares only the name and the version. The other features keep the current rules.
The history¶
- The outlet keeps one history for the whole outlet, not one history for
each connection. The history holds the last samples, with their
seqnumbers, in the order of the pushes. - The history also holds a sample that the outlet pushes with no consumer. The dropout is the time with no consumer.
- The outlet starts the history when the first consumer agrees to
resume/1. Before that point, the history costs nothing. An outlet that serves only liblsl inlets never keeps a history. The history then stays until the outlet closes. - Two limits set the size of the history. The outlet removes the oldest sample when it reaches a limit:
labstream.ResumeSeconds: the time of samples at the nominal rate. The default is 30 s. A stream with an irregular rate uses the memory limit only. The value 0 turns the history off, and the outlet does not answerresume/1.labstream.ResumeMemory: the memory in MiB. The default is 64 MiB.- The memory of one sample is 16 bytes (the timestamp and the number),
plus 32 bytes for each channel (the size of a
Value), plus the bytes of each string value. Thus a marker stream with long strings reaches the memory limit before the time limit. - Each outlet has its own history. A process with 10 outlets that each
reach the memory limit holds 640 MiB. An application with many outlets
must set a lower
labstream.ResumeMemory. - The default of 30 s covers a cut of 10 s. On Linux, the keepalive of
labstream ends a half-open connection after 6 s
(
crates/labstream-net/src/keepalive.rs:29). The inlet then tries to connect again until the link works. In the lossy-link benchmark ofdocs/roadmap.md, step 0, a cut of 10 s gave a gap of about 11.8 s. The first default of 10 s lost the oldest samples of that gap, so the user set the default to 30 s on 2026-11-21. - The liblsl watchdog waits 15 s by default (
src/api_config.cpp:303). A dropout that only the watchdog detects is longer than the default history. Theseqcount then shows the samples that the history did not hold. - At 4000 Hz x 64 channels, one second of history takes about 8 MB, so
64 MiB holds about 8 s. At this load, the memory limit acts before the
time limit. At 512 Hz x 8 channels, 30 s takes about 4.2 MB, and the
time limit acts first. The flat sample store of
docs/roadmap.md(the flat typed API step) decreases the cost of each sample by about 8 times.
The resend¶
The outlet reads the epoch and the number R from the token. Let O be
the oldest number in the history, and N the number that the next push
gets.
- The outlet registers the new consumer queue before it writes the answer
headers, because the answer holds
N. The registration is one step under the lock of the fanout. The queue gets each live sample fromN. liblsl registers the queue later (src/tcp_server.cpp:746). A peer cannot see this difference. - If the epoch is the epoch of the outlet, and
O <= R < N, the connection sends the history samples fromRtoN - 1. Then it sends the samples of the queue. IfR = N, there is nothing to send again. - If
R < O, the resend starts atO. The firstseqrecord givesO. The inlet countsO - Rlost samples, byseqcount rule 2. - If
R > N, or the epoch is different, or the offer has no parameter, or the history is empty, the outlet sends no history. The firstseqrecord givesN. - The history holds numbers below
N, and the queue holds numbers fromN. Thus no number repeats, and no number belowRgoes to the inlet. - The connection reads the history in blocks of at most 256 samples. It
takes the lock of the history once for each block. A push thus waits
for at most the copy of one block, not for the whole resend. A copy of
one sample at 64 channels took about 1.9 us in a measurement on the
branch
perf/quick-wins. Thus one block takes about 0.5 ms. - The history can remove samples during a resend, because of its limits.
If the next number is no longer in the history, the connection
continues at the oldest number. The
seqrecord before that sample shows the gap. - The queue keeps its size from
Max-Buffer-Length. The live samples wait in the queue during the resend. If the queue is full, it drops the oldest samples, as in SPEC.md 8.7. Theseqrecord before the next sample shows this drop as a gap. - A resent sample keeps its original timestamp. The next section gives the rules.
The framing does not change. The seq record and the sample encoding of
SPEC.md 7 carry the resend.
The timestamps of a resend¶
An outlet sends a chunk with one timestamp. Only the first sample of the
chunk carries timestamp bytes. Each later sample carries the deduced tag
(SPEC.md 9.2, chunk_timestamps in crates/labstream-net/src/outlet.rs).
The inlet calculates a deduced timestamp from the sample before it
(SPEC.md 8.1). A resend can start in the middle of a chunk. The inlet then
has no correct sample before the first resent sample.
- The history holds a full timestamp for each sample. It holds no deduced tag.
- The fanout calculates the full timestamp under its lock, in the order of
the
seqnumbers. It usesTimestampDeducerincrates/labstream-wire/src/lib.rs. The inlet uses the same code, so the two results are equal bit for bit. - Each push path goes through the fanout:
Outlet::push,Outlet::push_many, and the chunk functions of the C API, which make their own deduced tags (crates/labstream-capi/src/lib.rs:1301). - One deducer serves the whole outlet. It starts when the outlet opens, as
the
seqcounter does. It also runs before the history starts (history rule 3). Otherwise a history that starts in the middle of a chunk holds wrong timestamps. The cost is one addition for each sample. A blocking outlet has no history and needs no deducer. - When
resume/1is on, the connection writes the full timestamp (tag 2 of SPEC.md 7.1) for the first sample of the connection, and for each sample whose number is not one more than the number before it. A drop in the queue, or a sample that leaves the history during a resend, gives such a gap. Each resent sample also carries its full timestamp. The change from the history to the queue is not a gap when no number is missing, because the deduced timestamp is then correct. - Each other sample keeps the tag of its push. A connection with no gap
carries the same bytes as with
seq/1only. - Thus a deduced timestamp always follows the sample with the number
before it. A connection with
seq/1only can start in the middle of a chunk, and then gets wrong deduced timestamps until the next chunk (SPEC.md 8.4). Withresume/1, this fault does not occur.
The clock after a recovery¶
- A resend occurs only on a recovery to the same
uidwith the same epoch. On this path, the inlet keeps its clock offset, its post-processor, and its timestamp deducer (crates/labstream-net/src/inlet.rs:756-771). - The outlet is the same process, with the same clock. Thus the resent samples get the same clock offset as the live samples.
- With the dejitter option, the resent samples close the gap in the
count of samples. The count of the dejitter filter then stays correct
(
samples_since_t0_++insrc/time_postprocessor.cpp:119). - A different epoch resets the clock offset (negotiation rule 8). The resent samples of a new run do not exist, so no resent sample gets the offset of a different process.
What the inlet reports¶
Inlet::lost()counts only the samples that the history did not hold.Inlet::resent()inlabstream, andInlet::samples_resent()inlabstream-net, give the count of samples that came from a history since the inlet opened. A sample came from the history when its number is below theNof the answer.- The value is
Nonewhen the current connection does not useresume. - The C API gets two functions, one for the lost count and one for the
resent count. Each returns a signed 64-bit value. The value -1 means
None. The names follow the names of the Rust API.
The conformance plan¶
- liblsl outlet with a parameter. Extend
oracle/headerprobe.pyto sendseq/1 resume/1=9c3e51a0d2b7f4e81f4a0. Make sure that the answer and the data bytes are the same as for a request with no header. - liblsl inlet. Make sure that a labstream outlet keeps no history when only liblsl inlets connect. A unit test reads the size of the history.
- Released labstream 0.1.2. Run it as a peer in both directions. Each run must give plain LSL.
- The
seqbuild of #12. Run it as a peer in both directions. It answersseq/1and does not answerresume/1. Make sure that the inlet counts the loss of a dropout and gets no resend. - The configuration.
labstream.Features = {resume}withoutseqgives no resume, on the inlet and on the outlet.labstream.ResumeSeconds = 0gives no answerresume/1. - The syntax. Unit tests send a parameter of 16 and of 33 digits, an
offer with two
resume/1tokens, and an answer with no parameter. Each case must give a connection withseqand noresume. - The resend rules. Write a unit test for each case of the resend:
Rin the history,R = N,Rbelow the history,RaboveN, a different epoch, and an empty history. One more test sends a resend that is longer thanMax-Buffer-Length. One more test removes history samples during a resend. - The timestamps. A unit test starts a resend in the middle of a chunk. Each resent sample must carry tag 2, and each timestamp must be equal bit for bit to the timestamp that an inlet with no dropout calculates.
- A live dropout. The outlet ends each consumer connection, and pushes
for 3 s. The inlet must get each sample one time, in order, and
Inlet::lost()must give 0. Run at 512 Hz x 8 channels and at 4000 Hz x 64 channels. The test must fail withresumeoff. The outlet pushes chunks of more than one sample. A second inlet with no dropout must get the same values and the same timestamps, bit for bit, with all post-processing options on. Run the same test on a marker stream with string values and an irregular rate. - A reused
uid. Close an outlet, and open a new outlet with the sameuid. The inlet must get no resend, must reset itsseqcount, and must count no false loss. - A dropout longer than the history. Set
labstream.ResumeSecondsto 1. The loss count must be exact. - The push delay. At 4000 Hz x 64 channels, measure the longest push during a resend of 8 s. It must stay below 2 ms.
- The interop matrix.
oracle/interop.pymust give the same result as before, withresumeon. - Latency and CPU. Run
latency.pywithresumeon against theseqbuild. The history adds one copy for each push.
The status of the conformance plan¶
The status on 2026-11-20, at the merge of feat/resume into main. The
live tests are in crates/labstream-net/tests/, in the files that start
with resume_.
- Done.
oracle/headerprobe.pypasses for liblsl, labstream 0.1.2, theseqbuild, and theresumebuild. Theresumebuild answersresume/1with its own epoch andseq/1. Run the probe withoutLD_LIBRARY_PATH. Otherwise each probe program loads liblsl. - Done.
a_plain_request_starts_no_history: a request with no header, which is the request of liblsl, and an offer ofseq/1only, start no history. An offer ofresume/1starts it. - Done.
oracle/interop.pywith 0.1.2 as the second peer: 28 of 28 cells, and 24 of 24 cells with chunks of 16 and in the blocking mode.oracle/resumeprobe.pyagainst a 0.1.2 outlet: the inlet loses the dropout, and both counts are unknown. - Done. The same interop runs with the
seqbuild pass. Against aseqoutlet,oracle/resumeprobe.pyshows 1832 missing samples and a loss count of 1832. The resend count is unknown. - Done.
resume_config_no_seq.rsandresume_config_no_history.rs. Each runs as its own process, because the library reads its configuration one time. - Done. The unit tests in
features.rs. - Done, with one change. The resend does not go through the consumer
queue, so
Max-Buffer-Lengthdoes not limit it. The live samples wait in the queue during the resend. A unit test drops samples from that queue, and one more test removes history samples during a resend. - Done. The unit tests in
outlet.rscompare each timestamp bit for bit. - Done, with one change. Three live tests cut the connection for 3 s:
512 Hz x 8 channels, 4000 Hz x 64 channels, and a marker stream. Each
sample arrives once, in order, with the raw timestamp of a second inlet,
bit for bit. With
labstream.Features = {seq}, these tests fail. With post-processing on, two inlets do not agree bit for bit, because each inlet measures its own clock offset. The test with post-processing thus checks the time axis of one inlet: it never goes back, and no step across the dropout is more than two sample periods. - Done.
a_new_outlet_with_an_old_uid_gives_no_resend_and_no_false_loss. The new outlet has pushed 300 samples, and the inlet expects 100. The inlet gets only the live samples, with no false loss. - Done.
resume_short_history.rs, withResumeSeconds = 1: a 3 s dropout at 512 Hz gave 1448 missing samples, a loss count of 1448, and 512 resent samples. - Done, as a measurement.
the_longest_push_during_a_long_resend_stays_shortis an ignored test. Run it withcargo test --release -p labstream-net --test resume_live -- --ignored. A resend of about 7.6 s at 4000 Hz x 64 channels gave a longest push of 0.60, 0.62, and 0.81 ms in three runs. The limit is 2 ms. A resend of 8 s does not fit in the default memory limit at this load, so the cut is 7 s. - Done. Against liblsl: 28 of 28 cells, 24 of 24 with chunks, and 24 of 24 in the blocking mode.
- Done. The first build added about 80 µs to the median at
4000 Hz x 64 channels, chunk 32. The fix gives the queues each sample
before the history copy. The latency is now in the range of the
seqbuild. The outlet CPU is about 1.5 points higher.docs/latency.mdgives the runs.
Open questions¶
- The final names of the Rust API and the C API for the resend count.
- An API that marks each resent sample. Version 1 gives a count only. The
health API step of
docs/roadmap.mdcan add gap positions and resend positions. - A request for the history on the first connection. A new viewer can then show the last seconds at once. Version 1 sends a history only after a recovery.
dgram: samples over UDP¶
Status: spec approved by the user on 2026-11-21. Implemented on main,
and on by default (docs/roadmap.md, decision 13). The token is dgram/1.
docs/roadmap.md, step 5, gives the decision for plain UDP (decision 12).
Change of 2026-11-21. The first version missed two targets. At 30 %
and 50 % loss, the resends went on TCP, and TCP at that loss waits
seconds. On a clean link of 1 Mbit/s, the fixed copies made the p99 worse
than TCP. The user asked for a fix of both. The resend of a small gap now
goes on UDP (the feedback datagram), and the count of copies follows the
measured loss. dgram/1 is not released, and no liblsl peer negotiates
it, so the token stays dgram/1 and the wire format changes in place.
The purpose¶
TCP gives each byte in order. When the network loses one segment, each
later sample waits until TCP sends the segment again. On a link with 20 ms
delay and 1 % loss, the p99 latency of both libraries is about 70 ms, and
the longest wait is up to 118 ms (docs/latency.md, section "A slow,
lossy, or cut link"). Wi-Fi loses packets in this way.
dgram sends the samples in UDP datagrams. A lost datagram stops only its
own samples. The next datagram carries copies of them, so the inlet repairs
most losses after one datagram. The TCP connection stays open, and carries
everything else.
What liblsl does¶
These facts come from conformance/liblsl/ at e651023c.
- The data channel of liblsl is TCP only. The UDP sockets of liblsl carry
discovery and the time probes, not samples (
src/udp_server.cpp). - A liblsl peer ignores the
Labstream-Featuresheader (the section "What liblsl does with an extra header" above). Thus a liblsl peer never usesdgram.
The scope¶
dgramchanges only the path of the samples from the outlet to the inlet. The headers, the test pattern, theseqrecords, and the end of the stream stay on TCP.dgramneedsseq/1andresume/1on the same connection. Theseqnumbers put the samples in order. Theresumehistory gives a sample again when each copy of it is lost.dgramdoes not cover a change of address. If the address of a peer changes, the TCP connection ends, andresume/1fills the gap.docs/roadmap.mdhas connection migration as an open question.dgramdoes not encrypt. Step 14 ofdocs/roadmap.mdcovers encryption.dgramis on by default after the two-machine Wi-Fi test of 2026-11-21 (docs/roadmap.md, decision 13):labstream.Featuresis{seq, resume, dgram}. Set{seq, resume}to keep samples on TCP.
The rules for the negotiation¶
- The inlet offers
dgram/1with no parameter. - The outlet answers
dgram/1only if all of these are true. Otherwise it leavesdgram/1out. - The answer also holds
seq/1andresume/1. - The outlet is not a blocking outlet.
- The format is a string, or one sample takes at most 400 bytes. A
datagram then holds at least 3 samples, so the copies can work. A
stream with larger samples gets no gain from
dgram, and stays on TCP. - The outlet opens one UDP socket for each connection. The socket uses
the address family of the TCP connection. Its port is in the range of
ports.BasePortandports.PortRange, as the data port is, so that a firewall rule for LSL covers it. - The outlet answers
dgram/1=<port><cookie>. The port is the UDP port of the outlet, in exactly 4 hexadecimal digits. The cookie is 64 random bits, in exactly 16 hexadecimal digits. Example:dgram/1=c35b9f2e81d04a7713c6. - The inlet ignores an answer
dgram/1with no parameter, or with a parameter of other than 20 digits.dgramis then off. - The outlet ignores an offer
dgram/1with a parameter.
The hello¶
The outlet sends no datagram before it knows the address of the inlet. The inlet sends the first datagram, because a firewall or a NAT on the side of the inlet then lets the answers through.
- After the test pattern, the inlet sends a hello datagram to the UDP port of the outlet, at the address of the TCP connection:
- The inlet sends the hello again each 100 ms, until the first data datagram arrives, or for 1 s.
- The outlet accepts the first hello with the correct cookie from the address of the TCP peer. The source address and port of that hello become the target of the data datagrams. The outlet ignores each other hello.
- Until the outlet accepts a hello, the samples go on TCP, as with
seqonly. If no correct hello arrives in 1 s, the connection stays on TCP. The inlet then also stops its hellos.
The change of path¶
- When the outlet accepts the hello, it writes a path record on TCP:
u8 tag 0xFD
u8 path 1 (UDP) or 0 (TCP)
u64 number little-endian, the number of the first sample on that path
- Each sample below that number goes on the old path. Each sample from
that number goes on the new path, except a sample that does not fit in
one datagram. Such a sample goes on TCP, with its
seqrecord. - The tag
0xFDis not a sample tag, as0xFEis not. The record does not count towardMax-Chunk-Length. - A path record with
path = 0gives the change back to TCP. The fallback section gives the cases.
The data datagram¶
u8 type 2 (data)
u64 cookie little-endian, from the answer
u64 first little-endian, the number of the first sample in the datagram
u16 count little-endian, the count of samples in the datagram
u32 serial little-endian, the number of the datagram
... the samples, in the encoding of SPEC.md 7, one after another
- The samples of one datagram have consecutive numbers, from
first. Each data datagram of a connection gets the nextserial, from 0: a datagram with new samples, a repeat datagram, and a resend datagram. The inlet measures the loss of datagrams from the gaps inserial. - Each sample carries its full timestamp (tag 2). A datagram can arrive
after a later one, or not at all, so the inlet cannot deduce a
timestamp from the sample before it. The history already holds the
full timestamps (
resumetimestamp rule 1). - The byte order of the samples is the byte order of the TCP connection.
- A datagram has at most 1200 bytes, the header included. This size passes most links with no fragmentation of IP.
- The inlet ignores a datagram with a wrong cookie, or from an address that is not the address of the outlet.
The idle datagram¶
A loss shows at the inlet only when a later datagram arrives. On a marker stream, the next marker can come minutes later. An idle datagram gives the inlet the next number when no sample follows:
u8 type 3 (idle)
u64 cookie little-endian, from the answer
u64 next little-endian, the number that the next sample will get
- After the last data datagram, the outlet sends the repeat datagram of the copies rule 3 at 5 ms, or an idle datagram if it has no copy to send. It then sends idle datagrams at 25 ms, 100 ms, and 250 ms. A lost last datagram thus shows at the inlet soon, also at heavy loss. While no sample follows, the outlet then sends an idle datagram each 1 s. These datagrams also keep the state of a NAT or a firewall open.
- When
nextis above the last number that the inlet has, the inlet has a gap, and the resend rules apply.
The copies¶
- The outlet first puts the new samples of a push into datagrams.
- Then it fills the free space of each datagram with copies of the samples
just before the new samples, newest first, so that the samples stay
consecutive. Each sample goes into at most
1 + Cdatagrams: once as new, and as a copy in at mostClater datagrams.Cis the count of copies of rule 6. - If the outlet sends no data datagram for 5 ms after a data datagram, it sends one repeat datagram: copies of the last samples, with no new sample. A push of a chunk, and the last marker before a quiet time, thus get their copies after 5 ms, not at the next push.
- Example: at 512 Hz x 8 channels of
float32, a sample takes 41 bytes. With one sample for each push, the next datagram comes about 2 ms later and carries the copies. With chunks of 16, the repeat datagram carries them after 5 ms. - At 4000 Hz x 64 channels with chunks of 32, a sample takes 265 bytes, and 4 samples fill a datagram. The new samples fill most datagrams, and the repeat datagram holds only the last 4 samples. A lost datagram then often needs a resend.
- The count of copies. Copies cost bytes. On a link of 1 Mbit/s with
no loss, 2 copies made each datagram of a 512 Hz x 8 channel stream
about 60 % longer than the TCP segment, and the p99 went from 1.1 ms
to 2.0 ms. Thus
Cfollows the loss of datagrams that the inlet measures (the feedback datagram):
| measured loss | C |
|---|---|
| 0 | 0 |
| up to 2 % | 2 |
| up to 10 % | 3 |
| up to 25 % | 4 |
| up to 40 % | 6 |
| more than 40 % | 8 |
Cstarts at 0.- A higher
Capplies at once. - A lower
Capplies only after each report for 5 s gave it, and after the outlet sent 1000 datagrams. - With
C = 0, the repeat datagram has no copy, and the outlet sends the idle datagram of the idle rule 1 in its place.
With C copies, a raw loss p leaves about p to the power C + 1
of the samples for a resend: 0.02 % at 30 % with C = 6, and 0.2 % at
50 % with C = 8.
The resend¶
- The inlet keeps the number that it expects next,
E. It gives the application each sample in the order of the numbers, as with TCP. - A sample above
Ewaits in a buffer. A copy of a sample that the inlet already has goes away. - A gap is a run of missing numbers below the highest number that the inlet knows of. A gap of at most 64 samples is a small gap. A larger gap comes from a cut, not from a lost datagram.
- A small gap goes on UDP. If a small gap stays for 2 datagram
periods, or for 10 ms if that is longer, the inlet puts it in a
feedback datagram (the next section). Each small gap goes in, not only
the gap at
E, so the gaps get their resends in parallel. The inlet sends the gap again eachmax(10 ms, 1.5 x R)until the gap closes.Ris the round trip of a resend: the time from the first request of a gap to the arrival of a sample of it.Rstarts at 50 ms. - The outlet sends the samples of a small gap from the
resumehistory, in data datagrams on UDP, with no copies. IfCis 3 or more, it sends each such datagram twice. It sends at most 256 samples for one feedback datagram, and it does not send a sample again within 10 ms. A sample that the history no longer holds gets no resend. - The inlet gives up a small gap when it stood at
Eformax(1 s, 4 x R). The time counts from when the gap reachedE, so a gap behind a TCP resend first waits for that resend. At 30 % loss in each direction, a request and its answer both arrive in about half of the tries. 1 s holds about 15 tries, and leaves less than 1 gap in 10000 unfilled. On a slow link, a TCP resend after a cut can fill the queue of the link for seconds. The first rule, 1 s from when the gap first showed, then gave up a sample in 2 of 3 runs of the cut of 10 s at 1 Mbit/s. The inlet gives up a small gap only while datagrams still arrive (within 500 ms). After 1.5 s with no datagram, the link is in a cut, and the wait starts again when datagrams return. Without this rule, the inlet gave up a gap at the start of a cut before TCP closed, andresume/1asked past that sample. - A large gap goes on TCP. If a large gap at
Estays for the same wait, the inlet asks for it on TCP:
u8 tag 0xFC
u64 from little-endian, the first missing number
u32 count little-endian, the count of missing samples
- The outlet sends the samples of a TCP request from the
resumehistory on TCP, with theirseqrecords, as for a resend after a recovery. - If the history no longer holds a sample, the outlet sends the next one that it holds. The inlet counts the samples between as lost.
- The inlet gives up a large gap after 500 ms with no answer and no other data on TCP. Data on TCP shows that an answer can still be on the way, on a slow link. It counts the gap as lost, and gives the samples after it. A sample of the gap that arrives later goes away.
- A gap that an open TCP request covers gets no new request on TCP or on
UDP. Only a part beyond the request gets one. At the start of a
connection with a
resumeresend, the numbers of the resend count as requested. Without this rule, a reconnect on a slow link sent each part of the resend about 14 times, and the backlog ended the connection again.
The first version sent each resend on TCP, one gap at a time. At 30 % loss in each direction, TCP waits seconds for each lost segment, and the later gaps waited behind the first one. The runs lost about 3000 of 6144 samples.
The feedback datagram¶
The inlet sends it to the UDP port of the outlet, from the socket of its hellos:
u8 type 4 (feedback)
u64 cookie little-endian, from the answer
u32 loss little-endian, the measured loss of datagrams, in parts per
million, or 0xFFFFFFFF if the inlet has no measure yet
u8 gaps the count of gaps that follow, at most 64
... each gap: u64 from, then u32 count, little-endian
- The inlet measures the loss of datagrams from
serial. It counts the datagrams that arrived and the range of theirserialvalues in buckets of 100 ms, and adds the last 10 buckets. A gap inserialbetween two buckets does not count, so the time of a cut is no loss. - The inlet sends a feedback datagram each 100 ms while datagrams arrive, and also each time that a small gap is due for a request (resend rule 4).
- The outlet accepts a feedback datagram only with the correct cookie and from the address of the accepted hello. It ignores each other one.
- The outlet sets
Cfromloss(the copies, rule 6).
The count on two paths¶
The seq rules count one ordered byte stream. With dgram, samples
arrive on two paths, and a TCP resend can carry a number below the numbers
that UDP already gave.
- The inlet merges the two paths by number, before the count. The
seqcount rules then apply to the merged stream: each sample that the inlet gives to the application movesEby one. - A
seqrecord on TCP gives the number of the next sample on TCP only. It does not moveE, and it counts no loss by itself. - A loss counts only in three cases: resend rules 6, 9, and 10.
Inlet::lost()is thus the count of the numbers that the inlet never gave.
The fallback to TCP¶
A cut stops both paths, and a burst of Wi-Fi loss stops UDP for some milliseconds. Neither is a reason to leave UDP. A fallback is only for a UDP path that stays bad while data still arrives, or that stops while TCP works.
- Heavy loss. The inlet measures the loss after the copies and the resends: the samples that it gave up, in each window of 1 s. A window counts only if at least 10 datagrams arrived in it. If 3 windows in a row show more than 5 %, the inlet writes a path request on TCP. The first version counted the samples that it asked for. At 50 % loss that count is about 12 %, so the connection changed to TCP, and TCP at 50 % loss lost about 5350 of 6144 samples. The path request:
The outlet then writes a path record path = 0 with the number from,
and sends the samples from from on TCP, from the history and then
live.
2. A dead UDP path. On the UDP path, the outlet sends a datagram at
least each 1 s (the idle rule). If no datagram arrives for 3 s while
TCP still works, the inlet writes the same path request.
3. An error of the socket. If the outlet cannot send a datagram, it
writes a path record path = 0 itself.
4. The way back. 30 s after a fallback, the outlet tries UDP again: it
writes a path record path = 1 and sends on UDP. The address of the
inlet stays the address of the accepted hello. If the path is still
bad, rule 1 or 2 gives the next fallback.
A raw loss of 30 % or 50 % thus stays on UDP: the copies and the resends on UDP leave almost no sample to give up. TCP at such a loss is worse than UDP, so a fallback would only add loss. Rule 1 is for a UDP path that is much worse than TCP, for example a UDP rate limit in a firewall.
Keepalive on UDP¶
labstream ends a quiet TCP connection after about 5 s with no answer to its
keepalive probes, and after 6 s with data that the peer does not
acknowledge (crates/labstream-net/src/keepalive.rs). On UDP, the TCP
connection is quiet, so the probes run all the time. At 50 % loss in each
direction, a probe and its answer both arrive in a quarter of the tries,
and 3 failed probes in a row are frequent. Without the rules below, the
TCP connection broke in 2 of 3 runs at 50 % loss, and the resume resend
of the reconnect stalled on TCP: about 1100 samples lost in each.
- While the samples go on UDP, each side uses long timers on its TCP socket: the first probe after 30 s, a probe each 5 s, 6 probes, and an acknowledgement timeout of 60 s.
- The datagrams show that the peer is alive. The inlet gets a datagram at least each 1 s (the idle rule), and the outlet gets a feedback datagram each 100 ms.
- If a side gets no datagram of its peer for 3 s, or if the path changes to TCP, it uses the short timers again.
What the inlet reports¶
Inlet::lost()counts the samples that neither a copy nor a resend gave.Inlet::resent()counts the samples of aresumeresend, as before. It does not count a copy or a resend ofdgram.- The API that shows the path of the connection (UDP or TCP) is an open question.
The conformance plan¶
- liblsl and older peers.
oracle/headerprobe.pywithdgram/1in the offer: liblsl, 0.1.2, theseqbuild, and theresumebuild answer nodgram/1, and nothing else changes. - The negotiation. Unit tests:
dgram/1withoutseq/1orresume/1, a parameter of a wrong length, an offer with a parameter, a blocking outlet, and a stream with samples of more than 400 bytes. Each gives a connection with nodgram. A live test: the UDP port is in the range ofports.BasePortandports.PortRange. - The encoding. Unit tests: a data datagram reads back, a cut datagram is an error, and a datagram never has more than 1200 bytes.
- The copies. Unit tests: each sample goes into at most
1 + Cdatagrams, the samples of each datagram are consecutive, and one lost datagram of a 512 Hz x 8 channel stream costs no sample whenCis 2. The count of copies follows the table of the copies rule 6: it goes up at once, and down only after 5 s and 1000 datagrams. 4a. The repair at heavy loss. A unit test simulates the packer, the reorder buffer, and the feedback with a seeded random loss in each direction and a delay of 20 ms. At 30 % loss no sample is lost. At 50 % loss at most 0.1 % is lost. With the resend on TCP rules of the first version, the same simulation loses samples at 30 %. 4b. The watchdog. A live test withtuning.WatchdogTimeThresholdshorter than the run: a connection on UDP, with no byte on TCP, keeps its samples on UDP past the watchdog time. - The order and the count at the inlet. Unit tests with each pattern
of loss, repeat, and reorder on UDP, mixed with resends on TCP: the
inlet gives each sample once, in order, and
Inlet::lost()counts only the numbers that it never gave. A gap past the time limit counts as lost, and a late sample of that gap goes away. An idle datagram after a lost last datagram starts a resend. - The hello. Live tests: a wrong cookie gets no data. A hello from a different address gets no data. With no hello, the connection stays on TCP after 1 s, and loses no sample.
- The change of path. A live test: no sample is lost, and none arrives twice, at the change to UDP and at the change back to TCP.
- Large samples. A live test with string samples of 2000 bytes, mixed with small ones. The large ones go on TCP, and each sample arrives once, in order.
- Heavy loss and the fallback. In the lossy-link benchmark:
- a loss of 30 % in each direction keeps the connection on UDP, with no lost sample,
- a loss of 50 % in each direction keeps the connection on UDP, and loses much less than TCP: at most 0.1 % of the samples,
- the same two rules from the start of the run, before the
connection opens: the result of the connect is reported, for
dgramand for TCP, - after a fallback, the connection tries UDP again after 30 s,
- a UDP path that stops while TCP works (a rule that drops only UDP) changes the connection to TCP within 4 s, with no lost sample.
- The success criterion.
oracle/lossylink.pywithdgram/1on. The script needs options for the load and for a marker stream first.- At 512 Hz x 8 channels, chunk 1, with 20 ms delay and 1 % loss: the p99 is less than 35 ms, and no sample is lost.
- The same with chunks of 16, and on a marker stream with 200 markers each second: the p99 is less than 35 ms, and no sample is lost.
- At 4000 Hz x 64 channels, chunk 32, with 20 ms delay and 1 % loss: the p99 is no worse than with TCP, and no sample is lost.
- The rules
clean,delay, andrategive a p99 no worse than TCP, outside the range of the runs. - The cut of 3 s loses no sample, and the connection is still on UDP after the cut.
- The cut of 10 s loses no sample, and the longest wait is no longer than with TCP (about 11.9 s).
- The interop matrix.
oracle/interop.pygives the same result as before, withdgramon. - Latency and CPU on loopback.
oracle/latency.pywithdgramon against the build before it. The CPU of each side must not grow by more than 25 %. - Two machines on Wi-Fi. A manual test with an outlet and an inlet on
two machines, one on Wi-Fi, for 10 minutes. This test must pass before
dgramgoes on by default. - Windows and macOS. The tests of items 6 to 8 pass in CI on each platform.
The status of the conformance plan¶
The status on 2026-11-21, on the branch feat/dgram. docs/latency.md,
section "dgram/1 over a slow, lossy, or cut link", gives the runs.
- Done.
oracle/headerprobe.pyoffersdgram/1. liblsl, 0.1.2, and theseqbuild answer nodgram/1. Current labstream answersseq/1,resume/1, anddgram/1, and nothing else changes. - Done. The unit tests in
features.rs, anddgram_outlet_live.rsfor the port range. - Done. The unit tests in
dgram.rs. - Done. The unit tests of
PackerandCopyControlindgram.rs. 4a. Done. The simulation unit tests indgram.rscover 1 %, 30 %, and 50 % loss. 4b. Done.crates/labstream-net/tests/dgram_watchdog.rs. - Done. The unit tests of
Reorderindgram.rs, with loss, repeats, reorder on two paths, and cuts. - Partly done.
dgram_outlet_live.rs: a wrong cookie keeps the samples on TCP. A hello from a different address is not tested. - Done.
dgram_outlet_live.rsanddgram_live.rs: the change to UDP, a path request back to TCP, and a cut of 3 s, with each sample once. - Done. Both live files: string samples of 2000 bytes go on TCP, in order.
- Mostly met. A UDP path that stops changes to TCP after about 2.9 s
with no lost sample.
udpbackreturns to UDP after 30 s with no lost sample. At 30 % loss after 2 s,dgramloses no sample. At 50 % loss after 2 s, a traced 3-run batch lost0, 0, 0samples. One earlier 3-run batch lost6110, 0, 1(one run stalled after 34 samples). From the start, 30 % loss gave0, 0, 759lost ondgramagainstno connect, 4129, 5939on TCP. At 50 % from the start, discovery or handshake failed in most runs for every library. - Met. With 20 ms delay and 1 % loss, the p99 is 22.0 ms at chunk 1,
28.9 ms at chunk 16, and 20.9 ms for markers, with no lost sample. At
4000 Hz x 64 channels,
dgramloses none and TCP loses over 12000. At 1 Mbit/s,dgrammatches TCP (1.2 ms against 1.1 ms). The cuts of 3 s, 10 s, and 10 s at 1 Mbit/s lose no sample, andcut3stays on UDP. - Done.
oracle/interop.pywithdgramon passes 28 of 28 plain cells (plus 4 self-tests), 24 of 24 numeric chunk cells, and 24 of 24 numeric sync cells. - Partly met.
oracle/latency.pyon loopback gives lower p50 on every load, and equal or lower CPU on single-sample loads. Chunked loads exceed +25 % CPU on the inlet (0.8 % against 0.6 % at 512 Hz x 8, chunk 16, and 3.7 % against 2.3 % at 4000 Hz x 64, chunk 32). Outlet CPU at 4000 Hz x 64, chunk 32 is 6.6 % against 5.2 % (+27 %), because one chunk splits into 8 datagrams. - Done.
conformance/peer/src/bin/wifitest.rsran for 10 minutes in each mode (200 s each at 512 Hz x 8, 1000 Hz x 32, and 4000 Hz x 64 chunk 32) from Linux to Windows over Wi-Fi.dgramstayed on UDP for 100 % of each load with 0 lost samples, and cutp99-p50from 6817.6 ms to 21.9 ms at 1000 Hz x 32 and from 128.0 ms to 19.3 ms at 4000 Hz x 64 chunk 32 (docs/latency.md). The user then turneddgramon by default (docs/roadmap.md, decision 13). - Partly done. On Windows,
dgram_live(3 tests),dgram_outlet_live(7 tests), anddgram_watchdog(1 test) all pass. macOS waits until CI works again.
Open questions¶
- The API that shows the path of the connection, and the count of copies and resends that the inlet used.
- The size of 1200 bytes. A link with a larger MTU can take more samples in each datagram.
- A rate limit of the outlet. Version 1 sends at the rate of the application. The fallback rule 1 is the only reaction to loss.
select: channel and rate selection¶
A viewer on a slow link often needs a subset of channels, or a lower sample
rate, or both. With select/1, one consumer asks for a narrower view while
other consumers on the same outlet still receive the full stream.
- The inlet offers
select/1=<param>. The lowercase hexadecimal parameter holds: - 8 hex digits: integer decimation factor
D(u32big-endian,D >= 1) - 4 hex digits: channel count
K(u16big-endian,0= all channels) 4 * Khex digits: each 0-based channel index (u16big-endian)- The outlet checks that every index is in range and that
D > 1only runs on a numeric stream with a positive nominal rate. If valid, the outlet answers with the sameselect/1=<param>token. Aliblsloutlet ignores the header and sends the full stream. - The two test pattern samples after the headers use the full channel count. Selected framing starts at the first byte after the second test pattern sample.
- When
D == 1, each selected channel keeps the exact bits of the full stream.seq/1,resume/1, anddgram/1stay active, anddgram/1checks datagram fit against the selected channel count. - When
D > 1, the outlet applies a symmetric Type I linear-phase Hamming-windowed sinc low-pass FIR filter to each selected numeric channel and emits one sample for everyDinput samples: - Tap count:
N = min(4 * D + 1, 257)(odd, centerM = (N - 1) / 2) - Normalized cutoff:
fc = 0.45 / Dcycles per input sample - Window:
w[k] = 0.54 - 0.46 * cos(2 * pi * k / (N - 1)) - Normalized taps sum to
1.0(unit DC gain). Each output sample carries the timestamp of the center tap, with zero phase lag. Decimated sessions run over TCP withseq/1numbers on the decimated timeline and leaveresume/1anddgram/1off. - The inlet updates
info(),current_info(), andfullinfo()with the selected channel count, the selected nominal rate, and the selected<channel>entries under<desc><channels>.
comp: lossless wire compression¶
A wireless or slow link has less bandwidth than a cable. With comp/1, two
labstream peers compress numeric sample values bit for bit on TCP and on UDP
(dgram/1).
- Negotiation. For a numeric stream (not
Format::String), the inlet offerscomp/1with no parameter. A non-blocking labstream outlet answerscomp/1. Aliblslpeer ignores the header and uses plain LSL. Whenshm/1activates aftershm-ok, shared memory transfers raw bytes directly andcomp/1stays off. - Test pattern. The two test pattern samples always use plain LSL framing. Compression starts at the first byte after the second test pattern sample.
- Bit-exact channel transform. Each numeric channel value maps bijectively
to an unsigned integer of the channel width (identity for
Int8,Int16,Int32, andInt64, and an order-preserving IEEE-754 bijection forFloat32andDouble64that keeps-0.0,+0.0, subnormals, and NaN payloads exact). The encoder takes a wrapping first-order delta against the previous sample on the same channel, applies ZigZag sign folding, and writes an adaptive LSB-first Golomb-Rice code with a 15-zero escape to the raw width. Sample 0 never updates the delta EMA so DC offsets do not inflate sample 1. - TCP framing. On TCP, the outlet and inlet keep one per-channel state in lockstep. When compressed bytes plus 2 bytes are fewer than the raw channel bytes, the outlet writes one compressed sample record:
0xF9,u16payload length (little-endian), compressed payload (deduced timestamp).0xFA, 8-bytef64timestamp (connection byte order),u16payload length (little-endian), compressed payload (transmitted timestamp). When compression does not save bytes, the outlet writes a plain LSL sample (0x01or0x02) and both peers update the predictor state from that sample. Worst-case expansion on incompressible data is zero bytes.- UDP framing (
dgram/1). When bothdgram/1andcomp/1are active, the outlet packs consecutive samples into self-containedDATA_COMPdatagrams (type byte5, same 23-byte header asDATAtype2). The payload holds a flags byte, the raw little-endianf64timestamp of sample 0, sample 0 (raw or Rice-coded), and then for each later sample a 2nd-orderf64timestamp delta and all channel deltas. Each datagram decodes independently with no cross-datagram state. If plainDATAis smaller or equal, the outlet sendsDATA(type2). - Observability.
Inlet::is_compressedandInlet::compression_ratio(labstream-netandlabstream),InletHealth::{compressed, compression_ratio}, andlabstream_inlet_compressedpluslabstream_inlet_compression_ratio(labstream-capi) report active compression and the observed wire-to-raw byte ratio.
shm: shared memory on one machine¶
The hostname does not prove that the two processes share a machine. Two
machines can have the same name, and a container can have the name of its
host. Thus shm needs one more step after the headers:
- The inlet offers
shm/1. - The outlet makes a memory segment. It writes a random value into the
segment. It answers
shm/1=<segment id>. - The inlet opens the segment and reads the random value.
- The inlet writes one line on the TCP connection:
shm-ok <value>orshm-no. - If the value matches, the outlet sends the samples through the segment. Otherwise, or after 1 s with no line, the outlet sends the samples on TCP.
The outlet does not send data before step 5. The TCP connection stays open in both cases. It carries the end of the stream and the recovery.
The segment must allow access only by the user that owns the outlet.
Platform behavior:
- Linux:
shm_open(O_CREAT | O_EXCL | O_RDWR, 0o600)plusfchmod(0o600)andmmap(MAP_SHARED)under/ls-shm-<id>(24 bytes, within POSIX name limits). Once the inlet confirmsshm-ok, the outlet callsshm_unlinkat once so the entry leaves/dev/shmwhile the kernel holds the mapping until both processes exit. Cross-process wakeup usesSYS_futex(FUTEX_WAITandFUTEX_WAKEwithoutFUTEX_PRIVATE_FLAG) with predictive pre-wake on steady high-rate streams. - macOS and other Unix:
shm_open(0o600),ftruncate,mmap, andshm_unlink, with short spin and 50 us sleep backoff. - Windows:
CreateFileMappingWandOpenFileMappingWin the session-onlyLocal\ls-shm-<id>namespace withMapViewOfFile, paired with a named auto-resetCreateEventW/OpenEventW(Local\ls-ev-<id>) for wakeup.
A clock model with drift¶
Status: implemented on main (docs/roadmap.md, step 17).
A fit of offset and drift is a choice of the inlet alone. The outlet answers
the same time probes as today. Thus this feature needs no negotiation, and
it does not use this header. labstream_time::DriftModel fits a 64-burst
RTT-weighted linear model with outlier down-weighting from each burst midpoint
(t0 + t3) / 2. Opt-in flags::DRIFT (16, Post::DRIFT,
LABSTREAM_POST_DRIFT) evaluates the smooth offset for each sample timestamp
with no 2 s step, while default flags::CLOCKSYNC stays bit-exact with liblsl.
Device-delay metadata¶
Status: implemented on main (docs/roadmap.md, step 15).
Device-delay calibration needs no wire header. The measured delay goes into
<desc><synchronization><offset_mean> (with optional <offset_rms>,
<offset_median>, <offset_5_percentile>, and <offset_95_percentile>),
which liblsl tools and LabRecorder keep verbatim in XDF files. Opt-in
flags::DEVICE_DELAY (32, Post::DEVICE_DELAY,
LABSTREAM_POST_DEVICE_DELAY) reads that value and subtracts it from each
timestamp while default timestamps stay unchanged.
meta: in-band live metadata¶
Status: implemented on main (docs/roadmap.md, step 16). The token is
meta/1, on by default in labstream.Features.
Comparison with a second LSL stream¶
A second irregular string LSL stream also carries live metadata and works with liblsl tools and LabRecorder. It has three costs for an application:
- The viewer must discover, open, and track a second stream for each device,
and match its
source_idor name by convention. - The second stream runs its own TCP socket and clock sync thread, so sample boundary ordering with the data stream is approximate.
- A device driver that opens one outlet must open and manage two outlets.
In-band meta/1 avoids those costs for labstream peers. A device can still
publish a second LSL marker stream when XDF archival of metadata through
liblsl LabRecorder is necessary.
Wire format¶
When both peers negotiate meta/1, the outlet can write a 0xFC record on
the TCP feed channel (active on TCP, dgram/1, and shm/1):
u8 tag 0xFC
u64 seq little-endian outlet sample sequence number at emission
f64 timestamp little-endian IEEE-754 seconds on the outlet clock
u32 key_len little-endian UTF-8 byte length (max 65536)
u32 val_len little-endian UTF-8 byte length (max 65536)
[u8; key_len] UTF-8 key (for example `impedance/Fp1`)
[u8; val_len] UTF-8 value (for example `4.2 kOhm`)
On TCP, the outlet writes each record before the first sample whose sequence
number is at or above seq. On initial connection, the outlet sends the
latest value of each key in seq order. A liblsl inlet never offers meta/1
and never receives a 0xFC record.
Browser reach (WebSocket and WebAssembly)¶
Status: implemented on main (docs/roadmap.md, step 13).
WsBridge (crates/labstream-net/src/ws.rs) and labstream relay --ws-port
expose an opt-in RFC 6455 WebSocket endpoint. The endpoint is off by default
and accepts only loopback peers unless --ws-allow lists other addresses.
Subscribed streams send binary frames with an 8-byte header
([u32 stream_id LE][u32 sample_count LE]) followed by exact little-endian
LSL wire samples (TAG_TRANSMITTED_TIMESTAMP = 2) for decoding by
crates/labstream-wasm (wasm32-unknown-unknown). Text JSON frames handle
list, subscribe, unsubscribe, marker, and forwarded meta/1 updates.
enc: opt-in negotiated transport encryption¶
Status: implemented on main (docs/roadmap.md, step 14). The token is
enc/1=<64-hex-pubkey>. It is off by default.
Configuration and trust model¶
- By default,
encis not inlabstream.Featuresandlabstream.RequireEncryptionis0. Every connection uses plain LSL. - When the user adds
enctolabstream.Features(or callslabstream_set_encryption), two labstream peers negotiateenc/1and encrypt all post-test-pattern feed traffic. A liblsl peer ignoresLabstream-Featuresand gets plain LSL. - When
labstream.RequireEncryption = 1, the outlet refuses a plain inlet withLSL/110 403 Encryption required, and the inlet refuses a plain outlet with a clear permission error. - When
labstream.EncryptionKeyis empty, the handshake uses ephemeral X25519 key exchange (RFC 7748) to stop passive network eavesdropping. Whenlabstream.EncryptionKeyis set, the pre-shared key mixes into the HKDF-SHA256 salt for mutual peer authentication. - Discovery (
LSL:shortinfo) stays plain LSL so liblsl peers on the same network keep working unchanged.
Wire format¶
Both the inlet offer and the outlet answer carry enc/1=<64-hex-pubkey>
(32-byte ephemeral X25519 public key). Both sides derive one 32-byte
ChaCha20-Poly1305 (RFC 8439) key via HKDF-SHA256 (RFC 5869) over
SHA-256("labstream-enc-v1" || inlet_pk || outlet_pk [|| "|psk|" || psk])
using the reviewed ring crate.
From the first byte after the two plain test-pattern samples, the outlet wraps the feed in length-prefixed AEAD frames:
u32 ct_len little-endian length of ciphertext plus 16-byte tag
[u8; ct_len] ChaCha20-Poly1305(key, nonce = [0,0,0,0 || seq_le], aad = ct_len_le)
The outlet writes an empty authenticated frame at once so a mismatched
pre-shared key fails during open. seq/1, resume/1, select/1, comp/1,
and meta/1 run inside the encrypted TCP stream. shm/1 and dgram/1 stay
off while enc/1 is active so every sample stays encrypted on the wire.
Alternatives that this proposal rejects¶
A higher Data-Protocol-Version, for example 120. liblsl uses the lower
of the two versions (src/tcp_server.cpp:641). Thus a liblsl peer falls back
correctly. But the version numbers belong to liblsl. A future liblsl release
can use the same number for a different format, and the two ends then agree
on different things. A version is also one scale, and the features are
independent.
A new request line, for example LSL:labstream-feed. A liblsl server
sends no answer to a request line that it does not know
(src/tcp_server.cpp:502-531). The inlet then needs a timeout and a second
connection for each liblsl outlet. That adds a delay to each start and to
each recovery.
A field in the stream description. The description goes to every consumer, and LabRecorder writes it into each XDF file. A field there changes the stored data, and it does not describe one connection.
The conformance plan¶
Each item gives its status on main.
- liblsl outlet, raw request. Send a feed request with the header to the
oracle outlet. Make sure that the answer and the data bytes are the same
as for the request without the header. Done:
oracle/headerprobe.pypasses for liblsl and for labstreammain. It also reads the first data byte: a sample tag (1 or 2) for each outlet, and the record tag0xFEonly when the answer holdsseq/1. - liblsl inlet. Make sure that a labstream outlet sends no
Labstream-Featuresline, and no record, when the request has none. Done:crates/labstream-net/tests/seq_live.rs,a_request_without_the_header_gets_plain_samples. The interop matrix also runs liblsl inlets against the labstream outlet. - Released labstream 0.1.2. Run it as a peer in both directions. It
knows nothing of the header, so each run must give plain LSL. Done:
below
crates/,maindiffers from the tagv0.1.2only in one comment.oracle/headerprobe.pyon amainoutlet shows no answer line. Item 2 covers a 0.1.2 inlet, which sends no header. - Two labstream peers. Run each feature on and off, and each mix of
offer and answer. Done: the unit tests in
feed.rsandfeatures.rscover each mix.oracle/interop.pyand its self test pass withseqon, and again withlabstream.Features = {}in a configuration file.oracle/headerprobe.pywith the feature off gives an empty answer and no other change. - Syntax. Send tokens with uppercase letters, with
;, and with a bad form. Make sure that the outlet ignores each bad token, and keeps the good ones. Done: the unit tests infeatures.rs. - The full interop matrix.
oracle/interop.pymust give the same result as before, with the header on. Done: each mode gives the same count as onmain.
Open questions¶
- The API that reports the features of the current connection.