Skip to main content

labstream_net/
relay.rs

1//! Local-to-network LSL stream relay (`docs/roadmap.md`, step 4).
2//!
3//! A `liblsl` outlet does not speak `seq/1`, `resume/1`, `dgram/1`, or
4//! store-and-forward. [`StreamRelay`] attaches to an existing LSL outlet (for
5//! example a `liblsl` device driver on the same machine) and republishes its
6//! description, sample bits, and timestamps through a `labstream` [`Outlet`].
7//! Downstream `labstream` inlets then cross the bad link with all negotiated
8//! features active.
9
10use crate::desc::{Kind, Node};
11use crate::history::HistoryLimits;
12use crate::{read_fullinfo, Inlet, Outlet, StreamInfo};
13use labstream_wire::PackedSample;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use std::sync::Arc;
16use std::thread::JoinHandle;
17use std::time::Duration;
18
19/// XML tag appended to `<desc>` of a relayed stream so an inlet can tell a
20/// relayed stream from its source stream even when the names match.
21pub const RELAY_DESC_TAG: &str = "labstream_relay";
22
23/// Default suffix appended to relayed stream names and `source_id` values.
24pub const DEFAULT_SUFFIX: &str = "-relay";
25
26/// Options for [`StreamRelay::start`].
27#[derive(Debug, Clone)]
28pub struct RelayOptions {
29    /// Suffix appended to the published stream name (default `"-relay"`).
30    /// Pass an empty string to keep the original stream name.
31    pub name_suffix: String,
32    /// Optional session identifier override for the relayed outlet.
33    /// `None` keeps the source stream session (or active configuration).
34    pub session_id: Option<String>,
35    /// Optional `resume` and disk store-and-forward limits for the relayed
36    /// outlet. `None` uses the active configuration (`Config::history_limits`).
37    pub history_limits: Option<HistoryLimits>,
38    /// Input buffer capacity on the relay inlet, in samples.
39    /// `None` picks 360 s for regular streams and 3600 samples for irregular
40    /// streams.
41    pub buffer_samples: Option<i32>,
42    /// Timeout for initial connection and `LSL:fullinfo` fetch.
43    pub open_timeout: Duration,
44}
45
46impl Default for RelayOptions {
47    fn default() -> Self {
48        RelayOptions {
49            name_suffix: DEFAULT_SUFFIX.to_string(),
50            session_id: None,
51            history_limits: None,
52            buffer_samples: None,
53            open_timeout: Duration::from_secs(5),
54        }
55    }
56}
57
58/// True when `info` describes a stream published by a `labstream` relay.
59///
60/// Checks both the `<labstream_relay>` element in `<desc>` (present on
61/// `LSL:fullinfo`) and the `"-relay"` suffix on `source_id` (present on
62/// short discovery answers too).
63pub fn is_relayed(info: &StreamInfo) -> bool {
64    let has_tag = info
65        .desc
66        .children
67        .iter()
68        .any(|c| c.kind == Kind::Element && c.name == RELAY_DESC_TAG);
69    has_tag || info.source_id.ends_with(DEFAULT_SUFFIX)
70}
71
72/// Build the relayed [`StreamInfo`] from a full source description.
73///
74/// Preserves `stream_type`, `channel_count`, `format`, `nominal_srate`, and
75/// every existing `<desc>` child node, clears `uid` so the relay outlet gets
76/// its own instance identifier, updates `name` and `source_id`, and appends a
77/// `<labstream_relay>` metadata element to `<desc>`.
78pub fn build_relayed_info(source: &StreamInfo, opts: &RelayOptions) -> StreamInfo {
79    let mut out = source.clone();
80    out.name = format!("{}{}", source.name, opts.name_suffix);
81    out.uid.clear();
82    out.v4address.clear();
83    out.v4data_port = 0;
84    out.v4service_port = 0;
85    out.v6address.clear();
86    out.v6data_port = 0;
87    out.v6service_port = 0;
88    out.created_at = 0.0;
89    out.hostname = crate::info::hostname();
90    if let Some(sess) = &opts.session_id {
91        out.session_id = sess.clone();
92    }
93    out.source_id = if source.source_id.is_empty() {
94        format!("{}{}", source.uid, DEFAULT_SUFFIX)
95    } else if source.source_id.ends_with(DEFAULT_SUFFIX) {
96        source.source_id.clone()
97    } else {
98        format!("{}{}", source.source_id, DEFAULT_SUFFIX)
99    };
100
101    // Append `<labstream_relay>` marker without altering any existing `<desc>` children.
102    let mut marker = Node::element(RELAY_DESC_TAG);
103    for (tag, val) in [
104        ("source_uid", source.uid.as_str()),
105        ("source_name", source.name.as_str()),
106        ("source_id", source.source_id.as_str()),
107        ("source_hostname", source.hostname.as_str()),
108    ] {
109        let mut child = Node::element(tag);
110        if !val.is_empty() {
111            child.children.push(Node::text(val));
112        }
113        marker.children.push(child);
114    }
115    if out.desc.name.is_empty() {
116        out.desc.name = "desc".to_string();
117    }
118    out.desc.children.push(marker);
119    out
120}
121
122/// A live relay forwarding one source LSL stream into a `labstream` [`Outlet`].
123pub struct StreamRelay {
124    source_uid: String,
125    source_name: String,
126    outlet_info: StreamInfo,
127    outlet: Arc<Outlet>,
128    forwarded: Arc<AtomicU64>,
129    stop: Arc<AtomicBool>,
130    running: Arc<AtomicBool>,
131    worker: Option<JoinHandle<()>>,
132}
133
134impl StreamRelay {
135    /// Attach to `source`, fetch its full `<desc>`, open a `labstream`
136    /// [`Outlet`], and start forwarding packed samples with exact timestamps.
137    pub fn start(source: &StreamInfo, opts: RelayOptions) -> std::io::Result<StreamRelay> {
138        let full = read_fullinfo(source, opts.open_timeout).unwrap_or_else(|_| source.clone());
139        let buffer_samples = opts.buffer_samples.unwrap_or_else(|| {
140            if full.nominal_srate > 0.0 {
141                ((360.0 * full.nominal_srate).ceil() as i32).max(1)
142            } else {
143                3600
144            }
145        });
146        let mut inlet = Inlet::open_recovering(source, opts.open_timeout, buffer_samples)?;
147        // Never alter source timestamps: pass raw values bit-for-bit.
148        inlet.set_postprocessing(0);
149
150        let relayed_desc = build_relayed_info(&full, &opts);
151        let limits = opts
152            .history_limits
153            .unwrap_or_else(|| crate::config::get().history_limits());
154        let outlet = Arc::new(Outlet::new_with_limits(relayed_desc, limits)?);
155        let outlet_info = outlet.info().clone();
156
157        let forwarded = Arc::new(AtomicU64::new(0));
158        let stop = Arc::new(AtomicBool::new(false));
159        let running = Arc::new(AtomicBool::new(true));
160
161        let out_ref = Arc::clone(&outlet);
162        let fwd_ref = Arc::clone(&forwarded);
163        let stop_ref = Arc::clone(&stop);
164        let run_ref = Arc::clone(&running);
165
166        let worker = std::thread::spawn(move || {
167            let mut batch: Vec<PackedSample> = Vec::with_capacity(256);
168            while !stop_ref.load(Ordering::Relaxed) {
169                batch.clear();
170                match inlet.pull_chunk_packed(&mut batch, 1024, Duration::from_millis(50)) {
171                    Ok(0) => {
172                        if inlet.is_finished() {
173                            break;
174                        }
175                    }
176                    Ok(n) => {
177                        let to_push = std::mem::take(&mut batch);
178                        out_ref.push_samples_packed(to_push);
179                        fwd_ref.fetch_add(n as u64, Ordering::Relaxed);
180                    }
181                    Err(_) => break,
182                }
183            }
184            run_ref.store(false, Ordering::SeqCst);
185        });
186
187        Ok(StreamRelay {
188            source_uid: source.uid.clone(),
189            source_name: source.name.clone(),
190            outlet_info,
191            outlet,
192            forwarded,
193            stop,
194            running,
195            worker: Some(worker),
196        })
197    }
198
199    /// Description published by the relay outlet.
200    pub fn info(&self) -> &StreamInfo {
201        &self.outlet_info
202    }
203
204    /// Instance identifier (`uid`) of the source stream being relayed.
205    pub fn source_uid(&self) -> &str {
206        &self.source_uid
207    }
208
209    /// Name of the source stream being relayed.
210    pub fn source_name(&self) -> &str {
211        &self.source_name
212    }
213
214    /// Total number of samples forwarded so far.
215    pub fn forwarded(&self) -> u64 {
216        self.forwarded.load(Ordering::Relaxed)
217    }
218
219    /// True while the relay forwarding thread is running.
220    pub fn is_running(&self) -> bool {
221        self.running.load(Ordering::SeqCst)
222    }
223
224    /// Number of downstream consumers connected to the relay outlet.
225    pub fn consumer_count(&self) -> usize {
226        self.outlet.consumer_count()
227    }
228
229    /// Bytes held by the relay outlet's `resume` history in RAM.
230    pub fn history_ram_bytes(&self) -> usize {
231        self.outlet.history_ram_bytes()
232    }
233
234    /// Bytes held by the relay outlet's `resume` history on disk.
235    pub fn history_disk_bytes(&self) -> u64 {
236        self.outlet.history_disk_bytes()
237    }
238
239    /// Signal the relay to stop and join its worker thread.
240    pub fn stop(&mut self) {
241        self.stop.store(true, Ordering::SeqCst);
242        if let Some(h) = self.worker.take() {
243            let _ = h.join();
244        }
245    }
246}
247
248impl Drop for StreamRelay {
249    fn drop(&mut self) {
250        self.stop();
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use labstream_wire::Format;
258
259    #[test]
260    fn build_relayed_info_preserves_desc_and_marks_stream_as_relayed() {
261        let mut src = StreamInfo::new("BioSemi", "EEG", 8, Format::Float32, 512.0);
262        src.uid = "orig-uid-123".to_string();
263        src.source_id = "biosemi-01".to_string();
264        let mut chs = Node::element("channels");
265        let mut ch0 = Node::element("channel");
266        let mut lbl = Node::element("label");
267        lbl.children.push(Node::text("Fp1"));
268        ch0.children.push(lbl);
269        chs.children.push(ch0);
270        src.desc.name = "desc".to_string();
271        src.desc.children.push(chs);
272
273        assert!(!is_relayed(&src));
274
275        let relayed = build_relayed_info(&src, &RelayOptions::default());
276        assert!(is_relayed(&relayed));
277        assert_eq!(relayed.name, "BioSemi-relay");
278        assert_eq!(relayed.source_id, "biosemi-01-relay");
279        assert!(relayed.uid.is_empty(), "outlet generates fresh uid");
280        assert_eq!(relayed.stream_type, "EEG");
281        assert_eq!(relayed.channel_count, 8);
282        assert_eq!(relayed.format, Format::Float32);
283        assert_eq!(relayed.nominal_srate, 512.0);
284        assert!(relayed.desc.children.iter().any(|c| c.name == "channels"));
285        assert!(relayed
286            .desc
287            .children
288            .iter()
289            .any(|c| c.name == RELAY_DESC_TAG));
290    }
291}