Skip to main content

publish/
publish.rs

1//! Publish a stream that another machine can find and record.
2//!
3//! This uses `labstream-net` directly, so no C ABI is on the path. Run it on one
4//! machine and open LabRecorder on another.
5//!
6//! ```text
7//! cargo run --release -p labstream-net --example publish -- --name RustTest
8//! ```
9//!
10//! The signal is built from the sample number, so a recording can be read back
11//! and tested. Channel `k` carries a sine wave of `k + 1` Hz. The last channel
12//! carries the sample number itself, which shows a gap at once.
13
14use labstream_net::{Outlet, StreamInfo};
15use labstream_wire::{Format, Sample, Value};
16use std::time::{Duration, Instant};
17
18struct Args {
19    name: String,
20    stream_type: String,
21    channels: usize,
22    rate: f64,
23    seconds: f64,
24    chunk: usize,
25    markers: bool,
26    /// A word that separates one publisher from another on the same network.
27    tag: String,
28}
29
30fn parse() -> Args {
31    let mut a = Args {
32        name: "RustTest".to_string(),
33        stream_type: "EEG".to_string(),
34        channels: 8,
35        rate: 100.0,
36        seconds: 0.0,
37        chunk: 1,
38        markers: true,
39        tag: String::new(),
40    };
41    let raw: Vec<String> = std::env::args().collect();
42    let mut i = 1;
43    while i + 1 < raw.len() {
44        let (k, v) = (raw[i].as_str(), raw[i + 1].as_str());
45        match k {
46            "--name" => a.name = v.to_string(),
47            "--type" => a.stream_type = v.to_string(),
48            "--channels" => a.channels = v.parse().unwrap_or(8),
49            "--rate" => a.rate = v.parse().unwrap_or(100.0),
50            // Zero means no limit.
51            "--seconds" => a.seconds = v.parse().unwrap_or(0.0),
52            "--chunk" => a.chunk = v.parse().unwrap_or(1),
53            "--markers" => a.markers = v != "0",
54            "--tag" => a.tag = v.to_string(),
55            other => {
56                eprintln!("unknown option {other}");
57                std::process::exit(2);
58            }
59        }
60        i += 2;
61    }
62    a
63}
64
65/// The marker for one whole second of the signal, if there is one.
66///
67/// A marker stream carries no rate, so it holds an event and not a sample.
68/// This sends one at each whole second, which is where the sine of channel one
69/// crosses zero on its way up. A plot then shows each marker on a crossing,
70/// and an alignment error is visible without any measurement.
71fn marker_for(n: u64, rate: f64) -> Option<String> {
72    let per_second = rate.max(1.0) as u64;
73    if n % per_second != 0 {
74        return None;
75    }
76    let second = n / per_second;
77    Some(if second % 5 == 0 {
78        format!("burst {second}")
79    } else {
80        format!("tick {second}")
81    })
82}
83
84/// The label of one channel. LabRecorder writes these into the recording.
85fn label(k: usize) -> String {
86    const NAMES: [&str; 8] = ["Fp1", "Fp2", "C3", "C4", "P3", "P4", "O1", "O2"];
87    match NAMES.get(k) {
88        Some(n) => n.to_string(),
89        None => format!("Ch{}", k + 1),
90    }
91}
92
93/// Add the tag to a name, when there is one.
94///
95/// The tag separates one publisher from another. With it, the three modes of
96/// `oracle/labrecorder.sh` can run at the same time, and a recorder shows
97/// which library sent which stream.
98fn tagged(base: &str, tag: &str) -> String {
99    if tag.is_empty() {
100        base.to_string()
101    } else {
102        format!("{base}-{tag}")
103    }
104}
105
106fn main() {
107    let a = parse();
108    let stream_name = tagged(&a.name, &a.tag);
109    let marker_name = tagged(&format!("{}-Markers", a.name), &a.tag);
110    let suffix = if a.tag.is_empty() {
111        String::new()
112    } else {
113        format!("_{}", a.tag)
114    };
115
116    let mut info = StreamInfo::new(
117        &stream_name,
118        &a.stream_type,
119        a.channels as u32,
120        Format::Float32,
121        a.rate,
122    );
123    // A source identifier lets a consumer find the stream again after a
124    // restart. Without one, no recovery is possible. SPEC.md 10.1.
125    //
126    // The identifier and the tree below match `oracle/publish.c` exactly, so
127    // the three publishers of `oracle/labrecorder.sh` describe one stream and
128    // a plot of one can be compared with a plot of another.
129    info.source_id = format!("{}_publish{suffix}", a.name);
130
131    {
132        let chns = info.desc.append_child("channels");
133        for k in 0..a.channels {
134            let c = chns.append_child("channel");
135            c.append_child_value("label", &label(k));
136            c.append_child_value("unit", "microvolts");
137            c.append_child_value("type", &a.stream_type);
138        }
139    }
140    info.desc
141        .append_child_value("manufacturer", "conformance publisher");
142    let acq = info.desc.append_child("acquisition");
143    acq.append_child_value("model", "publish example");
144
145    let outlet = match Outlet::new(info) {
146        Ok(o) => o,
147        Err(e) => {
148            eprintln!("cannot publish: {e}");
149            std::process::exit(1);
150        }
151    };
152
153    // A marker stream is a second stream: one channel of text, and no rate.
154    // A recorder treats it as events rather than as a signal.
155    let markers = if a.markers {
156        let mut m = StreamInfo::new(&marker_name, "Markers", 1, Format::String, 0.0);
157        m.source_id = format!("{}_markers{suffix}", a.name);
158        match Outlet::new(m) {
159            Ok(o) => Some(o),
160            Err(e) => {
161                eprintln!("cannot publish the markers: {e}");
162                None
163            }
164        }
165    } else {
166        None
167    };
168
169    let published = outlet.info();
170    println!("=== the stream is published");
171    println!("  name          {}", published.name);
172    println!("  type          {}", published.stream_type);
173    println!("  channels      {} float32", published.channel_count);
174    println!("  rate          {} Hz", published.nominal_srate);
175    println!("  source id     {}", published.source_id);
176    println!("  session       {}", published.session_id);
177    println!("  host          {}", published.hostname);
178    println!("  uid           {}", published.uid);
179    let cfg = labstream_net::config::get();
180    let port = |n: u16| {
181        if n == 0 {
182            "none".to_string()
183        } else {
184            n.to_string()
185        }
186    };
187    println!(
188        "  IPv4          data {}  service {}",
189        port(published.v4data_port),
190        port(published.v4service_port)
191    );
192    println!(
193        "  IPv6          data {}  service {}",
194        port(published.v6data_port),
195        port(published.v6service_port)
196    );
197    let which = match (cfg.allow_ipv4, cfg.allow_ipv6) {
198        (true, true) => "IPv4 and IPv6",
199        (true, false) => "IPv4 only",
200        (false, true) => "IPv6 only. A consumer has no other way to reach this stream.",
201        (false, false) => "none. Nothing can reach this stream.",
202    };
203    println!("  protocols     {which}");
204    match &markers {
205        Some(m) => {
206            println!(
207                "  marker stream {}  ({})",
208                m.info().name,
209                m.info().source_id
210            );
211            println!("                one every second, on a zero crossing of channel one");
212            if !m.holds_multicast_port() {
213                println!("  WARNING: the marker stream does not hold the multicast port.");
214            }
215        }
216        None => println!("  marker stream none"),
217    }
218
219    // A query from another machine arrives by multicast or by broadcast. The
220    // outlet joins each group on each local address, so this list is the one
221    // that decides whether another machine can find the stream at all.
222    let addresses = labstream_net::local_ipv4_addresses();
223    println!("\n=== the addresses that carry a query");
224    if addresses.is_empty() {
225        println!("  none found. Another machine will not see this stream.");
226    }
227    for addr in &addresses {
228        println!("  {addr}");
229    }
230    println!("  multicast port {}", cfg.multicast_port);
231    println!("  groups         {}", cfg.multicast_addresses.join(", "));
232    println!("  configuration  {}", cfg.source);
233    if outlet.holds_multicast_port() {
234        println!("  multicast port held by this outlet");
235    } else {
236        println!(
237            "  WARNING: port {} is held by another process on this machine.",
238            cfg.multicast_port
239        );
240        println!("  A multicast query will not reach this outlet. Stop the other");
241        println!("  program, or expect the other machine to find nothing.");
242    }
243
244    println!("\n=== open LabRecorder on the other machine and press Update");
245    println!("  The count below rises when a recorder links the stream.\n");
246
247    let period = if a.rate > 0.0 { 1.0 / a.rate } else { 0.01 };
248    let start = Instant::now();
249    let mut n: u64 = 0;
250    let mut consumers = 0;
251    let mut reported = Instant::now() - Duration::from_secs(10);
252    let mut block: Vec<Sample> = Vec::new();
253
254    loop {
255        if a.seconds > 0.0 && start.elapsed().as_secs_f64() >= a.seconds {
256            println!("\n{n} samples sent. Stopping.");
257            return;
258        }
259
260        let now = outlet.consumer_count();
261        if now != consumers {
262            println!(
263                "  consumers {consumers} -> {now}   after {:.1} s, {n} samples",
264                start.elapsed().as_secs_f64()
265            );
266            consumers = now;
267        }
268        if reported.elapsed() >= Duration::from_secs(5) {
269            println!(
270                "  {:.0} s, {n} samples, {consumers} consumer(s)",
271                start.elapsed().as_secs_f64()
272            );
273            reported = Instant::now();
274        }
275
276        // The value of a channel comes from the sample number, so a recording
277        // can be tested later. The last channel holds the number itself.
278        let t = n as f64 / a.rate.max(1.0);
279        let values: Vec<Value> = (0..a.channels)
280            .map(|k| {
281                if k + 1 == a.channels {
282                    Value::F32(n as f32)
283                } else {
284                    let hz = (k + 1) as f64;
285                    Value::F32((100.0 * (2.0 * std::f64::consts::PI * hz * t).sin()) as f32)
286                }
287            })
288            .collect();
289        let sample = Sample {
290            // A timestamp of zero means the current clock. SPEC.md 8.3.
291            timestamp: 0.0,
292            values,
293        };
294
295        if a.chunk > 1 {
296            block.push(sample);
297            if block.len() == a.chunk {
298                // The timestamp names the last sample of the chunk. SPEC.md 9.2.
299                outlet.push_chunk(&block, 0.0);
300                block.clear();
301            }
302        } else {
303            outlet.push(&sample);
304        }
305
306        // The marker carries the same rule for its timestamp as the sample: a
307        // value of zero means the current clock. The two therefore sit within
308        // a fraction of one period of each other. SPEC.md 8.3.
309        if let (Some(m), Some(text)) = (&markers, marker_for(n, a.rate)) {
310            m.push(&Sample {
311                timestamp: 0.0,
312                values: vec![Value::Str(text.into_bytes())],
313            });
314        }
315        n += 1;
316
317        std::thread::sleep(Duration::from_secs_f64(period));
318    }
319}