Skip to main content

labstream_proto/
feed.rs

1//! The data feed state machine, client side. SPEC.md 4 and 6.
2//!
3//! The machine takes bytes and returns bytes. It opens no socket and reads no
4//! clock, so a test drives every state with a byte slice.
5
6use crate::header::{parse_block, Error, Headers, StatusLine};
7use crate::negotiate::{BIG, LITTLE};
8use labstream_wire::{ByteOrder, Codec, Format, Sample, TEST_PATTERN_OFFSETS};
9
10/// What the client asks for.
11#[derive(Debug, Clone, PartialEq)]
12pub struct FeedParams {
13    /// The version to ask for.
14    pub version: i32,
15    /// The UID of the stream to open.
16    pub uid: String,
17    /// The byte order of this machine.
18    pub native_byte_order: i32,
19    /// How fast this machine converts a byte order.
20    ///
21    /// A measured value. A test injects a fixed number, because no conformance
22    /// test can compare it. SPEC.md 5.2.
23    pub endian_performance: f64,
24    /// True when this machine holds IEEE-754 floats.
25    pub has_ieee754_floats: bool,
26    /// True when this machine holds subnormal values.
27    pub supports_subnormals: bool,
28    /// The width of one channel value. Zero for a string stream.
29    pub value_size: i32,
30    /// The buffer length to ask for.
31    pub max_buffer_length: i32,
32    /// The chunk length to ask for. Zero means no limit.
33    pub max_chunk_length: i32,
34    /// The host name of this machine.
35    pub hostname: String,
36    /// The source identifier of the stream.
37    pub source_id: String,
38    /// The session identifier.
39    pub session_id: String,
40}
41
42impl FeedParams {
43    /// Build the usual parameters for a stream.
44    pub fn new(uid: &str, format: Format) -> Self {
45        FeedParams {
46            version: crate::negotiate::LSL_PROTOCOL_VERSION,
47            uid: uid.to_string(),
48            native_byte_order: if cfg!(target_endian = "little") {
49                LITTLE
50            } else {
51                BIG
52            },
53            endian_performance: 0.0,
54            has_ieee754_floats: true,
55            supports_subnormals: true,
56            value_size: format.width().unwrap_or(0) as i32,
57            max_buffer_length: 360,
58            max_chunk_length: 0,
59            hostname: String::new(),
60            source_id: String::new(),
61            session_id: "default".to_string(),
62        }
63    }
64
65    /// Write the request line and the header block.
66    ///
67    /// The field order matches `src/data_receiver.cpp:170-190`. A real liblsl
68    /// server reads the names and not the order, but a transcript comparison
69    /// needs the same order.
70    pub fn to_wire(&self) -> Vec<u8> {
71        let mut s = format!("LSL:streamfeed/{} {}\r\n", self.version, self.uid);
72        s.push_str(&format!(
73            "Native-Byte-Order: {}\r\n",
74            self.native_byte_order
75        ));
76        s.push_str(&format!(
77            "Endian-Performance: {}\r\n",
78            self.endian_performance.floor()
79        ));
80        s.push_str(&format!(
81            "Has-IEEE754-Floats: {}\r\n",
82            self.has_ieee754_floats as i32
83        ));
84        s.push_str(&format!(
85            "Supports-Subnormals: {}\r\n",
86            self.supports_subnormals as i32
87        ));
88        s.push_str(&format!("Value-Size: {}\r\n", self.value_size));
89        // liblsl writes this name, and the server never reads it. SPEC.md 4.4.
90        s.push_str(&format!("Data-Protocol-Version: {}\r\n", self.version));
91        s.push_str(&format!(
92            "Max-Buffer-Length: {}\r\n",
93            self.max_buffer_length
94        ));
95        s.push_str(&format!("Max-Chunk-Length: {}\r\n", self.max_chunk_length));
96        s.push_str(&format!("Hostname: {}\r\n", self.hostname));
97        s.push_str(&format!("Source-Id: {}\r\n", self.source_id));
98        s.push_str(&format!("Session-Id: {}\r\n", self.session_id));
99        s.push_str("\r\n");
100        s.into_bytes()
101    }
102}
103
104/// The parameters that the answer settled.
105#[derive(Debug, Clone, PartialEq)]
106pub struct FeedAgreement {
107    /// The negotiated data protocol version.
108    pub data_protocol_version: i32,
109    /// The byte order for the sample stream.
110    pub order: ByteOrder,
111    /// True when the reader clears subnormal values.
112    pub suppress_subnormals: bool,
113    /// The UID that the answer named.
114    pub uid: String,
115}
116
117/// Where the client is in the handshake.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum State {
120    /// The request went out. The client waits for the answer headers.
121    AwaitingHeaders,
122    /// The headers arrived. The client waits for two test pattern samples.
123    AwaitingTestPattern,
124    /// The handshake finished. Every later byte is a sample.
125    Streaming,
126    /// The handshake stopped.
127    Failed,
128}
129
130/// The client side of a data feed.
131pub struct FeedClient {
132    params: FeedParams,
133    format: Format,
134    channels: usize,
135    state: State,
136    agreement: Option<FeedAgreement>,
137    codec: Option<Codec>,
138}
139
140impl FeedClient {
141    /// Build a client and return the bytes to send.
142    pub fn start(params: FeedParams, format: Format, channels: usize) -> (Self, Vec<u8>) {
143        let bytes = params.to_wire();
144        (
145            FeedClient {
146                params,
147                format,
148                channels,
149                state: State::AwaitingHeaders,
150                agreement: None,
151                codec: None,
152            },
153            bytes,
154        )
155    }
156
157    /// The current state.
158    pub fn state(&self) -> State {
159        self.state
160    }
161
162    /// What the answer settled. Available once the headers arrive.
163    pub fn agreement(&self) -> Option<&FeedAgreement> {
164        self.agreement.as_ref()
165    }
166
167    /// The codec for the sample stream. Available once the headers arrive.
168    pub fn codec(&self) -> Option<&Codec> {
169        self.codec.as_ref()
170    }
171
172    /// Read the answer headers.
173    ///
174    /// Returns the number of bytes used. A buffer with no complete block
175    /// returns `Error::Incomplete`, and the caller reads more bytes.
176    pub fn on_headers(&mut self, buf: &[u8]) -> Result<usize, Error> {
177        let nl = match buf.iter().position(|&b| b == b'\n') {
178            Some(n) => n,
179            None => return Err(Error::Incomplete),
180        };
181        let status = StatusLine::parse(&String::from_utf8_lossy(&buf[..nl]))?;
182
183        // A newer major version stops the feed.
184        // `src/data_receiver.cpp:200-203`.
185        if status.version / 100 > self.params.version / 100 {
186            self.state = State::Failed;
187            return Err(Error::VersionTooNew {
188                theirs: status.version,
189                ours: self.params.version,
190            });
191        }
192
193        if status.action() != crate::header::StatusAction::Proceed {
194            self.state = State::Failed;
195            return Err(Error::Status(status));
196        }
197
198        let (headers, used) = match parse_block(&buf[nl + 1..]) {
199            Some(x) => x,
200            None => return Err(Error::Incomplete),
201        };
202
203        let agreement = self.read_answer(&headers)?;
204        let order = agreement.order;
205        self.codec = Some(
206            Codec::new(self.format, self.channels, order)
207                .with_suppress_subnormals(agreement.suppress_subnormals),
208        );
209        self.agreement = Some(agreement);
210        self.state = State::AwaitingTestPattern;
211        Ok(nl + 1 + used)
212    }
213
214    fn read_answer(&mut self, h: &Headers) -> Result<FeedAgreement, Error> {
215        // The UID must match. `src/data_receiver.cpp:242`.
216        let uid = h.get("uid").unwrap_or("").to_string();
217        if !uid.is_empty() && uid != self.params.uid {
218            self.state = State::Failed;
219            return Err(Error::UidMismatch {
220                expected: self.params.uid.clone(),
221                actual: uid,
222            });
223        }
224
225        // A value of 0 means the native order of the reader. This case exists
226        // for liblsl 1.13 and earlier. `src/data_receiver.cpp:231`.
227        let raw = h.get_int("byte-order").unwrap_or(LITTLE as i64) as i32;
228        let order_value = if raw == 0 {
229            self.params.native_byte_order
230        } else {
231            raw
232        };
233        let order = match ByteOrder::from_wire(order_value) {
234            Some(o) => o,
235            None => {
236                self.state = State::Failed;
237                return Err(Error::ByteOrderNotSupported(order_value));
238            }
239        };
240
241        let version = h
242            .get_int("data-protocol-version")
243            .unwrap_or(self.params.version as i64) as i32;
244        if version > self.params.version {
245            self.state = State::Failed;
246            return Err(Error::VersionTooNew {
247                theirs: version,
248                ours: self.params.version,
249            });
250        }
251        // A server can agree to a version below the one that was asked for.
252        // `src/tcp_server.cpp:576` only refuses a different major version, so
253        // a 1.10 request against a server set to 1.00 is answered with 1.00.
254        //
255        // Protocol 1.00 carries every sample in a Boost archive
256        // (`src/sample.cpp:330`), which this implementation does not read. It
257        // has to stop here. Without this test the bytes of the archive are
258        // decoded as 1.10 samples, and the first error is a wrong tag rather
259        // than a wrong version.
260        if version < 110 {
261            self.state = State::Failed;
262            return Err(Error::VersionTooOld { theirs: version });
263        }
264
265        Ok(FeedAgreement {
266            data_protocol_version: version,
267            order,
268            suppress_subnormals: h.get_bool("suppress-subnormals").unwrap_or(false),
269            uid,
270        })
271    }
272
273    /// Read the two test pattern samples and compare them. SPEC.md 6.
274    ///
275    /// The client builds the expected samples itself. A mismatch means the
276    /// formats differ, and liblsl stops the feed with a named error.
277    ///
278    /// Returns the number of bytes used.
279    pub fn on_test_pattern(&mut self, buf: &[u8]) -> Result<usize, TestPatternError> {
280        let codec = self.codec.as_ref().ok_or(TestPatternError::NotReady)?;
281        let mut off = 0usize;
282        for (i, pattern) in TEST_PATTERN_OFFSETS.iter().enumerate() {
283            let (got, n) = match codec.decode(&buf[off..]) {
284                Ok(x) => x,
285                Err(labstream_wire::Error::Truncated) => return Err(TestPatternError::Incomplete),
286                Err(e) => {
287                    self.state = State::Failed;
288                    return Err(TestPatternError::Decode(e));
289                }
290            };
291            let want = labstream_wire::test_pattern(self.format, self.channels, *pattern);
292            if !same_sample(&got, &want) {
293                self.state = State::Failed;
294                return Err(TestPatternError::Mismatch {
295                    index: i,
296                    expected: Box::new(want),
297                    actual: Box::new(got),
298                });
299            }
300            off += n;
301        }
302        self.state = State::Streaming;
303        Ok(off)
304    }
305
306    /// Read samples from the stream.
307    pub fn on_samples(&self, buf: &[u8]) -> Result<(Vec<Sample>, usize), labstream_wire::Error> {
308        let codec = self.codec.as_ref().expect("the handshake set the codec");
309        codec.decode_all(buf)
310    }
311}
312
313/// Compare two samples by bit pattern.
314///
315/// liblsl compares samples with `operator!=`. A direct comparison of floats
316/// fails for a value that is not a number, so this compares bits.
317fn same_sample(a: &Sample, b: &Sample) -> bool {
318    use labstream_wire::Value;
319    a.timestamp.to_bits() == b.timestamp.to_bits()
320        && a.values.len() == b.values.len()
321        && a.values.iter().zip(&b.values).all(|(x, y)| match (x, y) {
322            (Value::F32(p), Value::F32(q)) => p.to_bits() == q.to_bits(),
323            (Value::F64(p), Value::F64(q)) => p.to_bits() == q.to_bits(),
324            _ => x == y,
325        })
326}
327
328/// A failure while reading the test pattern.
329#[derive(Debug, Clone, PartialEq)]
330pub enum TestPatternError {
331    /// The buffer holds no complete sample yet.
332    Incomplete,
333    /// The handshake has not reached this stage.
334    NotReady,
335    /// The codec refused the bytes.
336    Decode(labstream_wire::Error),
337    /// A sample did not match the pattern.
338    ///
339    /// liblsl reports `The received test-pattern samples do not match the
340    /// specification. The protocol formats are likely incompatible.`
341    /// (`src/data_receiver.cpp:294`).
342    Mismatch {
343        /// Which of the two samples differed.
344        index: usize,
345        /// The sample that the specification produces.
346        expected: Box<Sample>,
347        /// The sample that arrived.
348        actual: Box<Sample>,
349    },
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355    use crate::header::parse_block;
356    use crate::negotiate::{negotiate, FeedRequest, Outcome, ServerStream};
357
358    fn handshake(
359        format: Format,
360        channels: usize,
361        client_order: i32,
362        client_perf: f64,
363    ) -> FeedClient {
364        let mut p = FeedParams::new("uid-1", format);
365        p.native_byte_order = client_order;
366        p.endian_performance = client_perf;
367        let (mut client, request) = FeedClient::start(p, format, channels);
368
369        // Drive a server built from the same specification.
370        let text = String::from_utf8_lossy(&request);
371        let head = text.split("\r\n").next().unwrap().to_string();
372        let uid = head.split(' ').nth(1).unwrap_or("").to_string();
373        let block_start = request.iter().position(|&b| b == b'\n').unwrap() + 1;
374        let (headers, _) = parse_block(&request[block_start..]).expect("a block");
375
376        let srv = ServerStream::new("uid-1", format, LITTLE, 1000.0);
377        let req = FeedRequest::from_headers(110, &uid, &headers, srv.channel_bytes);
378        let accepted = match negotiate(&req, &srv) {
379            Outcome::Accept(a) => a,
380            Outcome::Refuse(s) => panic!("refused: {} {}", s.code, s.message),
381        };
382
383        let answer = accepted.to_wire(110, "uid-1");
384        client.on_headers(answer.as_bytes()).expect("headers");
385
386        // The server then sends the two test pattern samples.
387        let codec = *client.codec().expect("a codec");
388        let mut bytes = Vec::new();
389        for off in TEST_PATTERN_OFFSETS {
390            let s = labstream_wire::test_pattern(format, channels, off);
391            codec.encode(&s, &mut bytes).expect("encode");
392        }
393        let used = client.on_test_pattern(&bytes).expect("the test pattern");
394        assert_eq!(used, bytes.len());
395        client
396    }
397
398    #[test]
399    fn the_request_carries_every_header_that_liblsl_writes() {
400        let p = FeedParams::new("abc", Format::Float32);
401        let text = String::from_utf8(p.to_wire()).unwrap();
402        for name in [
403            "Native-Byte-Order",
404            "Endian-Performance",
405            "Has-IEEE754-Floats",
406            "Supports-Subnormals",
407            "Value-Size",
408            "Data-Protocol-Version",
409            "Max-Buffer-Length",
410            "Max-Chunk-Length",
411            "Hostname",
412            "Source-Id",
413            "Session-Id",
414        ] {
415            assert!(text.contains(name), "the request is missing {name}");
416        }
417        assert!(text.starts_with("LSL:streamfeed/110 abc\r\n"));
418        assert!(text.ends_with("\r\n\r\n"));
419    }
420
421    #[test]
422    fn a_full_handshake_reaches_the_streaming_state() {
423        let c = handshake(Format::Float32, 8, LITTLE, 0.0);
424        assert_eq!(c.state(), State::Streaming);
425        let a = c.agreement().expect("an agreement");
426        assert_eq!(a.data_protocol_version, 110);
427        assert_eq!(a.order, ByteOrder::Little);
428    }
429
430    #[test]
431    fn a_slow_client_makes_the_server_swap() {
432        let c = handshake(Format::Double64, 4, BIG, 0.0);
433        assert_eq!(c.agreement().unwrap().order, ByteOrder::Big);
434    }
435
436    #[test]
437    fn a_wrong_uid_in_the_answer_stops_the_feed() {
438        let p = FeedParams::new("uid-1", Format::Float32);
439        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
440        let answer = "LSL/110 200 OK\r\nUID: another\r\nByte-Order: 1234\r\n\
441                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
442        match c.on_headers(answer.as_bytes()) {
443            Err(Error::UidMismatch { actual, .. }) => assert_eq!(actual, "another"),
444            other => panic!("expected a UID mismatch, got {other:?}"),
445        }
446        assert_eq!(c.state(), State::Failed);
447    }
448
449    #[test]
450    fn a_404_answer_stops_the_feed() {
451        let p = FeedParams::new("uid-1", Format::Float32);
452        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
453        match c.on_headers(b"LSL/110 404 Not found\r\n\r\n") {
454            Err(Error::Status(s)) => assert_eq!(s.code, 404),
455            other => panic!("expected a status error, got {other:?}"),
456        }
457        assert_eq!(c.state(), State::Failed);
458    }
459
460    #[test]
461    fn a_byte_order_of_zero_means_the_native_order() {
462        // The case for liblsl 1.13 and earlier.
463        let p = FeedParams::new("uid-1", Format::Float32);
464        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
465        let answer = "LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 0\r\n\
466                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
467        c.on_headers(answer.as_bytes()).expect("headers");
468        assert_eq!(c.agreement().unwrap().order, ByteOrder::native());
469    }
470
471    #[test]
472    fn a_wrong_test_pattern_stops_the_feed() {
473        let p = FeedParams::new("uid-1", Format::Float32);
474        let (mut c, _) = FeedClient::start(p, Format::Float32, 2);
475        let answer = "LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 1234\r\n\
476                      Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n";
477        c.on_headers(answer.as_bytes()).expect("headers");
478
479        // Send the second pattern first. A wrong implementation does this.
480        let codec = *c.codec().unwrap();
481        let mut bytes = Vec::new();
482        for off in [2, 4] {
483            codec
484                .encode(
485                    &labstream_wire::test_pattern(Format::Float32, 2, off),
486                    &mut bytes,
487                )
488                .unwrap();
489        }
490        match c.on_test_pattern(&bytes) {
491            Err(TestPatternError::Mismatch { index, .. }) => assert_eq!(index, 0),
492            other => panic!("expected a mismatch, got {other:?}"),
493        }
494        assert_eq!(c.state(), State::Failed);
495    }
496
497    #[test]
498    fn an_incomplete_buffer_asks_for_more() {
499        let p = FeedParams::new("uid-1", Format::Float32);
500        let (mut c, _) = FeedClient::start(p, Format::Float32, 1);
501        assert_eq!(
502            c.on_headers(b"LSL/110 200 OK\r\nUID: uid-1\r\n"),
503            Err(Error::Incomplete)
504        );
505        assert_eq!(c.state(), State::AwaitingHeaders);
506    }
507}