1use labstream_wire::Format;
4
5#[derive(Debug, Clone, PartialEq)]
7pub struct StreamInfo {
8 pub name: String,
10 pub stream_type: String,
12 pub channel_count: u32,
14 pub format: Format,
16 pub nominal_srate: f64,
18 pub source_id: String,
20 pub session_id: String,
22 pub hostname: String,
24 pub uid: String,
26 pub created_at: f64,
28 pub v4address: String,
35 pub v6address: String,
38 pub v4data_port: u16,
40 pub v4service_port: u16,
42 pub v6data_port: u16,
44 pub v6service_port: u16,
46 pub desc: crate::desc::Node,
52 from_document: bool,
63}
64
65pub fn format_name(f: Format) -> &'static str {
70 match f {
71 Format::Float32 => "float32",
72 Format::Double64 => "double64",
73 Format::String => "string",
74 Format::Int32 => "int32",
75 Format::Int16 => "int16",
76 Format::Int8 => "int8",
77 Format::Int64 => "int64",
78 Format::Undefined => "undefined",
79 }
80}
81
82pub fn format_from_name(s: &str) -> Option<Format> {
84 Some(match s {
85 "float32" => Format::Float32,
86 "double64" => Format::Double64,
87 "string" => Format::String,
88 "int32" => Format::Int32,
89 "int16" => Format::Int16,
90 "int8" => Format::Int8,
91 "int64" => Format::Int64,
92 _ => return None,
93 })
94}
95
96impl StreamInfo {
97 pub fn new(
99 name: &str,
100 stream_type: &str,
101 channel_count: u32,
102 format: Format,
103 srate: f64,
104 ) -> Self {
105 StreamInfo {
106 name: name.to_string(),
107 stream_type: stream_type.to_string(),
108 channel_count,
109 format,
110 nominal_srate: srate,
111 source_id: String::new(),
112 session_id: String::new(),
117 hostname: hostname(),
118 uid: String::new(),
119 created_at: 0.0,
120 v4address: String::new(),
121 v6address: String::new(),
122 v4data_port: 0,
123 v4service_port: 0,
124 v6data_port: 0,
125 v6service_port: 0,
126 desc: crate::desc::Node::element("desc"),
127 from_document: false,
128 }
129 }
130
131 pub fn to_shortinfo_xml(&self) -> String {
137 self.to_xml("\t<desc />\n")
138 }
139
140 pub fn to_fullinfo_xml(&self) -> String {
147 let mut body = String::new();
148 let mut node = self.desc.clone();
149 node.name = "desc".to_string();
150 node.write(&mut body, 1);
151 self.to_xml(&body)
152 }
153
154 fn to_xml(&self, desc_body: &str) -> String {
155 let field = |name: &str, value: String| -> String {
158 if value.is_empty() && self.from_document {
159 format!("\t<{name} />\n")
160 } else {
161 format!("\t<{name}>{value}</{name}>\n")
162 }
163 };
164 let mut out = String::from("<?xml version=\"1.0\"?>\n<info>\n");
165 out.push_str(&field("name", escape(&self.name)));
166 out.push_str(&field("type", escape(&self.stream_type)));
167 out.push_str(&field("channel_count", self.channel_count.to_string()));
168 out.push_str(&field(
169 "channel_format",
170 format_name(self.format).to_string(),
171 ));
172 out.push_str(&field("source_id", escape(&self.source_id)));
173 out.push_str(&field("nominal_srate", show_point_16(self.nominal_srate)));
174 out.push_str(&field("version", "1.100000000000000".to_string()));
175 out.push_str(&field("created_at", show_point_16(self.created_at)));
176 out.push_str(&field("uid", escape(&self.uid)));
177 out.push_str(&field("session_id", escape(&self.session_id)));
178 out.push_str(&field("hostname", escape(&self.hostname)));
179 out.push_str(&field("v4address", escape(&self.v4address)));
180 out.push_str(&field("v4data_port", self.v4data_port.to_string()));
181 out.push_str(&field("v4service_port", self.v4service_port.to_string()));
182 out.push_str(&field("v6address", escape(&self.v6address)));
183 out.push_str(&field("v6data_port", self.v6data_port.to_string()));
184 out.push_str(&field("v6service_port", self.v6service_port.to_string()));
185 out.push_str(desc_body);
186 out.push_str("</info>\n");
187 out
188 }
189
190 pub fn from_shortinfo_xml(xml: &str) -> Option<Self> {
192 let s = labstream_proto::discovery::ShortInfo::parse(xml)?;
193 Some(StreamInfo {
194 name: s.name,
195 stream_type: s.stream_type,
196 channel_count: s.channel_count,
197 format: format_from_name(&s.channel_format)?,
198 nominal_srate: s.nominal_srate,
199 source_id: s.source_id,
200 session_id: tag(xml, "session_id").unwrap_or("default").to_string(),
201 hostname: s.hostname,
202 uid: s.uid,
203 created_at: tag(xml, "created_at")
204 .and_then(|v| v.trim().parse().ok())
205 .unwrap_or(0.0),
206 v4address: tag(xml, "v4address").unwrap_or("").trim().to_string(),
207 v6address: tag(xml, "v6address").unwrap_or("").trim().to_string(),
208 v4data_port: s.v4data_port,
209 v4service_port: s.v4service_port,
210 v6data_port: tag(xml, "v6data_port")
211 .and_then(|v| v.trim().parse().ok())
212 .unwrap_or(0),
213 v6service_port: tag(xml, "v6service_port")
214 .and_then(|v| v.trim().parse().ok())
215 .unwrap_or(0),
216 desc: crate::desc::Node::element("desc"),
217 from_document: true,
218 })
219 }
220
221 pub fn from_fullinfo_xml(xml: &str) -> Result<Self, String> {
229 let root = crate::desc::parse(xml).ok_or_else(|| "the document is not XML".to_string())?;
230 let info = if root.name == "info" {
231 root
232 } else {
233 root.child("info")
234 .cloned()
235 .ok_or_else(|| "no <info> element".to_string())?
236 };
237
238 let text = |k: &str| info.child_value_of(k).to_string();
239
240 let name = text("name");
241 if name.is_empty() {
242 return Err("Received a stream info with empty <name> field.".into());
243 }
244 let channel_count = bounded(&text("channel_count"), "channel_count", 0, 0)? as u32;
245 bounded(&text("nominal_srate"), "nominal_srate", 0, 0)?;
246 let nominal_srate = stod(&text("nominal_srate"))?;
247 let fmt = text("channel_format");
248 let format =
249 format_from_name(&fmt).ok_or_else(|| format!("Invalid channel format {fmt}"))?;
250 if (stod(&text("version"))? * 100.0) as i32 <= 0 {
251 return Err("The version of the given stream info is invalid.".into());
252 }
253 let created_at = stod(&text("created_at"))?;
254 let uid = text("uid");
255 if uid.is_empty() {
256 return Err("The UID of the given stream info is empty.".into());
257 }
258
259 Ok(StreamInfo {
260 name,
261 stream_type: text("type"),
262 channel_count,
263 format,
264 nominal_srate,
265 source_id: text("source_id"),
266 session_id: text("session_id"),
267 hostname: text("hostname"),
268 uid,
269 created_at,
270 v4address: text("v4address"),
271 v6address: text("v6address"),
272 v4data_port: bounded(&text("v4data_port"), "v4data_port", 0, 65535)? as u16,
273 v4service_port: bounded(&text("v4service_port"), "v4service_port", 0, 65535)? as u16,
274 v6data_port: bounded(&text("v6data_port"), "v6data_port", 0, 65535)? as u16,
275 v6service_port: bounded(&text("v6service_port"), "v6service_port", 0, 65535)? as u16,
276 desc: info
277 .child("desc")
278 .cloned()
279 .unwrap_or_else(|| crate::desc::Node::element("desc")),
280 from_document: true,
281 })
282 }
283
284 pub fn document(&self) -> crate::desc::Node {
291 let mut info = crate::desc::Node::element("info");
292 let mut put = |name: &str, value: String| {
293 info.append_child_value(name, &value);
294 };
295 put("name", self.name.clone());
296 put("type", self.stream_type.clone());
297 put("channel_count", self.channel_count.to_string());
298 put("channel_format", format_name(self.format).to_string());
299 put("source_id", self.source_id.clone());
300 put("nominal_srate", show_point_16(self.nominal_srate));
301 put("version", "1.100000000000000".to_string());
302 put("created_at", show_point_16(self.created_at));
303 put("uid", self.uid.clone());
304 put("session_id", self.session_id.clone());
305 put("hostname", self.hostname.clone());
306 put("v4address", self.v4address.clone());
307 put("v4data_port", self.v4data_port.to_string());
308 put("v4service_port", self.v4service_port.to_string());
309 put("v6address", self.v6address.clone());
310 put("v6data_port", self.v6data_port.to_string());
311 put("v6service_port", self.v6service_port.to_string());
312 let mut tree = self.desc.clone();
313 tree.name = "desc".to_string();
314 info.children.push(tree);
315 info
316 }
317
318 pub fn matches(&self, query: &str) -> bool {
324 crate::xpath::matches(query, &self.document())
325 }
326}
327
328pub fn show_point_16(v: f64) -> String {
342 if v.is_nan() {
343 return "nan".to_string();
344 }
345 if v.is_infinite() {
346 return if v < 0.0 { "-inf" } else { "inf" }.to_string();
347 }
348 let sci = format!("{v:.15e}");
349 let (mantissa, exp_text) = match sci.split_once('e') {
350 Some(x) => x,
351 None => return sci,
352 };
353 let exp: i32 = exp_text.parse().unwrap_or(0);
354 if !(-4..16).contains(&exp) {
355 let sign = if exp < 0 { '-' } else { '+' };
356 return format!("{mantissa}e{sign}{:02}", exp.abs());
357 }
358 format!("{:.*}", (15 - exp) as usize, v)
359}
360
361fn stod(text: &str) -> Result<f64, String> {
367 let t = text.trim();
368 let mut end = 0;
369 for (i, c) in t.char_indices() {
370 let keep = c.is_ascii_digit()
371 || (i == 0 && (c == '-' || c == '+'))
372 || c == '.'
373 || c == 'e'
374 || c == 'E'
375 || ((c == '-' || c == '+')
376 && matches!(t.as_bytes().get(i - 1), Some(b'e') | Some(b'E')));
377 if !keep {
378 break;
379 }
380 end = i + c.len_utf8();
381 }
382 t[..end].parse().map_err(|_| "stod".to_string())
383}
384
385fn bounded(text: &str, field: &str, min: i32, max: i32) -> Result<i32, String> {
392 let t = text.trim();
393 let digits: String = t
394 .char_indices()
395 .take_while(|(i, c)| c.is_ascii_digit() || (*i == 0 && (*c == '-' || *c == '+')))
396 .map(|(_, c)| c)
397 .collect();
398 let value: i32 = digits.parse().map_err(|_| "stoi".to_string())?;
399 if value < min || (max != 0 && value > max) {
400 let mut msg = format!("{field} must be >={min}");
401 if max != 0 {
402 msg.push_str(&format!(" and <={max}"));
403 }
404 return Err(msg);
405 }
406 Ok(value)
407}
408
409fn escape(s: &str) -> String {
410 s.replace('&', "&")
411 .replace('<', "<")
412 .replace('>', ">")
413}
414
415fn tag<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
416 let open = format!("<{name}>");
417 let close = format!("</{name}>");
418 let a = xml.find(&open)? + open.len();
419 let b = xml[a..].find(&close)? + a;
420 Some(&xml[a..b])
421}
422
423pub fn hostname() -> String {
425 std::fs::read_to_string("/proc/sys/kernel/hostname")
426 .map(|s| s.trim().to_string())
427 .unwrap_or_else(|_| "unknown".to_string())
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433
434 fn info() -> StreamInfo {
435 let mut i = StreamInfo::new("Probe", "EEG", 8, Format::Float32, 100.0);
436 i.session_id = crate::SESSION_ID.into();
438 i.uid = "25cfa701-e55b-4e42-8fc2-103bbd2f86b6".into();
439 i.source_id = "src".into();
440 i.hostname = "box".into();
441 i.v4data_port = 16572;
442 i.v4service_port = 16572;
443 i
444 }
445
446 #[test]
447 fn the_description_round_trips() {
448 let a = info();
449 let xml = a.to_shortinfo_xml();
450 let b = StreamInfo::from_shortinfo_xml(&xml).expect("a description");
451 assert_eq!(b.name, a.name);
452 assert_eq!(b.channel_count, a.channel_count);
453 assert_eq!(b.format, a.format);
454 assert_eq!(b.uid, a.uid);
455 assert_eq!(b.v4data_port, a.v4data_port);
456 assert!((b.nominal_srate - a.nominal_srate).abs() < 1e-9);
457 }
458
459 #[test]
460 fn the_query_that_liblsl_builds_matches() {
461 let i = info();
463 assert!(i.matches("session_id='default' and name='Probe'"));
464 assert!(i.matches("session_id='default'"));
465 assert!(!i.matches("session_id='default' and name='Other'"));
466 assert!(!i.matches("session_id='other' and name='Probe'"));
467 }
468
469 #[test]
470 fn an_empty_query_matches_every_stream() {
471 assert!(info().matches(""));
472 assert!(info().matches(" "));
473 }
474
475 #[test]
476 fn a_query_beyond_equality_is_answered() {
477 let i = info();
480 assert!(i.matches("contains(name,'Pro')"));
481 assert!(i.matches("channel_count>4"));
482 assert!(i.matches("starts-with(type,'EE')"));
483 }
484
485 #[test]
486 fn a_value_with_a_space_survives_the_split() {
487 let mut i = info();
488 i.name = "My Stream and More".into();
489 assert!(i.matches("session_id='default' and name='My Stream and More'"));
490 }
491
492 #[test]
493 fn every_field_that_a_query_names_is_readable() {
494 let i = info();
495 for f in [
496 "name",
497 "type",
498 "source_id",
499 "session_id",
500 "hostname",
501 "uid",
502 "channel_format",
503 "channel_count",
504 ] {
505 assert!(i.matches(f), "the field {f} is missing from the document");
507 }
508 }
509
510 #[test]
511 fn the_format_names_match_liblsl() {
512 for (f, n) in [
513 (Format::Float32, "float32"),
514 (Format::Double64, "double64"),
515 (Format::String, "string"),
516 (Format::Int32, "int32"),
517 (Format::Int16, "int16"),
518 (Format::Int8, "int8"),
519 (Format::Int64, "int64"),
520 ] {
521 assert_eq!(format_name(f), n);
522 assert_eq!(format_from_name(n), Some(f));
523 }
524 }
525}
526
527#[cfg(test)]
528mod measured_xpath {
529 use super::*;
530
531 fn info() -> StreamInfo {
541 let mut i = StreamInfo::new("XpTest", "EEG", 8, Format::Float32, 100.0);
542 i.session_id = crate::SESSION_ID.into();
544 i.uid = "25cfa701-e55b-4e42-8fc2-103bbd2f86b6".into();
545 i.source_id = "xp_src".into();
546 i
547 }
548
549 #[test]
550 fn the_subset_that_a_resolver_emits_is_answered() {
551 let i = info();
552 for q in [
553 "",
554 "session_id='default'",
555 "session_id='default' and name='XpTest'",
556 "name='XpTest'",
557 "type='EEG'",
558 "source_id='xp_src'",
559 ] {
560 assert!(i.matches(q), "the subset must answer {q:?}");
561 }
562 for q in [
563 "session_id='default' and name='Other'",
564 "name='Nothing'",
565 "type='EMG'",
566 ] {
567 assert!(!i.matches(q), "the subset must refuse {q:?}");
568 }
569 }
570
571 #[test]
572 fn every_shape_that_the_oracle_answers_is_answered_here() {
573 let i = info();
577 for q in [
578 "contains(name,'XpT')",
579 "starts-with(name,'Xp')",
580 "string-length(name)>3",
581 "substring(name,1,2)='Xp'",
582 "concat(name,type)='XpTestEEG'",
583 "channel_count>4",
584 "number(channel_count)+1=9",
585 "//name='XpTest'",
586 "count(//name)=1",
587 "not(name='Nothing')",
588 "name='XpTest' or name='Nothing'",
589 "true()",
590 ] {
591 assert!(i.matches(q), "{q:?} must match, and the oracle answers it");
592 }
593 }
594
595 #[test]
596 fn a_malformed_query_matches_nothing() {
597 let i = info();
600 for q in [
601 "in'va'lid",
602 "name=",
603 "and and and",
604 "name='XpTest'))",
605 "!!!",
606 ] {
607 assert!(!i.matches(q), "a malformed query must not match: {q:?}");
608 }
609 }
610}
611
612pub mod transport {
614 pub const DEFAULT: u32 = 0;
617 pub const BUFSIZE_SAMPLES: u32 = 1;
619 pub const BUFSIZE_THOUSANDTHS: u32 = 2;
621}
622
623impl StreamInfo {
624 pub fn buffer_samples(&self, requested: i32, flags: u32) -> i32 {
633 if flags & transport::BUFSIZE_SAMPLES != 0 && flags & transport::BUFSIZE_THOUSANDTHS != 0 {
634 return requested.max(1);
637 }
638 let mut samples: i64 = if flags & transport::BUFSIZE_SAMPLES != 0 {
639 requested as i64
640 } else if self.nominal_srate == 0.0 {
641 requested as i64 * 100
642 } else {
643 (self.nominal_srate * requested as f64) as i64
644 };
645 if flags & transport::BUFSIZE_THOUSANDTHS != 0 {
646 samples /= 1000;
647 }
648 if samples > i32::MAX as i64 {
649 return i32::MAX;
650 }
651 if samples > 0 {
652 samples as i32
653 } else {
654 1
655 }
656 }
657}
658
659#[cfg(test)]
660mod buffer_length {
661 use super::*;
662
663 fn info(srate: f64) -> StreamInfo {
664 StreamInfo::new("B", "T", 2, Format::Float32, srate)
665 }
666
667 #[test]
668 fn a_rate_makes_the_request_a_count_of_seconds() {
669 assert_eq!(info(1000.0).buffer_samples(20, transport::DEFAULT), 20_000);
671 assert_eq!(info(100.0).buffer_samples(360, transport::DEFAULT), 36_000);
672 }
673
674 #[test]
675 fn no_rate_multiplies_by_one_hundred() {
676 assert_eq!(info(0.0).buffer_samples(1, transport::DEFAULT), 100);
677 assert_eq!(info(0.0).buffer_samples(6, transport::DEFAULT), 600);
678 }
679
680 #[test]
681 fn the_samples_flag_takes_the_value_as_it_stands() {
682 assert_eq!(
683 info(1000.0).buffer_samples(20, transport::BUFSIZE_SAMPLES),
684 20
685 );
686 assert_eq!(info(0.0).buffer_samples(20, transport::BUFSIZE_SAMPLES), 20);
687 }
688
689 #[test]
690 fn the_thousandths_flag_divides() {
691 assert_eq!(
692 info(1000.0).buffer_samples(20_000, transport::BUFSIZE_THOUSANDTHS),
693 20_000
694 );
695 }
696
697 #[test]
698 fn the_result_never_falls_below_one() {
699 assert_eq!(info(0.001).buffer_samples(1, transport::DEFAULT), 1);
700 assert_eq!(info(100.0).buffer_samples(0, transport::DEFAULT), 1);
701 assert_eq!(info(100.0).buffer_samples(-5, transport::DEFAULT), 1);
702 }
703}
704
705impl StreamInfo {
706 pub fn recovery_query(&self) -> String {
720 let mut q = format!("channel_count='{}'", self.channel_count);
721 if !self.name.is_empty() {
722 q.push_str(&format!(" and name='{}'", self.name));
723 }
724 if !self.stream_type.is_empty() {
725 q.push_str(&format!(" and type='{}'", self.stream_type));
726 }
727 if !self.source_id.is_empty() {
728 q.push_str(&format!(" and source_id='{}'", self.source_id));
729 }
730 q.push_str(&format!(
731 " and channel_format='{}'",
732 format_name(self.format)
733 ));
734 q
735 }
736
737 pub fn is_recoverable(&self) -> bool {
742 !self.source_id.is_empty()
743 }
744}
745
746#[cfg(test)]
747mod recovery {
748 use super::*;
749
750 fn info() -> StreamInfo {
751 let mut i = StreamInfo::new("RcTest", "EEG", 4, Format::Float32, 200.0);
752 i.session_id = crate::SESSION_ID.into();
754 i.source_id = "rc_fixed_source".into();
755 i.uid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee".into();
756 i
757 }
758
759 #[test]
760 fn the_query_matches_the_shape_that_liblsl_builds() {
761 assert_eq!(
762 info().recovery_query(),
763 "channel_count='4' and name='RcTest' and type='EEG' \
764 and source_id='rc_fixed_source' and channel_format='float32'"
765 );
766 }
767
768 #[test]
769 fn the_query_leaves_out_the_rate() {
770 assert!(!info().recovery_query().contains("nominal_srate"));
773 }
774
775 #[test]
776 fn the_query_finds_the_same_stream_after_a_new_identifier() {
777 let before = info();
778 let mut after = info();
779 after.uid = "11111111-2222-3333-4444-555555555555".into();
780 assert!(after.matches(&before.recovery_query()));
783 assert_ne!(before.uid, after.uid);
784 }
785
786 #[test]
787 fn the_query_refuses_a_different_stream() {
788 let q = info().recovery_query();
789 let mut other = info();
790 other.name = "Something".into();
791 assert!(!other.matches(&q));
792
793 let mut wider = info();
794 wider.channel_count = 8;
795 assert!(!wider.matches(&q));
796
797 let mut retyped = info();
798 retyped.format = Format::Double64;
799 assert!(!retyped.matches(&q));
800 }
801
802 #[test]
803 fn a_stream_with_no_source_identifier_cannot_be_recovered() {
804 let mut i = info();
805 i.source_id = String::new();
806 assert!(!i.is_recoverable());
807 assert!(info().is_recoverable());
808 assert!(!i.recovery_query().contains("source_id"));
811 }
812}