Skip to main content

labstream_net/
outlet.rs

1//! The outlet: a discovery responder and a TCP feed server.
2
3use crate::info::StreamInfo;
4use crate::queue::Fanout;
5use crate::{clock, config};
6use labstream_proto::discovery;
7use labstream_proto::header::parse_block;
8use labstream_proto::negotiate::{negotiate, FeedRequest, Outcome, ServerStream, LITTLE};
9use labstream_proto::timesync;
10use labstream_wire::{Codec, Sample, TEST_PATTERN_OFFSETS};
11use std::io::{Read, Write};
12use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket};
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15
16/// How fast this side converts a byte order.
17///
18/// liblsl measures this with a benchmark. A fixed value keeps the negotiation
19/// deterministic, and the value never travels as a claim about speed. It only
20/// decides which side converts. SPEC.md 5.2.
21const ENDIAN_PERFORMANCE: f64 = 1000.0;
22
23struct Shared {
24    info: Mutex<StreamInfo>,
25    /// One queue per connected consumer. SPEC.md 8.8.
26    fanout: Fanout,
27    /// The consumers of a blocking outlet, which holds no queue at all.
28    sync: Mutex<Vec<SyncConsumer>>,
29    /// True when this outlet writes each sample before the push returns.
30    sync_mode: bool,
31    stop: Mutex<bool>,
32}
33
34/// One consumer of a blocking outlet.
35///
36/// A blocking outlet holds the socket rather than a queue. Each consumer keeps
37/// its own codec, because two consumers can agree on different byte orders.
38struct SyncConsumer {
39    stream: TcpStream,
40    codec: Codec,
41}
42
43/// A stream outlet.
44pub struct Outlet {
45    shared: Arc<Shared>,
46    info: StreamInfo,
47    /// True when the outlet holds the port that carries a multicast query.
48    ///
49    /// Another process on this machine can already hold it. The outlet then
50    /// answers a unicast query and a broadcast query, and never sees a
51    /// multicast query. A consumer on another machine can therefore miss the
52    /// stream. SPEC.md 1.1.
53    multicast_bound: bool,
54}
55
56impl Outlet {
57    /// Publish a stream.
58    ///
59    /// The call binds a TCP port for the data and a UDP port for discovery and
60    /// time probes, then starts one thread for each.
61    pub fn new(info: StreamInfo) -> std::io::Result<Self> {
62        Outlet::with_flags(info, false)
63    }
64
65    /// Publish a stream that writes each sample before the push returns.
66    ///
67    /// This is `transp_sync_blocking` (`include/lsl/common.h:172`). The outlet
68    /// holds no queue, so a consumer that cannot keep up holds up the push
69    /// instead of losing a sample.
70    ///
71    /// **The wire is the same.** liblsl hands the socket to the blocking writer
72    /// only after the headers and the test pattern have gone out
73    /// (`src/tcp_server.cpp:733`), and the layout of a sample does not change
74    /// (`src/sync_serialization.h`). A consumer cannot tell the two modes
75    /// apart.
76    ///
77    /// A stream of strings has no fixed width, and liblsl refuses it here
78    /// (`src/stream_outlet_impl.cpp:34-38`).
79    pub fn new_blocking(info: StreamInfo) -> std::io::Result<Self> {
80        if info.format == labstream_wire::Format::String {
81            return Err(std::io::Error::other(
82                "Synchronous (zero-copy) mode is not supported for string-format streams",
83            ));
84        }
85        Outlet::with_flags(info, true)
86    }
87
88    fn with_flags(mut info: StreamInfo, sync_mode: bool) -> std::io::Result<Self> {
89        let cfg = config::get();
90        // One stack for each protocol that the configuration allows, the way
91        // `stream_outlet_impl::instantiate_stack` builds them.
92        let tcp4 = if cfg.allow_ipv4 {
93            bind_tcp_in_range(V4).ok()
94        } else {
95            None
96        };
97        let udp4 = if cfg.allow_ipv4 {
98            bind_udp_in_range(V4).ok()
99        } else {
100            None
101        };
102        let tcp6 = if cfg.allow_ipv6 {
103            bind_tcp_in_range(V6).ok()
104        } else {
105            None
106        };
107        let udp6 = if cfg.allow_ipv6 {
108            bind_udp_in_range(V6).ok()
109        } else {
110            None
111        };
112        if tcp4.is_none() && tcp6.is_none() {
113            return Err(std::io::Error::other(
114                "neither the IPv4 nor the IPv6 stack could be built",
115            ));
116        }
117        if let Some(t) = &tcp4 {
118            info.v4data_port = t.local_addr()?.port();
119        }
120        if let Some(u) = &udp4 {
121            info.v4service_port = u.local_addr()?.port();
122        }
123        if let Some(t) = &tcp6 {
124            info.v6data_port = t.local_addr()?.port();
125        }
126        if let Some(u) = &udp6 {
127            info.v6service_port = u.local_addr()?.port();
128        }
129        if info.uid.is_empty() {
130            info.uid = crate::make_uid();
131        }
132        info.created_at = clock();
133        // The server sets the session identifier as it starts.
134        // `src/tcp_server.cpp:328`.
135        if info.session_id.is_empty() {
136            info.session_id = config::get().session_id.clone();
137        }
138
139        let shared = Arc::new(Shared {
140            info: Mutex::new(info.clone()),
141            fanout: Fanout::new(),
142            sync: Mutex::new(Vec::new()),
143            sync_mode,
144            stop: Mutex::new(false),
145        });
146
147        for sock in [udp4, udp6].into_iter().flatten() {
148            let s = Arc::clone(&shared);
149            std::thread::spawn(move || udp_loop(sock, s));
150        }
151        // A multicast or broadcast query arrives on its own port, outside the
152        // unicast range (`src/api_config.cpp:169`). An outlet that listens only
153        // on the range never answers one.
154        let mut multicast_bound = false;
155        for family in [V4, V6] {
156            if (family == V4 && !cfg.allow_ipv4) || (family == V6 && !cfg.allow_ipv6) {
157                continue;
158            }
159            if let Ok(mc) = bind_multicast_port(family) {
160                multicast_bound = true;
161                let s = Arc::clone(&shared);
162                std::thread::spawn(move || udp_loop(mc, s));
163            }
164        }
165        for listener in [tcp4, tcp6].into_iter().flatten() {
166            let s = Arc::clone(&shared);
167            std::thread::spawn(move || tcp_loop(listener, s));
168        }
169
170        Ok(Outlet {
171            shared,
172            info,
173            multicast_bound,
174        })
175    }
176
177    /// The description that this outlet publishes.
178    pub fn info(&self) -> &StreamInfo {
179        &self.info
180    }
181
182    /// True when the outlet holds the port that carries a multicast query.
183    ///
184    /// A false value is not an error on its own. It means that another process
185    /// on this machine holds the port, and that only a unicast query or a
186    /// broadcast query reaches this outlet.
187    pub fn holds_multicast_port(&self) -> bool {
188        self.multicast_bound
189    }
190
191    /// The number of connected consumers.
192    pub fn consumer_count(&self) -> usize {
193        if self.shared.sync_mode {
194            // A blocking outlet registers its consumers with the writer rather
195            // than with the queue. `src/stream_outlet_impl.cpp:176-179`.
196            return self.shared.sync.lock().unwrap().len();
197        }
198        self.shared.fanout.count()
199    }
200
201    /// Wait until at least one consumer is connected.
202    pub fn wait_for_consumers(&self, timeout: Duration) -> bool {
203        let end = Instant::now() + timeout;
204        while Instant::now() < end {
205            if self.consumer_count() > 0 {
206                return true;
207            }
208            std::thread::sleep(Duration::from_millis(20));
209        }
210        self.consumer_count() > 0
211    }
212
213    /// Send one sample to every connected consumer.
214    ///
215    /// This never waits. A consumer whose queue is full loses its oldest
216    /// sample, and every other consumer is unaffected. SPEC.md 8.7 and 8.8.
217    pub fn push(&self, s: &Sample) {
218        // Two rules decide the timestamp, and both belong here.
219        //
220        // A configuration can order every timestamp to be the current clock
221        // (`src/stream_outlet_impl.cpp:162`). A pushed timestamp of zero also
222        // means the current clock (`src/stream_outlet_impl.cpp:170`, SPEC.md
223        // 8.3).
224        //
225        // The second rule has to live in the outlet and not at the C boundary.
226        // A consumer reads a timestamp of zero as "no sample", so an outlet
227        // that sends one delivers values that no application can use.
228        //
229        // The deduced tag is -1.0, so it passes through untouched.
230        let timestamp = if config::get().force_default_timestamps || s.timestamp == 0.0 {
231            clock()
232        } else {
233            s.timestamp
234        };
235        let owned;
236        let sample = if timestamp == s.timestamp {
237            s
238        } else {
239            owned = Sample {
240                timestamp,
241                values: s.values.clone(),
242            };
243            &owned
244        };
245        if self.shared.sync_mode {
246            write_blocking(&self.shared, sample);
247            return;
248        }
249        self.shared.fanout.push(sample);
250    }
251}
252
253/// Write one sample to every consumer, and wait for each write to finish.
254///
255/// A consumer whose socket fails is dropped. Nothing is queued, so a consumer
256/// that reads slowly holds up the caller. That is the whole point of the mode.
257fn write_blocking(shared: &Shared, sample: &Sample) {
258    let mut out = Vec::new();
259    let mut consumers = shared.sync.lock().unwrap();
260    consumers.retain_mut(|c| {
261        out.clear();
262        if c.codec.encode(sample, &mut out).is_err() {
263            return false;
264        }
265        c.stream.write_all(&out).is_ok() && c.stream.flush().is_ok()
266    });
267}
268
269impl Drop for Outlet {
270    fn drop(&mut self) {
271        *self.shared.stop.lock().unwrap() = true;
272        self.shared.fanout.close();
273    }
274}
275
276/// Which protocol a socket speaks.
277pub(crate) const V4: bool = false;
278pub(crate) const V6: bool = true;
279
280/// The address that a listening socket of this family binds.
281fn any_address(v6: bool) -> std::net::IpAddr {
282    if v6 {
283        std::net::Ipv6Addr::UNSPECIFIED.into()
284    } else {
285        std::net::Ipv4Addr::UNSPECIFIED.into()
286    }
287}
288
289/// Bind the first free port of the range, for one protocol.
290///
291/// liblsl walks the same range and then falls back to a port that the
292/// operating system picks, when `ports.AllowRandomPorts` allows it
293/// (`src/socket_utils.cpp:6-25`).
294fn bind_tcp_in_range(v6: bool) -> std::io::Result<TcpListener> {
295    let cfg = config::get();
296    let host = any_address(v6);
297    let mut last = None;
298    for p in cfg.base_port..cfg.base_port + cfg.port_range {
299        match TcpListener::bind((host, p)) {
300            Ok(l) => return Ok(l),
301            Err(e) => last = Some(e),
302        }
303    }
304    Err(last.unwrap_or_else(|| std::io::Error::other("no free TCP port in the range")))
305}
306
307fn bind_udp_in_range(v6: bool) -> std::io::Result<UdpSocket> {
308    let cfg = config::get();
309    let host = any_address(v6);
310    let mut last = None;
311    for p in cfg.base_port..cfg.base_port + cfg.port_range {
312        match UdpSocket::bind((host, p)) {
313            Ok(s) => {
314                // Joining with the unspecified address lets the kernel pick one
315                // interface. It can pick the loopback, which carries no
316                // multicast, and the outlet is then invisible.
317                join_groups(&s, v6);
318                if !v6 {
319                    let _ = s.set_broadcast(true);
320                }
321                return Ok(s);
322            }
323            Err(e) => last = Some(e),
324        }
325    }
326    Err(last.unwrap_or_else(|| std::io::Error::other("no free UDP port in the range")))
327}
328
329fn bind_multicast_port(v6: bool) -> std::io::Result<UdpSocket> {
330    // The port has to be shared. `src/udp_server.cpp:60` sets `reuse_address`
331    // before it binds, so several outlets in one process, and several
332    // programs on one machine, all receive the same multicast query.
333    //
334    // Without this, only the first outlet answers a multicast query. A program
335    // that publishes a data stream and a marker stream would then have one of
336    // the two invisible to another machine.
337    //
338    // The standard library has no call for this option.
339    let addr = SocketAddr::new(any_address(v6), config::get().multicast_port);
340    let sock = socket2::Socket::new(
341        if v6 {
342            socket2::Domain::IPV6
343        } else {
344            socket2::Domain::IPV4
345        },
346        socket2::Type::DGRAM,
347        Some(socket2::Protocol::UDP),
348    )?;
349    sock.set_reuse_address(true)?;
350    if v6 {
351        // A socket that also accepts IPv4 would take the port from the IPv4
352        // responder, and one of the two families would go unanswered.
353        sock.set_only_v6(true)?;
354    }
355    sock.bind(&addr.into())?;
356    let s: UdpSocket = sock.into();
357    join_groups(&s, v6);
358    if !v6 {
359        let _ = s.set_broadcast(true);
360    }
361    Ok(s)
362}
363
364/// Join every discovery group of one family on every local interface.
365///
366/// An IPv6 join names an interface by its index, not by its address
367/// (`src/udp_server.cpp:78`). Index zero lets the operating system pick, and
368/// every real index is tried as well.
369fn join_groups(s: &UdpSocket, v6: bool) {
370    if v6 {
371        for group in &config::get().multicast_addresses {
372            if let Ok(addr) = group.parse::<std::net::Ipv6Addr>() {
373                if !addr.is_multicast() {
374                    continue;
375                }
376                for index in crate::local_interface_indexes() {
377                    let _ = s.join_multicast_v6(&addr, index);
378                }
379            }
380        }
381        return;
382    }
383    let mut ifaces = crate::local_ipv4_addresses();
384    ifaces.push(std::net::Ipv4Addr::UNSPECIFIED);
385    for group in &config::get().multicast_addresses {
386        if let Ok(addr) = group.parse::<std::net::Ipv4Addr>() {
387            // A broadcast address is not a group, so no join is possible.
388            if addr.is_broadcast() || !addr.is_multicast() {
389                continue;
390            }
391            for iface in &ifaces {
392                let _ = s.join_multicast_v4(&addr, iface);
393            }
394        }
395    }
396}
397
398/// Answer discovery queries and time probes. SPEC.md 2 and 3.
399fn udp_loop(sock: UdpSocket, shared: Arc<Shared>) {
400    let _ = sock.set_read_timeout(Some(Duration::from_millis(200)));
401    let mut buf = [0u8; 65536];
402    loop {
403        if *shared.stop.lock().unwrap() {
404            return;
405        }
406        let (n, from) = match sock.recv_from(&mut buf) {
407            Ok(x) => x,
408            Err(_) => continue,
409        };
410        // The arrival time belongs to a time probe, so read the clock first.
411        let t1 = clock();
412        let msg = &buf[..n];
413        if std::env::var_os("LSL_TRACE_UDP").is_some() {
414            eprintln!(
415                "TRACE udp {} bytes from {}: {:?}",
416                n,
417                from,
418                String::from_utf8_lossy(&msg[..n.min(80)])
419            );
420        }
421
422        if let Some(q) = discovery::parse_query(msg) {
423            let info = shared.info.lock().unwrap().clone();
424            // A query that does not match gets no answer at all. SPEC.md 2.2.
425            if info.matches(&q.query) {
426                let xml = info.to_shortinfo_xml();
427                let reply = discovery::build_answer(&q.query_id, &xml);
428                let to = std::net::SocketAddr::new(from.ip(), q.return_port);
429                let _ = sock.send_to(&reply, to);
430            }
431            continue;
432        }
433
434        if let Some(p) = timesync::parse_probe(msg) {
435            let t2 = clock();
436            let reply = timesync::build_answer(p.wave_id, p.t0, t1, t2);
437            let _ = sock.send_to(&reply, from);
438            continue;
439        }
440        // An unknown method gets no answer. SPEC.md 10.
441    }
442}
443
444fn tcp_loop(listener: TcpListener, shared: Arc<Shared>) {
445    let _ = listener.set_nonblocking(true);
446    loop {
447        if *shared.stop.lock().unwrap() {
448            return;
449        }
450        match listener.accept() {
451            Ok((stream, _)) => {
452                let s = Arc::clone(&shared);
453                let _ = stream.set_nonblocking(false);
454                std::thread::spawn(move || {
455                    let _ = serve_client(stream, s);
456                });
457            }
458            Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
459                std::thread::sleep(Duration::from_millis(20));
460            }
461            Err(_) => return,
462        }
463    }
464}
465
466/// Run one feed connection. SPEC.md 4, 5, and 6.
467fn serve_client(mut stream: TcpStream, shared: Arc<Shared>) -> std::io::Result<()> {
468    stream.set_nodelay(true)?;
469    stream.set_read_timeout(Some(Duration::from_secs(30)))?;
470
471    // Read the request line first. Only a feed request carries a header block,
472    // so a read that waits for the empty line would hang on the other two.
473    // `src/tcp_server.cpp:499` reads the same way.
474    let mut buf = Vec::new();
475    let mut tmp = [0u8; 4096];
476    let nl = loop {
477        if let Some(p) = buf.iter().position(|&c| c == b'\n') {
478            break p;
479        }
480        let n = stream.read(&mut tmp)?;
481        if n == 0 {
482            return Ok(());
483        }
484        buf.extend_from_slice(&tmp[..n]);
485        if buf.len() > 1 << 20 {
486            return Ok(());
487        }
488    };
489    let request_line = String::from_utf8_lossy(&buf[..nl])
490        .trim_end_matches('\r')
491        .to_string();
492
493    let info = shared.info.lock().unwrap().clone();
494
495    // A request for the whole description. The answer is the document, and the
496    // close of the connection ends it. `src/tcp_server.cpp:508`.
497    if request_line == "LSL:fullinfo" {
498        stream.write_all(info.to_fullinfo_xml().as_bytes())?;
499        return stream.flush();
500    }
501
502    // A request for the short description, with the query on the next line.
503    // A stream that does not match the query gets no answer at all.
504    // `src/tcp_server.cpp:537`.
505    if request_line == "LSL:shortinfo" {
506        let query = loop {
507            let rest = &buf[nl + 1..];
508            if let Some(p) = rest.iter().position(|&c| c == b'\n') {
509                break String::from_utf8_lossy(&rest[..p]).trim().to_string();
510            }
511            let n = stream.read(&mut tmp)?;
512            if n == 0 {
513                return Ok(());
514            }
515            buf.extend_from_slice(&tmp[..n]);
516        };
517        if info.matches(&query) {
518            stream.write_all(info.to_shortinfo_xml().as_bytes())?;
519            return stream.flush();
520        }
521        return Ok(());
522    }
523
524    // A feed request carries a header block that ends with an empty line. Wait
525    // for that line before the block is read.
526    while find_double_crlf(&buf).is_none() {
527        let n = stream.read(&mut tmp)?;
528        if n == 0 {
529            return Ok(());
530        }
531        buf.extend_from_slice(&tmp[..n]);
532        if buf.len() > 1 << 20 {
533            return Ok(());
534        }
535    }
536
537    // Only the feed request is served here. SPEC.md 4.1 names the others.
538    let (version, uid) = match request_line.strip_prefix("LSL:streamfeed/") {
539        Some(rest) => {
540            let mut it = rest.splitn(2, ' ');
541            let v: i32 = it.next().unwrap_or("0").trim().parse().unwrap_or(0);
542            (v, it.next().unwrap_or("").trim().to_string())
543        }
544        None => {
545            if request_line.starts_with("LSL:streamfeed") {
546                (100, String::new())
547            } else {
548                return Ok(());
549            }
550        }
551    };
552
553    let (headers, _) = parse_block(&buf[nl + 1..]).unwrap_or_default();
554    let mut srv = ServerStream::new(&info.uid, info.format, LITTLE, ENDIAN_PERFORMANCE);
555    if info.format == labstream_wire::Format::String {
556        srv.channel_bytes = 0;
557    }
558    let req = FeedRequest::from_headers(version, &uid, &headers, srv.channel_bytes);
559
560    let trace = std::env::var_os("LSL_TRACE_TCP").is_some();
561    if trace {
562        eprintln!("TRACE request {request_line:?}");
563        eprintln!("TRACE headers {headers:?}");
564    }
565
566    let accepted = match negotiate(&req, &srv) {
567        Outcome::Refuse(s) => {
568            if trace {
569                eprintln!("TRACE refused {} {}", s.code, s.message);
570            }
571            stream.write_all(s.to_wire().as_bytes())?;
572            return Ok(());
573        }
574        Outcome::Accept(a) => a,
575    };
576
577    // Protocol 1.00 carries every sample in a Boost archive
578    // (`src/sample.cpp:330`), which this implementation does not write.
579    //
580    // liblsl answers 505 only when the **major** version differs
581    // (`src/tcp_server.cpp:576`), so 505 is the wrong word here: a request for
582    // 1.00 against a 1.10 server is one that liblsl serves. There is no code
583    // in this protocol for "the version is one I cannot write".
584    //
585    // The connection therefore closes with nothing written. A peer reads the
586    // end of the stream, which is a state every client already handles, rather
587    // than a status line that a 1.00 client never looks for.
588    if accepted.data_protocol_version < 110 {
589        if trace {
590            eprintln!(
591                "TRACE closing: the peer agreed to protocol {}, which this side does not write",
592                accepted.data_protocol_version
593            );
594        }
595        return Ok(());
596    }
597
598    stream.write_all(
599        accepted
600            .to_wire(srv.configured_version, &info.uid)
601            .as_bytes(),
602    )?;
603
604    let order = match accepted.codec_order() {
605        Some(o) => o,
606        None => return Ok(()),
607    };
608    let codec = Codec::new(info.format, info.channel_count as usize, order)
609        .with_suppress_subnormals(accepted.suppress_subnormals);
610
611    // Two test pattern samples open every feed. SPEC.md 6.
612    let mut out = Vec::new();
613    for off in TEST_PATTERN_OFFSETS {
614        let s = labstream_wire::test_pattern(info.format, info.channel_count as usize, off);
615        codec
616            .encode(&s, &mut out)
617            .map_err(|e| std::io::Error::other(e.to_string()))?;
618    }
619    if trace {
620        eprintln!(
621            "TRACE accepted version={} buffer={} chunk={} order={:?} test-pattern={} bytes",
622            accepted.data_protocol_version,
623            accepted.max_buffer_length,
624            accepted.max_chunk_length,
625            accepted.codec_order(),
626            out.len()
627        );
628    }
629    stream.write_all(&out)?;
630    stream.flush()?;
631
632    // A buffer length of zero or less sends nothing more. SPEC.md 9.
633    if accepted.max_buffer_length <= 0 {
634        return Ok(());
635    }
636
637    // A blocking outlet keeps the socket instead of a queue. The handover
638    // happens here, after the headers and the test pattern, which is where
639    // liblsl does it (`src/tcp_server.cpp:733`).
640    if shared.sync_mode {
641        if trace {
642            eprintln!("TRACE handing the socket to the blocking writer");
643        }
644        shared
645            .sync
646            .lock()
647            .unwrap()
648            .push(SyncConsumer { stream, codec });
649        return Ok(());
650    }
651
652    // The header carries a count of samples, already converted from whatever
653    // unit the peer's API used. SPEC.md 8.6.
654    let queue = shared
655        .fanout
656        .add(accepted.max_buffer_length.max(1) as usize);
657
658    // A chunk decides when one write happens. It is not a wire unit. SPEC.md 9.
659    let chunk = if accepted.max_chunk_length > 0 {
660        accepted.max_chunk_length as usize
661    } else {
662        1
663    };
664
665    let mut pending = Vec::new();
666    let mut count = 0usize;
667    let mut sent = 0usize;
668    loop {
669        if *shared.stop.lock().unwrap() || queue.is_closed() {
670            break;
671        }
672        match queue.pop(Duration::from_millis(200)) {
673            Some(s) => {
674                if codec.encode(&s, &mut pending).is_err() {
675                    break;
676                }
677                count += 1;
678                if count >= chunk {
679                    if trace && sent == 0 {
680                        eprintln!("TRACE first data write, {} bytes", pending.len());
681                    }
682                    if let Err(e) = stream.write_all(&pending) {
683                        if trace {
684                            eprintln!("TRACE write failed after {sent} samples: {e}");
685                        }
686                        break;
687                    }
688                    sent += count;
689                    let _ = stream.flush();
690                    pending.clear();
691                    count = 0;
692                }
693            }
694            None => {
695                // Nothing arrived. Write whatever is waiting so a partial
696                // chunk does not sit here.
697                if !pending.is_empty() {
698                    if stream.write_all(&pending).is_err() {
699                        break;
700                    }
701                    let _ = stream.flush();
702                    pending.clear();
703                    count = 0;
704                }
705            }
706        }
707    }
708    if trace {
709        eprintln!("TRACE session over after {sent} samples");
710    }
711    shared.fanout.remove(&queue);
712    Ok(())
713}
714
715fn find_double_crlf(buf: &[u8]) -> Option<usize> {
716    buf.windows(4).position(|w| w == b"\r\n\r\n").map(|p| p + 4)
717}
718
719impl Outlet {
720    /// Send several samples that share one timestamp, with one lock.
721    ///
722    /// The timestamps are the timestamps of [`Outlet::push_chunk`]. The only
723    /// difference is the number of locks: this takes the set of consumers once
724    /// for the whole block, and each consumer queue once. `push_chunk` takes both
725    /// once for each sample.
726    ///
727    /// A block of 500 samples to 2 consumers costs 3 locks here and 1500 locks
728    /// there.
729    ///
730    /// The blocking mode is not batched. That mode waits for each write on
731    /// purpose, so a block gives no gain.
732    pub fn push_chunk_fast(&self, samples: &[Sample], timestamp: f64) {
733        if samples.is_empty() {
734            return;
735        }
736        if self.shared.sync_mode {
737            self.push_chunk(samples, timestamp);
738            return;
739        }
740        let block: Vec<Sample> = self
741            .chunk_timestamps(samples, timestamp)
742            .map(|(t, s)| Sample {
743                // The rule of `Outlet::push` runs for each sample, so a
744                // configuration that orders the current clock still gets it.
745                timestamp: self.stamp(t),
746                values: s.values.clone(),
747            })
748            .collect();
749        self.shared.fanout.push_many(&block);
750    }
751
752    /// The timestamp of each sample of a chunk. SPEC.md 9.2.
753    fn chunk_timestamps<'a>(
754        &self,
755        samples: &'a [Sample],
756        timestamp: f64,
757    ) -> impl Iterator<Item = (f64, &'a Sample)> {
758        let mut first = if timestamp == 0.0 {
759            crate::clock()
760        } else {
761            timestamp
762        };
763        if self.info.nominal_srate != 0.0 {
764            first -= (samples.len() - 1) as f64 / self.info.nominal_srate;
765        }
766        samples.iter().enumerate().map(move |(k, s)| {
767            let t = if k == 0 {
768                first
769            } else {
770                labstream_wire::DEDUCED_TIMESTAMP
771            };
772            (t, s)
773        })
774    }
775
776    /// Apply the two timestamp rules of [`Outlet::push`].
777    fn stamp(&self, t: f64) -> f64 {
778        if config::get().force_default_timestamps || t == 0.0 {
779            clock()
780        } else {
781            t
782        }
783    }
784
785    /// Send several samples that share one timestamp. SPEC.md 9.2.
786    ///
787    /// The timestamp names the **last** sample. A stream with a rate counts
788    /// backward from it, so the first sample is dated
789    /// `timestamp - (count - 1) / rate`. Only that first sample carries a
790    /// timestamp on the wire, and the rest carry the deduced tag.
791    ///
792    /// An application that acquires a block and stamps it on arrival therefore
793    /// gets the right time for every sample in the block.
794    ///
795    /// [`Outlet::push_chunk_fast`] does the same with one lock for the block.
796    pub fn push_chunk(&self, samples: &[Sample], timestamp: f64) {
797        if samples.is_empty() {
798            return;
799        }
800        let mut first = if timestamp == 0.0 {
801            crate::clock()
802        } else {
803            timestamp
804        };
805        if self.info.nominal_srate != 0.0 {
806            first -= (samples.len() - 1) as f64 / self.info.nominal_srate;
807        }
808        for (k, s) in samples.iter().enumerate() {
809            self.push(&Sample {
810                timestamp: if k == 0 {
811                    first
812                } else {
813                    labstream_wire::DEDUCED_TIMESTAMP
814                },
815                values: s.values.clone(),
816            });
817        }
818    }
819}