1use 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
19pub const RELAY_DESC_TAG: &str = "labstream_relay";
22
23pub const DEFAULT_SUFFIX: &str = "-relay";
25
26#[derive(Debug, Clone)]
28pub struct RelayOptions {
29 pub name_suffix: String,
32 pub session_id: Option<String>,
35 pub history_limits: Option<HistoryLimits>,
38 pub buffer_samples: Option<i32>,
42 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
58pub 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
72pub 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 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
122pub 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 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 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 pub fn info(&self) -> &StreamInfo {
201 &self.outlet_info
202 }
203
204 pub fn source_uid(&self) -> &str {
206 &self.source_uid
207 }
208
209 pub fn source_name(&self) -> &str {
211 &self.source_name
212 }
213
214 pub fn forwarded(&self) -> u64 {
216 self.forwarded.load(Ordering::Relaxed)
217 }
218
219 pub fn is_running(&self) -> bool {
221 self.running.load(Ordering::SeqCst)
222 }
223
224 pub fn consumer_count(&self) -> usize {
226 self.outlet.consumer_count()
227 }
228
229 pub fn history_ram_bytes(&self) -> usize {
231 self.outlet.history_ram_bytes()
232 }
233
234 pub fn history_disk_bytes(&self) -> u64 {
236 self.outlet.history_disk_bytes()
237 }
238
239 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}