Skip to main content

labstream_net/
info.rs

1//! The stream description, and the query subset that a resolver sends.
2
3use labstream_wire::Format;
4
5/// The description of one stream.
6#[derive(Debug, Clone, PartialEq)]
7pub struct StreamInfo {
8    /// The stream name.
9    pub name: String,
10    /// The content type.
11    pub stream_type: String,
12    /// The channel count.
13    pub channel_count: u32,
14    /// The channel format.
15    pub format: Format,
16    /// The nominal rate. Zero means an irregular rate.
17    pub nominal_srate: f64,
18    /// The source identifier. An empty value blocks automatic recovery.
19    pub source_id: String,
20    /// The session identifier. A resolver query always tests this field.
21    pub session_id: String,
22    /// The host name of the sender.
23    pub hostname: String,
24    /// The stream instance identifier.
25    pub uid: String,
26    /// The clock reading at creation.
27    pub created_at: f64,
28    /// The address that the answer to a query came from.
29    ///
30    /// An outlet leaves this empty, and the resolver of the peer fills it in
31    /// from the sender of the answer (`src/resolve_attempt_udp.cpp:135-140`).
32    /// An inlet connects to this address, so a description with an empty one
33    /// can only be reached on the machine that published it.
34    pub v4address: String,
35    /// The IPv6 address that the answer came from. Same rule as
36    /// [`StreamInfo::v4address`].
37    pub v6address: String,
38    /// The TCP port that carries the data.
39    pub v4data_port: u16,
40    /// The UDP port that answers a query and a time probe.
41    pub v4service_port: u16,
42    /// The TCP port that carries the data over IPv6.
43    pub v6data_port: u16,
44    /// The UDP port that answers over IPv6.
45    pub v6service_port: u16,
46    /// The description tree.
47    ///
48    /// A discovery answer never carries this. It travels on the data port, in
49    /// answer to `LSL:fullinfo`. The node itself is the `<desc>` element, so
50    /// its children are what an application added.
51    pub desc: crate::desc::Node,
52    /// True when this description came from a document rather than from a
53    /// program.
54    ///
55    /// The two write an empty field differently. A program builds
56    /// `<v4address></v4address>`, because `write_xml` appends an empty text
57    /// node (`src/stream_info_impl.cpp:56`). A reader drops that text node, so
58    /// the same field writes back as `<v4address />`. SPEC.md 12.4.
59    ///
60    /// `HandleMetaData.cpp`, one of the example programs of liblsl, shows the
61    /// difference: it prints the document that an inlet received.
62    from_document: bool,
63}
64
65/// The format name that liblsl writes in a description.
66///
67/// `src/stream_info_impl.cpp` writes these exact words. A different word makes
68/// the stream unreadable to a real inlet.
69pub 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
82/// Read a format name.
83pub 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    /// Build a description with the usual values.
98    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            // The session identifier arrives when the stream is published, not
113            // when the description is built. `src/tcp_server.cpp:328` sets it
114            // from the configuration as the server starts, so a description
115            // that no outlet published reports an empty value.
116            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    /// Write the short description that a discovery answer carries.
132    ///
133    /// The field order and the number format follow the capture in
134    /// `captures/discover.json`. A real inlet reads this with pugixml, so it
135    /// needs valid XML and the exact field names.
136    pub fn to_shortinfo_xml(&self) -> String {
137        self.to_xml("\t<desc />\n")
138    }
139
140    /// Write the whole document, with the description tree.
141    ///
142    /// This is what a data port returns for `LSL:fullinfo`
143    /// (`src/tcp_server.cpp:508`), and what `lsl_get_xml` returns
144    /// (`src/lsl_streaminfo_c.cpp:63`). The only difference from the short form
145    /// is the content of `<desc>`.
146    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        // A reader drops an empty text node, so a description that came from a
156        // document writes an empty field as one empty tag. SPEC.md 12.4.
157        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    /// Read a short description.
191    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    /// Read a whole document, with the description tree.
222    ///
223    /// The checks and their order follow `read_xml`
224    /// (`src/stream_info_impl.cpp:99-155`). The text of the error is the text
225    /// that liblsl throws, because the C ABI shows it: a rejected document
226    /// leaves a blank description whose name reads `(invalid: TEXT)`.
227    /// `captures/desc/desc_nouid.name` holds one measured example.
228    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    /// The description as a tree, with the `<info>` element at the root.
285    ///
286    /// A query is evaluated against this (`src/stream_info_impl.cpp:214`). The
287    /// text of every field is the text that the same field carries on the
288    /// wire, so a query that names a number reads the same value that a peer
289    /// would read.
290    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    /// Test a query against this description.
319    ///
320    /// The query is XPath, the way liblsl reads it
321    /// (`src/stream_info_impl.cpp:214`). See [`crate::xpath`] for what the
322    /// reader covers and what it refuses.
323    pub fn matches(&self, query: &str) -> bool {
324        crate::xpath::matches(query, &self.document())
325    }
326
327    /// Return a copy of this description updated for an active `select/1`
328    /// channel subset and decimation factor (`docs/roadmap.md`, step 6).
329    ///
330    /// Updates `channel_count`, `nominal_srate`, and any `<desc><channels>`
331    /// `<channel>` elements to match `sel.channels` in order.
332    pub fn apply_selection(&self, sel: &labstream_proto::features::SelectParam) -> Self {
333        let mut out = self.clone();
334        out.channel_count = sel.output_channels(self.channel_count as usize) as u32;
335        out.nominal_srate = sel.output_srate(self.nominal_srate);
336        if !sel.channels.is_empty() {
337            if let Some(channels_node) = out.desc.child_mut("channels") {
338                let orig: Vec<crate::desc::Node> = channels_node
339                    .children
340                    .iter()
341                    .filter(|c| c.kind == crate::desc::Kind::Element && c.name == "channel")
342                    .cloned()
343                    .collect();
344                if !orig.is_empty() {
345                    let mut filtered = Vec::with_capacity(sel.channels.len());
346                    for &idx in &sel.channels {
347                        if let Some(ch) = orig.get(idx as usize) {
348                            filtered.push(ch.clone());
349                        }
350                    }
351                    channels_node
352                        .children
353                        .retain(|c| !(c.kind == crate::desc::Kind::Element && c.name == "channel"));
354                    channels_node.children.extend(filtered);
355                }
356            }
357        }
358        out
359    }
360
361    /// Store a calibrated device delay (and optional jitter RMS) in
362    /// `<desc><synchronization><offset_mean>` (`docs/roadmap.md`, step 15).
363    ///
364    /// `liblsl` tools and `LabRecorder` keep `<desc>` verbatim in XDF files.
365    pub fn set_device_delay(&mut self, delay_s: f64, rms_s: Option<f64>) {
366        self.set_device_delay_stats(delay_s, rms_s, None, None, None);
367    }
368
369    /// Store full device-delay calibration statistics in
370    /// `<desc><synchronization>` (`docs/roadmap.md`, step 15).
371    pub fn set_device_delay_stats(
372        &mut self,
373        mean_s: f64,
374        rms_s: Option<f64>,
375        median_s: Option<f64>,
376        p5_s: Option<f64>,
377        p95_s: Option<f64>,
378    ) {
379        if !mean_s.is_finite() {
380            return;
381        }
382        self.desc.children.retain(|c| c.name != "synchronization");
383        let sync = self.desc.append_child("synchronization");
384        sync.append_child_value("offset_mean", &format!("{mean_s:.6}"));
385        if let Some(v) = rms_s.filter(|x| x.is_finite()) {
386            sync.append_child_value("offset_rms", &format!("{v:.6}"));
387        }
388        if let Some(v) = median_s.filter(|x| x.is_finite()) {
389            sync.append_child_value("offset_median", &format!("{v:.6}"));
390        }
391        if let Some(v) = p5_s.filter(|x| x.is_finite()) {
392            sync.append_child_value("offset_5_percentile", &format!("{v:.6}"));
393        }
394        if let Some(v) = p95_s.filter(|x| x.is_finite()) {
395            sync.append_child_value("offset_95_percentile", &format!("{v:.6}"));
396        }
397    }
398
399    /// Read the calibrated device delay (in seconds) from
400    /// `<desc><synchronization><offset_mean>`, if present and finite.
401    pub fn device_delay(&self) -> Option<f64> {
402        let sync = self.desc.child("synchronization")?;
403        let text = sync.child_value_of("offset_mean").trim();
404        let val: f64 = text.parse().ok()?;
405        val.is_finite().then_some(val)
406    }
407
408    /// Read the calibrated device delay RMS jitter (in seconds) from
409    /// `<desc><synchronization><offset_rms>`, if present and finite.
410    pub fn device_delay_rms(&self) -> Option<f64> {
411        let sync = self.desc.child("synchronization")?;
412        let text = sync.child_value_of("offset_rms").trim();
413        let val: f64 = text.parse().ok()?;
414        val.is_finite().then_some(val)
415    }
416}
417
418/// Write a double the way liblsl writes one into a description.
419///
420/// `src/util/cast.cpp:9` builds the text with `setprecision(16)` and
421/// `showpoint` on a default stream. That is the general format with 16
422/// significant digits, and no trailing zero is removed. The rule:
423///
424/// * If the decimal exponent is below -4 or 16 and above, use the scientific
425///   form with 15 digits after the point.
426/// * If not, use the fixed form with `15 - exponent` digits after the point.
427///
428/// So a rate of 100 writes as `100.0000000000000` and a rate of 0 writes as
429/// `0.000000000000000`. Both are 16 significant digits, and both appear in
430/// `captures/desc/`.
431pub fn show_point_16(v: f64) -> String {
432    if v.is_nan() {
433        return "nan".to_string();
434    }
435    if v.is_infinite() {
436        return if v < 0.0 { "-inf" } else { "inf" }.to_string();
437    }
438    let sci = format!("{v:.15e}");
439    let (mantissa, exp_text) = match sci.split_once('e') {
440        Some(x) => x,
441        None => return sci,
442    };
443    let exp: i32 = exp_text.parse().unwrap_or(0);
444    if !(-4..16).contains(&exp) {
445        let sign = if exp < 0 { '-' } else { '+' };
446        return format!("{mantissa}e{sign}{:02}", exp.abs());
447    }
448    format!("{:.*}", (15 - exp) as usize, v)
449}
450
451/// Read a double the way `std::stod` reads one.
452///
453/// The reader takes the longest leading run that looks like a number and
454/// rejects text that starts with anything else. liblsl lets that rejection
455/// escape, and the whole description is then thrown away.
456fn stod(text: &str) -> Result<f64, String> {
457    let t = text.trim();
458    let mut end = 0;
459    for (i, c) in t.char_indices() {
460        let keep = c.is_ascii_digit()
461            || (i == 0 && (c == '-' || c == '+'))
462            || c == '.'
463            || c == 'e'
464            || c == 'E'
465            || ((c == '-' || c == '+')
466                && matches!(t.as_bytes().get(i - 1), Some(b'e') | Some(b'E')));
467        if !keep {
468            break;
469        }
470        end = i + c.len_utf8();
471    }
472    t[..end].parse().map_err(|_| "stod".to_string())
473}
474
475/// Read a whole number and hold it inside a range.
476///
477/// liblsl reads these fields with `std::stoi`, which stops at the first
478/// character that is not a digit. `100.0000000000000` therefore reads as 100
479/// and never throws. `get_bounded_child_val` then tests the range, and a zero
480/// maximum means no upper bound (`src/stream_info_impl.cpp:85`).
481fn bounded(text: &str, field: &str, min: i32, max: i32) -> Result<i32, String> {
482    let t = text.trim();
483    let digits: String = t
484        .char_indices()
485        .take_while(|(i, c)| c.is_ascii_digit() || (*i == 0 && (*c == '-' || *c == '+')))
486        .map(|(_, c)| c)
487        .collect();
488    let value: i32 = digits.parse().map_err(|_| "stoi".to_string())?;
489    if value < min || (max != 0 && value > max) {
490        let mut msg = format!("{field} must be >={min}");
491        if max != 0 {
492            msg.push_str(&format!(" and <={max}"));
493        }
494        return Err(msg);
495    }
496    Ok(value)
497}
498
499fn escape(s: &str) -> String {
500    s.replace('&', "&amp;")
501        .replace('<', "&lt;")
502        .replace('>', "&gt;")
503}
504
505fn tag<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
506    let open = format!("<{name}>");
507    let close = format!("</{name}>");
508    let a = xml.find(&open)? + open.len();
509    let b = xml[a..].find(&close)? + a;
510    Some(&xml[a..b])
511}
512
513/// The host name of this machine, or `unknown`.
514pub fn hostname() -> String {
515    std::fs::read_to_string("/proc/sys/kernel/hostname")
516        .map(|s| s.trim().to_string())
517        .unwrap_or_else(|_| "unknown".to_string())
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523
524    fn info() -> StreamInfo {
525        let mut i = StreamInfo::new("Probe", "EEG", 8, Format::Float32, 100.0);
526        // The outlet sets this when the stream is published.
527        i.session_id = crate::SESSION_ID.into();
528        i.uid = "25cfa701-e55b-4e42-8fc2-103bbd2f86b6".into();
529        i.source_id = "src".into();
530        i.hostname = "box".into();
531        i.v4data_port = 16572;
532        i.v4service_port = 16572;
533        i
534    }
535
536    #[test]
537    fn the_description_round_trips() {
538        let a = info();
539        let xml = a.to_shortinfo_xml();
540        let b = StreamInfo::from_shortinfo_xml(&xml).expect("a description");
541        assert_eq!(b.name, a.name);
542        assert_eq!(b.channel_count, a.channel_count);
543        assert_eq!(b.format, a.format);
544        assert_eq!(b.uid, a.uid);
545        assert_eq!(b.v4data_port, a.v4data_port);
546        assert!((b.nominal_srate - a.nominal_srate).abs() < 1e-9);
547    }
548
549    #[test]
550    fn the_query_that_liblsl_builds_matches() {
551        // `src/resolver_impl.cpp:66-73` builds exactly this shape.
552        let i = info();
553        assert!(i.matches("session_id='default' and name='Probe'"));
554        assert!(i.matches("session_id='default'"));
555        assert!(!i.matches("session_id='default' and name='Other'"));
556        assert!(!i.matches("session_id='other' and name='Probe'"));
557    }
558
559    #[test]
560    fn an_empty_query_matches_every_stream() {
561        assert!(info().matches(""));
562        assert!(info().matches("   "));
563    }
564
565    #[test]
566    fn a_query_beyond_equality_is_answered() {
567        // These once had to fail closed, because the matcher read only
568        // equality. The reader is XPath now, and the oracle answers all three.
569        let i = info();
570        assert!(i.matches("contains(name,'Pro')"));
571        assert!(i.matches("channel_count>4"));
572        assert!(i.matches("starts-with(type,'EE')"));
573    }
574
575    #[test]
576    fn a_value_with_a_space_survives_the_split() {
577        let mut i = info();
578        i.name = "My Stream and More".into();
579        assert!(i.matches("session_id='default' and name='My Stream and More'"));
580    }
581
582    #[test]
583    fn every_field_that_a_query_names_is_readable() {
584        let i = info();
585        for f in [
586            "name",
587            "type",
588            "source_id",
589            "session_id",
590            "hostname",
591            "uid",
592            "channel_format",
593            "channel_count",
594        ] {
595            // A bare name is true in XPath when the element exists.
596            assert!(i.matches(f), "the field {f} is missing from the document");
597        }
598    }
599
600    #[test]
601    fn the_format_names_match_liblsl() {
602        for (f, n) in [
603            (Format::Float32, "float32"),
604            (Format::Double64, "double64"),
605            (Format::String, "string"),
606            (Format::Int32, "int32"),
607            (Format::Int16, "int16"),
608            (Format::Int8, "int8"),
609            (Format::Int64, "int64"),
610        ] {
611            assert_eq!(format_name(f), n);
612            assert_eq!(format_from_name(n), Some(f));
613        }
614    }
615}
616
617#[cfg(test)]
618mod measured_xpath {
619    use super::*;
620
621    /// The queries that `oracle/xpath.py` measured against the oracle.
622    ///
623    /// The battery showed that liblsl supports every group of XPath 1.0. This
624    /// crate implements the conjunction of equalities that
625    /// `resolver_impl::build_query` emits, and it fails closed on the rest.
626    ///
627    /// These tests pin both halves. A later change that starts answering a
628    /// query outside the subset must be deliberate, because it changes what a
629    /// resolver sees.
630    fn info() -> StreamInfo {
631        let mut i = StreamInfo::new("XpTest", "EEG", 8, Format::Float32, 100.0);
632        // The outlet sets this when the stream is published.
633        i.session_id = crate::SESSION_ID.into();
634        i.uid = "25cfa701-e55b-4e42-8fc2-103bbd2f86b6".into();
635        i.source_id = "xp_src".into();
636        i
637    }
638
639    #[test]
640    fn the_subset_that_a_resolver_emits_is_answered() {
641        let i = info();
642        for q in [
643            "",
644            "session_id='default'",
645            "session_id='default' and name='XpTest'",
646            "name='XpTest'",
647            "type='EEG'",
648            "source_id='xp_src'",
649        ] {
650            assert!(i.matches(q), "the subset must answer {q:?}");
651        }
652        for q in [
653            "session_id='default' and name='Other'",
654            "name='Nothing'",
655            "type='EMG'",
656        ] {
657            assert!(!i.matches(q), "the subset must refuse {q:?}");
658        }
659    }
660
661    #[test]
662    fn every_shape_that_the_oracle_answers_is_answered_here() {
663        // `oracle/xpath.py` sends each of these to a real outlet and records
664        // the answer. Every one of them matches there, and every one of them
665        // used to be refused here.
666        let i = info();
667        for q in [
668            "contains(name,'XpT')",
669            "starts-with(name,'Xp')",
670            "string-length(name)>3",
671            "substring(name,1,2)='Xp'",
672            "concat(name,type)='XpTestEEG'",
673            "channel_count>4",
674            "number(channel_count)+1=9",
675            "//name='XpTest'",
676            "count(//name)=1",
677            "not(name='Nothing')",
678            "name='XpTest' or name='Nothing'",
679            "true()",
680        ] {
681            assert!(i.matches(q), "{q:?} must match, and the oracle answers it");
682        }
683    }
684
685    #[test]
686    fn a_malformed_query_matches_nothing() {
687        // The oracle behaves the same way: pugixml throws, liblsl catches and
688        // returns false (`src/stream_info_impl.cpp:239-241`).
689        let i = info();
690        for q in [
691            "in'va'lid",
692            "name=",
693            "and and and",
694            "name='XpTest'))",
695            "!!!",
696        ] {
697            assert!(!i.matches(q), "a malformed query must not match: {q:?}");
698        }
699    }
700}
701
702/// Flags that change how a buffer length is read. `include/lsl/common.h:156-172`.
703pub mod transport {
704    /// The default. The requested length is a count of seconds, or of hundreds
705    /// of samples when the stream carries no rate.
706    pub const DEFAULT: u32 = 0;
707    /// The requested length is a literal count of samples.
708    pub const BUFSIZE_SAMPLES: u32 = 1;
709    /// Divide the result by 1000.
710    pub const BUFSIZE_THOUSANDTHS: u32 = 2;
711}
712
713impl StreamInfo {
714    /// Convert a requested buffer length into a count of samples.
715    ///
716    /// This is `calc_transport_buf_samples` (`src/stream_info_impl.cpp:254-270`),
717    /// and liblsl runs it at the C boundary (`src/lsl_inlet_c.cpp:20`). The
718    /// wire only ever carries samples. SPEC.md 8.6.
719    ///
720    /// An implementation that skips this step builds a buffer wrong by a factor
721    /// of the rate. At 1000 Hz a request of 20 means 20,000 samples.
722    pub fn buffer_samples(&self, requested: i32, flags: u32) -> i32 {
723        if flags & transport::BUFSIZE_SAMPLES != 0 && flags & transport::BUFSIZE_THOUSANDTHS != 0 {
724            // liblsl throws here. A caller that asks for both gets the literal
725            // reading, which is the safer of the two.
726            return requested.max(1);
727        }
728        let mut samples: i64 = if flags & transport::BUFSIZE_SAMPLES != 0 {
729            requested as i64
730        } else if self.nominal_srate == 0.0 {
731            requested as i64 * 100
732        } else {
733            (self.nominal_srate * requested as f64) as i64
734        };
735        if flags & transport::BUFSIZE_THOUSANDTHS != 0 {
736            samples /= 1000;
737        }
738        if samples > i32::MAX as i64 {
739            return i32::MAX;
740        }
741        if samples > 0 {
742            samples as i32
743        } else {
744            1
745        }
746    }
747}
748
749#[cfg(test)]
750mod buffer_length {
751    use super::*;
752
753    fn info(srate: f64) -> StreamInfo {
754        StreamInfo::new("B", "T", 2, Format::Float32, srate)
755    }
756
757    #[test]
758    fn a_rate_makes_the_request_a_count_of_seconds() {
759        // The trap from SPEC.md 8.6. A request of 20 at 1000 Hz is 20,000.
760        assert_eq!(info(1000.0).buffer_samples(20, transport::DEFAULT), 20_000);
761        assert_eq!(info(100.0).buffer_samples(360, transport::DEFAULT), 36_000);
762    }
763
764    #[test]
765    fn no_rate_multiplies_by_one_hundred() {
766        assert_eq!(info(0.0).buffer_samples(1, transport::DEFAULT), 100);
767        assert_eq!(info(0.0).buffer_samples(6, transport::DEFAULT), 600);
768    }
769
770    #[test]
771    fn the_samples_flag_takes_the_value_as_it_stands() {
772        assert_eq!(
773            info(1000.0).buffer_samples(20, transport::BUFSIZE_SAMPLES),
774            20
775        );
776        assert_eq!(info(0.0).buffer_samples(20, transport::BUFSIZE_SAMPLES), 20);
777    }
778
779    #[test]
780    fn the_thousandths_flag_divides() {
781        assert_eq!(
782            info(1000.0).buffer_samples(20_000, transport::BUFSIZE_THOUSANDTHS),
783            20_000
784        );
785    }
786
787    #[test]
788    fn the_result_never_falls_below_one() {
789        assert_eq!(info(0.001).buffer_samples(1, transport::DEFAULT), 1);
790        assert_eq!(info(100.0).buffer_samples(0, transport::DEFAULT), 1);
791        assert_eq!(info(100.0).buffer_samples(-5, transport::DEFAULT), 1);
792    }
793}
794
795impl StreamInfo {
796    /// The query that an inlet uses to find a stream again after it is lost.
797    ///
798    /// `src/inlet_connection.cpp:154-173`. The fields are the ones that survive
799    /// a restart of the source. A stream keeps its name, its type, its source
800    /// identifier, its channel count, and its channel format. It receives a new
801    /// instance identifier.
802    ///
803    /// The nominal rate is left out on purpose. liblsl explains why in a
804    /// comment: a rate written as text and read back is often not the same
805    /// number, and a resolver then never finds the stream.
806    ///
807    /// The session identifier is also left out, unlike the query that a plain
808    /// resolve builds (`src/resolver_impl.cpp:66-73`).
809    pub fn recovery_query(&self) -> String {
810        let mut q = format!("channel_count='{}'", self.channel_count);
811        if !self.name.is_empty() {
812            q.push_str(&format!(" and name='{}'", self.name));
813        }
814        if !self.stream_type.is_empty() {
815            q.push_str(&format!(" and type='{}'", self.stream_type));
816        }
817        if !self.source_id.is_empty() {
818            q.push_str(&format!(" and source_id='{}'", self.source_id));
819        }
820        q.push_str(&format!(
821            " and channel_format='{}'",
822            format_name(self.format)
823        ));
824        q
825    }
826
827    /// True when this stream can be found again after its source restarts.
828    ///
829    /// A stream with no source identifier cannot. liblsl warns about it at
830    /// connection time (`src/inlet_connection.cpp:40`).
831    pub fn is_recoverable(&self) -> bool {
832        !self.source_id.is_empty()
833    }
834}
835
836#[cfg(test)]
837mod recovery {
838    use super::*;
839
840    fn info() -> StreamInfo {
841        let mut i = StreamInfo::new("RcTest", "EEG", 4, Format::Float32, 200.0);
842        // The outlet sets this when the stream is published.
843        i.session_id = crate::SESSION_ID.into();
844        i.source_id = "rc_fixed_source".into();
845        i.uid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee".into();
846        i
847    }
848
849    #[test]
850    fn the_query_matches_the_shape_that_liblsl_builds() {
851        assert_eq!(
852            info().recovery_query(),
853            "channel_count='4' and name='RcTest' and type='EEG' \
854             and source_id='rc_fixed_source' and channel_format='float32'"
855        );
856    }
857
858    #[test]
859    fn the_query_leaves_out_the_rate() {
860        // A rate written as text and read back is often a different number.
861        // liblsl leaves it out for that reason.
862        assert!(!info().recovery_query().contains("nominal_srate"));
863    }
864
865    #[test]
866    fn the_query_finds_the_same_stream_after_a_new_identifier() {
867        let before = info();
868        let mut after = info();
869        after.uid = "11111111-2222-3333-4444-555555555555".into();
870        // The restarted stream carries a new instance identifier and every
871        // other field is the same.
872        assert!(after.matches(&before.recovery_query()));
873        assert_ne!(before.uid, after.uid);
874    }
875
876    #[test]
877    fn the_query_refuses_a_different_stream() {
878        let q = info().recovery_query();
879        let mut other = info();
880        other.name = "Something".into();
881        assert!(!other.matches(&q));
882
883        let mut wider = info();
884        wider.channel_count = 8;
885        assert!(!wider.matches(&q));
886
887        let mut retyped = info();
888        retyped.format = Format::Double64;
889        assert!(!retyped.matches(&q));
890    }
891
892    #[test]
893    fn a_stream_with_no_source_identifier_cannot_be_recovered() {
894        let mut i = info();
895        i.source_id = String::new();
896        assert!(!i.is_recoverable());
897        assert!(info().is_recoverable());
898        // The query then carries no source identifier either, so it can match
899        // more than one stream.
900        assert!(!i.recovery_query().contains("source_id"));
901    }
902}