1use crate::header::{parse_block, Error, Headers, StatusLine};
7use crate::negotiate::{BIG, LITTLE};
8use labstream_wire::{ByteOrder, Codec, Format, Sample, TEST_PATTERN_OFFSETS};
9
10#[derive(Debug, Clone, PartialEq)]
12pub struct FeedParams {
13 pub version: i32,
15 pub uid: String,
17 pub native_byte_order: i32,
19 pub endian_performance: f64,
24 pub has_ieee754_floats: bool,
26 pub supports_subnormals: bool,
28 pub value_size: i32,
30 pub max_buffer_length: i32,
32 pub max_chunk_length: i32,
34 pub hostname: String,
36 pub source_id: String,
38 pub session_id: String,
40}
41
42impl FeedParams {
43 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 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 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#[derive(Debug, Clone, PartialEq)]
106pub struct FeedAgreement {
107 pub data_protocol_version: i32,
109 pub order: ByteOrder,
111 pub suppress_subnormals: bool,
113 pub uid: String,
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum State {
120 AwaitingHeaders,
122 AwaitingTestPattern,
124 Streaming,
126 Failed,
128}
129
130pub 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 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 pub fn state(&self) -> State {
159 self.state
160 }
161
162 pub fn agreement(&self) -> Option<&FeedAgreement> {
164 self.agreement.as_ref()
165 }
166
167 pub fn codec(&self) -> Option<&Codec> {
169 self.codec.as_ref()
170 }
171
172 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 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 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 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 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 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 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
313fn 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#[derive(Debug, Clone, PartialEq)]
330pub enum TestPatternError {
331 Incomplete,
333 NotReady,
335 Decode(labstream_wire::Error),
337 Mismatch {
343 index: usize,
345 expected: Box<Sample>,
347 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 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 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 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 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}