Skip to main content

Outlet

Struct Outlet 

Source
pub struct Outlet { /* private fields */ }
Expand description

A stream outlet.

Implementations§

Source§

impl Outlet

Source

pub fn new(info: StreamInfo) -> Result<Self>

Publish a stream.

The call binds a TCP port for the data and a UDP port for discovery and time probes, then starts one thread for each.

Examples found in repository?
examples/publish.rs (line 145)
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}
Source

pub fn new_blocking(info: StreamInfo) -> Result<Self>

Publish a stream that writes each sample before the push returns.

This is transp_sync_blocking (include/lsl/common.h:172). The outlet holds no queue, so a consumer that cannot keep up holds up the push instead of losing a sample.

The wire is the same. liblsl hands the socket to the blocking writer only after the headers and the test pattern have gone out (src/tcp_server.cpp:733), and the layout of a sample does not change (src/sync_serialization.h). A consumer cannot tell the two modes apart.

A stream of strings has no fixed width, and liblsl refuses it here (src/stream_outlet_impl.cpp:34-38).

Source

pub fn info(&self) -> &StreamInfo

The description that this outlet publishes.

Examples found in repository?
examples/publish.rs (line 169)
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}
Source

pub fn holds_multicast_port(&self) -> bool

True when the outlet holds the port that carries a multicast query.

A false value is not an error on its own. It means that another process on this machine holds the port, and that only a unicast query or a broadcast query reaches this outlet.

Examples found in repository?
examples/publish.rs (line 212)
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}
Source

pub fn consumer_count(&self) -> usize

The number of connected consumers.

Examples found in repository?
examples/publish.rs (line 260)
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}
Source

pub fn wait_for_consumers(&self, timeout: Duration) -> bool

Wait until at least one consumer is connected.

Source

pub fn push(&self, s: &Sample)

Send one sample to every connected consumer.

This never waits. A consumer whose queue is full loses its oldest sample, and every other consumer is unaffected. SPEC.md 8.7 and 8.8.

Examples found in repository?
examples/publish.rs (line 303)
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}
Source§

impl Outlet

Source

pub fn push_chunk_fast(&self, samples: &[Sample], timestamp: f64)

Send several samples that share one timestamp, with one lock.

The timestamps are the timestamps of Outlet::push_chunk. The only difference is the number of locks: this takes the set of consumers once for the whole block, and each consumer queue once. push_chunk takes both once for each sample.

A block of 500 samples to 2 consumers costs 3 locks here and 1500 locks there.

The blocking mode is not batched. That mode waits for each write on purpose, so a block gives no gain.

Source

pub fn push_chunk(&self, samples: &[Sample], timestamp: f64)

Send several samples that share one timestamp. SPEC.md 9.2.

The timestamp names the last sample. A stream with a rate counts backward from it, so the first sample is dated timestamp - (count - 1) / rate. Only that first sample carries a timestamp on the wire, and the rest carry the deduced tag.

An application that acquires a block and stamps it on arrival therefore gets the right time for every sample in the block.

Outlet::push_chunk_fast does the same with one lock for the block.

Examples found in repository?
examples/publish.rs (line 299)
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}

Trait Implementations§

Source§

impl Drop for Outlet

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl Forget for Outlet

§

impl Freeze for Outlet

§

impl Move for Outlet

§

impl RefUnwindSafe for Outlet

§

impl Send for Outlet

§

impl Sync for Outlet

§

impl Unpin for Outlet

§

impl UnsafeUnpin for Outlet

§

impl UnwindSafe for Outlet

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.