Skip to main content

labstream_net/
outlet.rs

1//! The outlet: a discovery responder and a TCP feed server.
2
3use crate::health::{ConsumerHealth, OutletHealth};
4use crate::info::StreamInfo;
5use crate::queue::{Fanout, SampleQueue};
6use crate::{clock, config};
7use labstream_proto::discovery;
8use labstream_proto::features;
9use labstream_proto::header::parse_block;
10use labstream_proto::negotiate::{negotiate, FeedRequest, Outcome, ServerStream, LITTLE};
11use labstream_proto::seq::Numbering;
12use labstream_proto::timesync;
13use labstream_wire::{Codec, PackedSample, Sample, TEST_PATTERN_OFFSETS};
14use std::io::{Read, Write};
15use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket};
16use std::sync::{Arc, Mutex};
17use std::time::{Duration, Instant};
18
19/// How fast this side converts a byte order.
20///
21/// liblsl measures this with a benchmark. A fixed value keeps the negotiation
22/// deterministic, and the value never travels as a claim about speed. It only
23/// decides which side converts. SPEC.md 5.2.
24const ENDIAN_PERFORMANCE: f64 = 1000.0;
25
26struct Shared {
27    info: Mutex<StreamInfo>,
28    /// One queue per connected consumer. SPEC.md 8.8.
29    fanout: Fanout,
30    /// The consumers of a blocking outlet, which holds no queue at all.
31    sync: Mutex<SyncSet>,
32    /// True when this outlet writes each sample before the push returns.
33    sync_mode: bool,
34    stop: Mutex<bool>,
35    /// The random value that identifies this run of the outlet for the
36    /// `resume` feature. `docs/extensions.md`, negotiation rule 2.
37    epoch: u64,
38}
39
40/// One consumer of a blocking outlet.
41///
42/// A blocking outlet holds the socket rather than a queue. Each consumer keeps
43/// its own codec, because two consumers can agree on different byte orders.
44struct SyncConsumer {
45    id: u64,
46    peer: String,
47    stream: TcpStream,
48    codec: Codec,
49    /// The record state, when the consumer agreed to `seq/1`.
50    numbering: Option<Numbering>,
51}
52
53/// The consumers of a blocking outlet, and the number of the next sample.
54///
55/// One lock holds both, so the numbers follow the order of the writes.
56#[derive(Default)]
57struct SyncSet {
58    list: Vec<SyncConsumer>,
59    next_consumer_id: u64,
60    next: u64,
61}
62
63/// A stream outlet.
64pub struct Outlet {
65    shared: Arc<Shared>,
66    info: StreamInfo,
67    /// True when the outlet holds the port that carries a multicast query.
68    ///
69    /// Another process on this machine can already hold it. The outlet then
70    /// answers a unicast query and a broadcast query, and never sees a
71    /// multicast query. A consumer on another machine can therefore miss the
72    /// stream. SPEC.md 1.1.
73    multicast_bound: bool,
74}
75
76impl Outlet {
77    /// Publish a stream.
78    ///
79    /// The call binds a TCP port for the data and a UDP port for discovery and
80    /// time probes, then starts one thread for each.
81    pub fn new(info: StreamInfo) -> std::io::Result<Self> {
82        Outlet::with_flags(info, false, config::get().history_limits())
83    }
84
85    /// Publish a stream with explicit `resume` history and disk-spool limits
86    /// (`docs/roadmap.md`, step 3).
87    pub fn new_with_limits(
88        info: StreamInfo,
89        limits: crate::history::HistoryLimits,
90    ) -> std::io::Result<Self> {
91        Outlet::with_flags(info, false, limits)
92    }
93
94    /// Publish a stream that writes each sample before the push returns.
95    ///
96    /// This is `transp_sync_blocking` (`include/lsl/common.h:172`). The outlet
97    /// holds no queue, so a consumer that cannot keep up holds up the push
98    /// instead of losing a sample.
99    ///
100    /// **The wire is the same.** liblsl hands the socket to the blocking writer
101    /// only after the headers and the test pattern have gone out
102    /// (`src/tcp_server.cpp:733`), and the layout of a sample does not change
103    /// (`src/sync_serialization.h`). A consumer cannot tell the two modes
104    /// apart.
105    ///
106    /// A stream of strings has no fixed width, and liblsl refuses it here
107    /// (`src/stream_outlet_impl.cpp:34-38`).
108    pub fn new_blocking(info: StreamInfo) -> std::io::Result<Self> {
109        if info.format == labstream_wire::Format::String {
110            return Err(std::io::Error::other(
111                "Synchronous (zero-copy) mode is not supported for string-format streams",
112            ));
113        }
114        Outlet::with_flags(info, true, config::get().history_limits())
115    }
116
117    fn with_flags(
118        mut info: StreamInfo,
119        sync_mode: bool,
120        limits: crate::history::HistoryLimits,
121    ) -> std::io::Result<Self> {
122        let cfg = config::get();
123        // One stack for each protocol that the configuration allows, the way
124        // `stream_outlet_impl::instantiate_stack` builds them.
125        let tcp4 = if cfg.allow_ipv4 {
126            bind_tcp_in_range(V4).ok()
127        } else {
128            None
129        };
130        let udp4 = if cfg.allow_ipv4 {
131            bind_udp_in_range(V4).ok()
132        } else {
133            None
134        };
135        let tcp6 = if cfg.allow_ipv6 {
136            bind_tcp_in_range(V6).ok()
137        } else {
138            None
139        };
140        let udp6 = if cfg.allow_ipv6 {
141            bind_udp_in_range(V6).ok()
142        } else {
143            None
144        };
145        if tcp4.is_none() && tcp6.is_none() {
146            return Err(std::io::Error::other(
147                "neither the IPv4 nor the IPv6 stack could be built",
148            ));
149        }
150        if let Some(t) = &tcp4 {
151            info.v4data_port = t.local_addr()?.port();
152        }
153        if let Some(u) = &udp4 {
154            info.v4service_port = u.local_addr()?.port();
155        }
156        if let Some(t) = &tcp6 {
157            info.v6data_port = t.local_addr()?.port();
158        }
159        if let Some(u) = &udp6 {
160            info.v6service_port = u.local_addr()?.port();
161        }
162        if info.uid.is_empty() {
163            info.uid = crate::make_uid();
164        }
165        info.created_at = clock();
166        // The server sets the session identifier as it starts.
167        // `src/tcp_server.cpp:328`.
168        if info.session_id.is_empty() {
169            info.session_id = config::get().session_id.clone();
170        }
171
172        let shared = Arc::new(Shared {
173            info: Mutex::new(info.clone()),
174            fanout: Fanout::with_rate(info.nominal_srate, limits),
175            sync: Mutex::new(SyncSet::default()),
176            sync_mode,
177            stop: Mutex::new(false),
178            epoch: {
179                let b = crate::random_bytes();
180                u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])
181            },
182        });
183
184        for sock in [udp4, udp6].into_iter().flatten() {
185            let s = Arc::clone(&shared);
186            std::thread::spawn(move || udp_loop(sock, s));
187        }
188        // A multicast or broadcast query arrives on its own port, outside the
189        // unicast range (`src/api_config.cpp:169`). An outlet that listens only
190        // on the range never answers one.
191        let mut multicast_bound = false;
192        for family in [V4, V6] {
193            if (family == V4 && !cfg.allow_ipv4) || (family == V6 && !cfg.allow_ipv6) {
194                continue;
195            }
196            if let Ok(mc) = bind_multicast_port(family) {
197                multicast_bound = true;
198                let s = Arc::clone(&shared);
199                std::thread::spawn(move || udp_loop(mc, s));
200            }
201        }
202        for listener in [tcp4, tcp6].into_iter().flatten() {
203            let s = Arc::clone(&shared);
204            std::thread::spawn(move || tcp_loop(listener, s));
205        }
206
207        Ok(Outlet {
208            shared,
209            info,
210            multicast_bound,
211        })
212    }
213
214    /// The description that this outlet publishes.
215    pub fn info(&self) -> &StreamInfo {
216        &self.info
217    }
218
219    /// True when the outlet holds the port that carries a multicast query.
220    ///
221    /// A false value is not an error on its own. It means that another process
222    /// on this machine holds the port, and that only a unicast query or a
223    /// broadcast query reaches this outlet.
224    pub fn holds_multicast_port(&self) -> bool {
225        self.multicast_bound
226    }
227
228    /// How many samples the `resume` history holds across RAM and disk. Zero
229    /// when the history is off, which is the case until a consumer agrees to
230    /// `resume/1`. `docs/extensions.md`, section `resume`.
231    pub fn history_len(&self) -> usize {
232        self.shared.fanout.history_len()
233    }
234
235    /// Bytes currently held by the `resume` history in RAM.
236    pub fn history_ram_bytes(&self) -> usize {
237        self.shared.fanout.history_ram_bytes()
238    }
239
240    /// Bytes currently held by the `resume` history in disk spool segments.
241    pub fn history_disk_bytes(&self) -> u64 {
242        self.shared.fanout.history_disk_bytes()
243    }
244
245    /// Path of the active disk spool directory, if disk spilling has started.
246    pub fn history_spool_dir(&self) -> Option<std::path::PathBuf> {
247        self.shared.fanout.history_spool_dir()
248    }
249
250    /// The number of connected consumers.
251    pub fn consumer_count(&self) -> usize {
252        if self.shared.sync_mode {
253            // A blocking outlet registers its consumers with the writer rather
254            // than with the queue. `src/stream_outlet_impl.cpp:176-179`.
255            return self.shared.sync.lock().unwrap().list.len();
256        }
257        self.shared.fanout.count()
258    }
259
260    /// Snapshot the fill and drop state of every connected consumer queue.
261    ///
262    /// For a blocking outlet (`Outlet::new_blocking`), each consumer has no
263    /// queue and reports zero fill, zero capacity, and zero drops.
264    pub fn health(&self) -> OutletHealth {
265        if self.shared.sync_mode {
266            let set = self.shared.sync.lock().unwrap();
267            let consumers = set
268                .list
269                .iter()
270                .map(|c| ConsumerHealth {
271                    id: c.id,
272                    peer: c.peer.clone(),
273                    fill: 0,
274                    capacity: 0,
275                    dropped: 0,
276                })
277                .collect();
278            return OutletHealth {
279                consumers,
280                history_len: 0,
281                pushed: set.next,
282            };
283        }
284        self.shared.fanout.health()
285    }
286
287    /// Wait until at least one consumer is connected.
288    pub fn wait_for_consumers(&self, timeout: Duration) -> bool {
289        let end = Instant::now() + timeout;
290        while Instant::now() < end {
291            if self.consumer_count() > 0 {
292                return true;
293            }
294            std::thread::sleep(Duration::from_millis(20));
295        }
296        self.consumer_count() > 0
297    }
298
299    /// Send one sample to every connected consumer.
300    ///
301    /// This never waits. A consumer whose queue is full loses its oldest
302    /// sample, and every other consumer is unaffected. SPEC.md 8.7 and 8.8.
303    pub fn push(&self, s: &Sample) {
304        self.push_packed(PackedSample::from_sample(s));
305    }
306
307    /// Emit a live metadata update stamped with the current local clock
308    /// (`docs/roadmap.md`, step 16).
309    ///
310    /// Every connected `labstream` consumer that negotiated `meta/1` receives
311    /// the update in order with the sample stream. `liblsl` inlets see no
312    /// change.
313    pub fn push_metadata(&self, key: &str, value: &str) -> labstream_proto::meta::MetadataUpdate {
314        self.push_metadata_at(key, value, 0.0)
315    }
316
317    /// Emit a live metadata update with an explicit timestamp (`0.0` uses the
318    /// current local clock).
319    pub fn push_metadata_at(
320        &self,
321        key: &str,
322        value: &str,
323        timestamp: f64,
324    ) -> labstream_proto::meta::MetadataUpdate {
325        let ts = if timestamp == 0.0 || config::get().force_default_timestamps {
326            crate::clock()
327        } else {
328            timestamp
329        };
330        self.shared
331            .fanout
332            .push_metadata(key.to_string(), value.to_string(), ts)
333    }
334
335    /// Snapshot the latest live metadata value emitted for each key.
336    pub fn metadata(
337        &self,
338    ) -> std::collections::BTreeMap<String, labstream_proto::meta::MetadataUpdate> {
339        self.shared.fanout.metadata_snapshot().1
340    }
341
342    /// Send one [`PackedSample`] to every connected consumer without copying
343    /// its channel payload across consumer queues or the `resume` history.
344    pub fn push_packed(&self, mut s: PackedSample) {
345        // Two rules decide the timestamp, and both belong here.
346        //
347        // A configuration can order every timestamp to be the current clock
348        // (`src/stream_outlet_impl.cpp:162`). A pushed timestamp of zero also
349        // means the current clock (`src/stream_outlet_impl.cpp:170`, SPEC.md
350        // 8.3).
351        //
352        // The second rule has to live in the outlet and not at the C boundary.
353        // A consumer reads a timestamp of zero as "no sample", so an outlet
354        // that sends one delivers values that no application can use.
355        //
356        // The deduced tag is -1.0, so it passes through untouched.
357        s.timestamp = self.stamp(s.timestamp);
358        if self.shared.sync_mode {
359            write_blocking_packed(&self.shared, &s);
360            return;
361        }
362        self.shared.fanout.push_packed(s);
363    }
364
365    /// Send one numeric sample directly from raw native-endian bytes.
366    ///
367    /// When only `shm/1` consumers are attached and `resume` history is off,
368    /// this avoids heap allocation completely.
369    pub fn push_numeric_raw(&self, timestamp: f64, format: labstream_wire::Format, bytes: &[u8]) {
370        let ts = self.stamp(timestamp);
371        if self.shared.sync_mode {
372            let s = PackedSample::from_raw_bytes(ts, format, Arc::from(bytes));
373            write_blocking_packed(&self.shared, &s);
374            return;
375        }
376        self.shared.fanout.push_numeric_raw(ts, format, bytes);
377    }
378
379    /// Send a flat contiguous numeric chunk with per-sample timestamps,
380    /// writing directly into `shm/1` consumer rings before allocating any
381    /// queued samples.
382    pub fn push_chunk_numeric_raw(
383        &self,
384        format: labstream_wire::Format,
385        raw: &[u8],
386        row_bytes: usize,
387        timestamps: &[f64],
388    ) {
389        if timestamps.is_empty() || row_bytes == 0 {
390            return;
391        }
392        let stamped: Vec<f64> = timestamps.iter().map(|&t| self.stamp(t)).collect();
393        if self.shared.sync_mode {
394            let block: Vec<PackedSample> = (0..stamped.len())
395                .map(|k| {
396                    PackedSample::from_raw_bytes(
397                        stamped[k],
398                        format,
399                        Arc::from(&raw[k * row_bytes..(k + 1) * row_bytes]),
400                    )
401                })
402                .collect();
403            write_blocking_many_packed(&self.shared, &block);
404            return;
405        }
406        self.shared
407            .fanout
408            .push_chunk_numeric_raw(format, raw, row_bytes, &stamped);
409    }
410}
411
412/// Write one packed sample to every consumer, and wait for each write to finish.
413///
414/// A consumer whose socket fails is dropped. Nothing is queued, so a consumer
415/// that reads slowly holds up the caller. That is the whole point of the mode.
416fn write_blocking_packed(shared: &Shared, sample: &PackedSample) {
417    write_blocking_many_packed(shared, std::slice::from_ref(sample));
418}
419
420/// Write several packed samples to every consumer, with one write for each consumer.
421fn write_blocking_many_packed(shared: &Shared, samples: &[PackedSample]) {
422    let mut out = Vec::new();
423    let mut set = shared.sync.lock().unwrap();
424    let first = set.next;
425    set.next = first.wrapping_add(samples.len() as u64);
426    set.list.retain_mut(|c| {
427        out.clear();
428        for (i, s) in samples.iter().enumerate() {
429            if let Some(n) = c.numbering.as_mut() {
430                n.before(first.wrapping_add(i as u64), &mut out);
431            }
432            if c.codec.encode_packed(s, &mut out).is_err() {
433                return false;
434            }
435        }
436        c.stream.write_all(&out).is_ok() && c.stream.flush().is_ok()
437    });
438}
439
440impl Drop for Outlet {
441    fn drop(&mut self) {
442        *self.shared.stop.lock().unwrap() = true;
443        self.shared.fanout.close();
444    }
445}
446
447/// Which protocol a socket speaks.
448pub(crate) const V4: bool = false;
449pub(crate) const V6: bool = true;
450
451/// The address that a listening socket of this family binds.
452fn any_address(v6: bool) -> std::net::IpAddr {
453    if v6 {
454        std::net::Ipv6Addr::UNSPECIFIED.into()
455    } else {
456        std::net::Ipv4Addr::UNSPECIFIED.into()
457    }
458}
459
460/// Bind the first free port of the range, for one protocol.
461///
462/// liblsl walks the same range and then falls back to a port that the
463/// operating system picks, when `ports.AllowRandomPorts` allows it
464/// (`src/socket_utils.cpp:6-25`).
465fn bind_tcp_in_range(v6: bool) -> std::io::Result<TcpListener> {
466    let cfg = config::get();
467    let host = any_address(v6);
468    let mut last = None;
469    for p in cfg.base_port..cfg.base_port + cfg.port_range {
470        match TcpListener::bind((host, p)) {
471            Ok(l) => return Ok(l),
472            Err(e) => last = Some(e),
473        }
474    }
475    Err(last.unwrap_or_else(|| std::io::Error::other("no free TCP port in the range")))
476}
477
478fn bind_udp_in_range(v6: bool) -> std::io::Result<UdpSocket> {
479    let cfg = config::get();
480    let host = any_address(v6);
481    let mut last = None;
482    for p in cfg.base_port..cfg.base_port + cfg.port_range {
483        match UdpSocket::bind((host, p)) {
484            Ok(s) => {
485                // Joining with the unspecified address lets the kernel pick one
486                // interface. It can pick the loopback, which carries no
487                // multicast, and the outlet is then invisible.
488                join_groups(&s, v6);
489                if !v6 {
490                    let _ = s.set_broadcast(true);
491                }
492                return Ok(s);
493            }
494            Err(e) => last = Some(e),
495        }
496    }
497    Err(last.unwrap_or_else(|| std::io::Error::other("no free UDP port in the range")))
498}
499
500fn bind_multicast_port(v6: bool) -> std::io::Result<UdpSocket> {
501    // The port has to be shared. `src/udp_server.cpp:60` sets `reuse_address`
502    // before it binds, so several outlets in one process, and several
503    // programs on one machine, all receive the same multicast query.
504    //
505    // Without this, only the first outlet answers a multicast query. A program
506    // that publishes a data stream and a marker stream would then have one of
507    // the two invisible to another machine.
508    //
509    // The standard library has no call for this option.
510    let addr = SocketAddr::new(any_address(v6), config::get().multicast_port);
511    let sock = socket2::Socket::new(
512        if v6 {
513            socket2::Domain::IPV6
514        } else {
515            socket2::Domain::IPV4
516        },
517        socket2::Type::DGRAM,
518        Some(socket2::Protocol::UDP),
519    )?;
520    sock.set_reuse_address(true)?;
521    if v6 {
522        // A socket that also accepts IPv4 would take the port from the IPv4
523        // responder, and one of the two families would go unanswered.
524        sock.set_only_v6(true)?;
525    }
526    sock.bind(&addr.into())?;
527    let s: UdpSocket = sock.into();
528    join_groups(&s, v6);
529    if !v6 {
530        let _ = s.set_broadcast(true);
531    }
532    Ok(s)
533}
534
535/// Join every discovery group of one family on every local interface.
536///
537/// An IPv6 join names an interface by its index, not by its address
538/// (`src/udp_server.cpp:78`). Index zero lets the operating system pick, and
539/// every real index is tried as well.
540fn join_groups(s: &UdpSocket, v6: bool) {
541    if v6 {
542        for group in &config::get().multicast_addresses {
543            if let Ok(addr) = group.parse::<std::net::Ipv6Addr>() {
544                if !addr.is_multicast() {
545                    continue;
546                }
547                for index in crate::local_interface_indexes() {
548                    let _ = s.join_multicast_v6(&addr, index);
549                }
550            }
551        }
552        return;
553    }
554    let mut ifaces = crate::local_ipv4_addresses();
555    ifaces.push(std::net::Ipv4Addr::UNSPECIFIED);
556    for group in &config::get().multicast_addresses {
557        if let Ok(addr) = group.parse::<std::net::Ipv4Addr>() {
558            // A broadcast address is not a group, so no join is possible.
559            if addr.is_broadcast() || !addr.is_multicast() {
560                continue;
561            }
562            for iface in &ifaces {
563                let _ = s.join_multicast_v4(&addr, iface);
564            }
565        }
566    }
567}
568
569/// Answer discovery queries and time probes. SPEC.md 2 and 3.
570fn udp_loop(sock: UdpSocket, shared: Arc<Shared>) {
571    let _ = sock.set_read_timeout(Some(Duration::from_millis(200)));
572    let mut buf = [0u8; 65536];
573    loop {
574        if *shared.stop.lock().unwrap() {
575            return;
576        }
577        let (n, from) = match sock.recv_from(&mut buf) {
578            Ok(x) => x,
579            Err(_) => continue,
580        };
581        // The arrival time belongs to a time probe, so read the clock first.
582        let t1 = clock();
583        let msg = &buf[..n];
584        if std::env::var_os("LSL_TRACE_UDP").is_some() {
585            eprintln!(
586                "TRACE udp {} bytes from {}: {:?}",
587                n,
588                from,
589                String::from_utf8_lossy(&msg[..n.min(80)])
590            );
591        }
592
593        if let Some(q) = discovery::parse_query(msg) {
594            let info = shared.info.lock().unwrap().clone();
595            // A query that does not match gets no answer at all. SPEC.md 2.2.
596            if info.matches(&q.query) {
597                let xml = info.to_shortinfo_xml();
598                let reply = discovery::build_answer(&q.query_id, &xml);
599                let to = std::net::SocketAddr::new(from.ip(), q.return_port);
600                let _ = sock.send_to(&reply, to);
601            }
602            continue;
603        }
604
605        if let Some(p) = timesync::parse_probe(msg) {
606            let t2 = clock();
607            let reply = timesync::build_answer(p.wave_id, p.t0, t1, t2);
608            let _ = sock.send_to(&reply, from);
609            continue;
610        }
611        // An unknown method gets no answer. SPEC.md 10.
612    }
613}
614
615fn tcp_loop(listener: TcpListener, shared: Arc<Shared>) {
616    let _ = listener.set_nonblocking(true);
617    loop {
618        if *shared.stop.lock().unwrap() {
619            return;
620        }
621        match listener.accept() {
622            Ok((stream, _)) => {
623                let s = Arc::clone(&shared);
624                let _ = stream.set_nonblocking(false);
625                std::thread::spawn(move || {
626                    let _ = serve_client(stream, s);
627                });
628            }
629            Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
630                std::thread::sleep(Duration::from_millis(20));
631            }
632            Err(_) => return,
633        }
634    }
635}
636
637/// Run one feed connection. SPEC.md 4, 5, and 6.
638fn serve_client(mut stream: TcpStream, shared: Arc<Shared>) -> std::io::Result<()> {
639    stream.set_nodelay(true)?;
640    stream.set_read_timeout(Some(Duration::from_secs(30)))?;
641    crate::keepalive::enable(&stream);
642
643    // Read the request line first. Only a feed request carries a header block,
644    // so a read that waits for the empty line would hang on the other two.
645    // `src/tcp_server.cpp:499` reads the same way.
646    let mut buf = Vec::new();
647    let mut tmp = [0u8; 4096];
648    let nl = loop {
649        if let Some(p) = buf.iter().position(|&c| c == b'\n') {
650            break p;
651        }
652        let n = stream.read(&mut tmp)?;
653        if n == 0 {
654            return Ok(());
655        }
656        buf.extend_from_slice(&tmp[..n]);
657        if buf.len() > 1 << 20 {
658            return Ok(());
659        }
660    };
661    let request_line = String::from_utf8_lossy(&buf[..nl])
662        .trim_end_matches('\r')
663        .to_string();
664
665    let info = shared.info.lock().unwrap().clone();
666
667    // A request for the whole description. The answer is the document, and the
668    // close of the connection ends it. `src/tcp_server.cpp:508`.
669    if request_line == "LSL:fullinfo" {
670        stream.write_all(info.to_fullinfo_xml().as_bytes())?;
671        return stream.flush();
672    }
673
674    // A request for the short description, with the query on the next line.
675    // A stream that does not match the query gets no answer at all.
676    // `src/tcp_server.cpp:537`.
677    if request_line == "LSL:shortinfo" {
678        let query = loop {
679            let rest = &buf[nl + 1..];
680            if let Some(p) = rest.iter().position(|&c| c == b'\n') {
681                break String::from_utf8_lossy(&rest[..p]).trim().to_string();
682            }
683            let n = stream.read(&mut tmp)?;
684            if n == 0 {
685                return Ok(());
686            }
687            buf.extend_from_slice(&tmp[..n]);
688        };
689        if info.matches(&query) {
690            stream.write_all(info.to_shortinfo_xml().as_bytes())?;
691            return stream.flush();
692        }
693        return Ok(());
694    }
695
696    // A feed request carries a header block that ends with an empty line. Wait
697    // for that line before the block is read.
698    while find_double_crlf(&buf).is_none() {
699        let n = stream.read(&mut tmp)?;
700        if n == 0 {
701            return Ok(());
702        }
703        buf.extend_from_slice(&tmp[..n]);
704        if buf.len() > 1 << 20 {
705            return Ok(());
706        }
707    }
708
709    // Only the feed request is served here. SPEC.md 4.1 names the others.
710    let (version, uid) = match request_line.strip_prefix("LSL:streamfeed/") {
711        Some(rest) => {
712            let mut it = rest.splitn(2, ' ');
713            let v: i32 = it.next().unwrap_or("0").trim().parse().unwrap_or(0);
714            (v, it.next().unwrap_or("").trim().to_string())
715        }
716        None => {
717            if request_line.starts_with("LSL:streamfeed") {
718                (100, String::new())
719            } else {
720                return Ok(());
721            }
722        }
723    };
724
725    let (headers, _) = parse_block(&buf[nl + 1..]).unwrap_or_default();
726    let mut srv = ServerStream::new(&info.uid, info.format, LITTLE, ENDIAN_PERFORMANCE);
727    if info.format == labstream_wire::Format::String {
728        srv.channel_bytes = 0;
729    }
730    let req = FeedRequest::from_headers(version, &uid, &headers, srv.channel_bytes);
731
732    let trace = std::env::var_os("LSL_TRACE_TCP").is_some();
733    if trace {
734        eprintln!("TRACE request {request_line:?}");
735        eprintln!("TRACE headers {headers:?}");
736    }
737
738    let accepted = match negotiate(&req, &srv) {
739        Outcome::Refuse(s) => {
740            if trace {
741                eprintln!("TRACE refused {} {}", s.code, s.message);
742            }
743            stream.write_all(s.to_wire().as_bytes())?;
744            return Ok(());
745        }
746        Outcome::Accept(a) => a,
747    };
748
749    // Protocol 1.00 carries every sample in a Boost archive
750    // (`src/sample.cpp:330`), which this implementation does not write.
751    //
752    // liblsl answers 505 only when the **major** version differs
753    // (`src/tcp_server.cpp:576`), so 505 is the wrong word here: a request for
754    // 1.00 against a 1.10 server is one that liblsl serves. There is no code
755    // in this protocol for "the version is one I cannot write".
756    //
757    // The connection therefore closes with nothing written. A peer reads the
758    // end of the stream, which is a state every client already handles, rather
759    // than a status line that a 1.00 client never looks for.
760    if accepted.data_protocol_version < 110 {
761        if trace {
762            eprintln!(
763                "TRACE closing: the peer agreed to protocol {}, which this side does not write",
764                accepted.data_protocol_version
765            );
766        }
767        return Ok(());
768    }
769
770    // A labstream inlet offers its features in one more header. An inlet
771    // that sent none gets the plain answer. `docs/extensions.md`.
772    let allowed = &config::get().features;
773    let offered = headers.get(features::HEADER_KEY).map(features::parse);
774    let mut answered = offered.as_deref().map(|o| features::answer(o, allowed));
775    let numbered = answered
776        .as_deref()
777        .is_some_and(|a| features::has(a, features::SEQ, 1));
778
779    // Negotiate `enc/1` (off by default, `docs/roadmap.md`, step 14).
780    let enc_policy = crate::enc::effective_policy();
781    let enc_key: Option<[u8; 32]> = if enc_policy.enabled {
782        let offered_enc = offered.as_deref().and_then(features::enc_request);
783        match (offered_enc, answered.as_mut()) {
784            (Some(peer_enc), Some(a)) => {
785                let kp = crate::enc::EphemeralKey::generate()?;
786                let pub_bytes = kp.public_bytes();
787                let key = kp.derive_feed_key(peer_enc.pubkey, true, enc_policy.psk.as_deref())?;
788                a.push(features::EncParam { pubkey: pub_bytes }.token());
789                if trace {
790                    eprintln!("TRACE enc: enabled (X25519 + ChaCha20-Poly1305)");
791                }
792                Some(key)
793            }
794            _ if enc_policy.required => {
795                let _ = stream.write_all(b"LSL/110 403 Encryption required\r\n\r\n");
796                let _ = stream.flush();
797                return Ok(());
798            }
799            _ => None,
800        }
801    } else {
802        None
803    };
804
805    // Negotiate `select/1` before `resume/1` and `dgram/1` because decimation
806    // changes the sample timeline and channel projection shrinks datagrams.
807    let selected: Option<features::SelectParam> = if let (false, Some(o), Some(a)) =
808        (shared.sync_mode, offered.as_deref(), answered.as_mut())
809    {
810        if let Some(sel) = features::select_request(
811            o,
812            allowed,
813            info.channel_count as usize,
814            info.nominal_srate,
815            info.format == labstream_wire::Format::String,
816        ) {
817            a.push(sel.token());
818            if trace {
819                eprintln!(
820                    "TRACE select: decimate={} channels={:?}",
821                    sel.decimate, sel.channels
822                );
823            }
824            Some(sel)
825        } else {
826            None
827        }
828    } else {
829        None
830    };
831    let decimating = selected.as_ref().is_some_and(|s| s.decimate > 1);
832    let out_channels = selected.as_ref().map_or(info.channel_count as usize, |s| {
833        s.output_channels(info.channel_count as usize)
834    });
835
836    let peer_label = stream
837        .peer_addr()
838        .map(|a| a.to_string())
839        .unwrap_or_default();
840
841    // A `resume` consumer gets its queue before the answer, because the
842    // answer holds the number of the first sample of the queue. liblsl makes
843    // the queue later (`src/tcp_server.cpp:746`), which a peer cannot see.
844    // `docs/extensions.md`, resend rule 1.
845    let mut resumed: Option<(Registered, Resend)> = None;
846    let mut resume_fresh_for_shm = false;
847    let queue_follows =
848        !shared.sync_mode && accepted.max_buffer_length > 0 && accepted.codec_order().is_some();
849    let allow_resume = queue_follows && !decimating;
850
851    // Check `shm/1` eligibility up front so fresh connections can negotiate
852    // `shm/1` cleanly alongside `resume/1` without allocating a redundant queue.
853    // When `enc/1` is active, keep samples on the authenticated encrypted TCP stream.
854    let wants_shm = queue_follows
855        && enc_key.is_none()
856        && info.format != labstream_wire::Format::String
857        && !decimating
858        && crate::shm::supported()
859        && offered
860            .as_deref()
861            .is_some_and(|o| features::shm_request(o, allowed));
862
863    if let (true, Some(o), Some(a)) = (allow_resume, offered.as_deref(), answered.as_mut()) {
864        if let Some(request) = features::resume_request(o, a, allowed) {
865            if shared.fanout.start_history() {
866                let from = match request {
867                    features::ResumeRequest::From(p) if p.epoch == shared.epoch => Some(p.number),
868                    _ => None,
869                };
870                if wants_shm && from.is_none() {
871                    let n = shared.fanout.next_number();
872                    a.push(
873                        features::ResumeParam {
874                            epoch: shared.epoch,
875                            number: n,
876                        }
877                        .token(),
878                    );
879                    resume_fresh_for_shm = true;
880                } else {
881                    let (queue, n) = shared.fanout.add_resumable_with_peer(
882                        accepted.max_buffer_length.max(1) as usize,
883                        peer_label.clone(),
884                    );
885                    a.push(
886                        features::ResumeParam {
887                            epoch: shared.epoch,
888                            number: n,
889                        }
890                        .token(),
891                    );
892                    if trace {
893                        eprintln!("TRACE resume: from {from:?}, first live sample {n}");
894                    }
895                    resumed = Some((
896                        Registered {
897                            fanout: &shared.fanout,
898                            queue,
899                        },
900                        Resend { from, until: n },
901                    ));
902                }
903            }
904        }
905    }
906
907    // Negotiate `comp/1` on numeric non-blocking sessions (`docs/extensions.md`,
908    // section `comp`). If `shm/1` activates after the headers, shared memory
909    // transfers raw bytes directly and `comp/1` is unused.
910    let compressed = if let (false, Some(o), Some(a)) =
911        (shared.sync_mode, offered.as_deref(), answered.as_mut())
912    {
913        let is_str = info.format == labstream_wire::Format::String;
914        if features::comp_request(o, allowed, is_str) {
915            a.push(features::Token::new(features::COMP, 1));
916            if trace {
917                eprintln!("TRACE comp: enabled");
918            }
919            true
920        } else {
921            false
922        }
923    } else {
924        false
925    };
926
927    // Negotiate `shm/1` on fresh numeric non-decimated sessions
928    // (`docs/extensions.md`, section `shm`).
929    let mut shm_writer: Option<Arc<crate::shm::ShmWriter>> = None;
930    if let (true, true, Some(a)) = (wants_shm, resumed.is_none(), answered.as_mut()) {
931        if let Ok(writer) = crate::shm::ShmWriter::create(
932            info.format,
933            out_channels,
934            accepted.max_buffer_length.max(1) as usize,
935        ) {
936            a.push(features::ShmParam { id: writer.id() }.token());
937            if trace {
938                eprintln!("TRACE shm: offered segment {:016x}", writer.id());
939            }
940            shm_writer = Some(Arc::new(writer));
941        }
942    }
943
944    // A `dgram` consumer gets a UDP socket of its own, and the answer gives
945    // its port and a cookie. `docs/extensions.md`, section `dgram`.
946    // When `shm/1` is offered on loopback, skip `dgram/1` so a container
947    // fallback uses pure TCP (`docs/roadmap.md`, step 9, criterion 3).
948    let peer_is_loopback = stream.peer_addr().is_ok_and(|p| p.ip().is_loopback());
949    let can_dgram = enc_key.is_none()
950        && (resumed.is_some() || resume_fresh_for_shm)
951        && !(shm_writer.is_some() && peer_is_loopback);
952    let mut dgram_socket: Option<(std::net::UdpSocket, u64, std::net::IpAddr)> = None;
953    if let (true, Some(o), Some(a)) = (can_dgram, offered.as_deref(), answered.as_mut()) {
954        let fits = crate::dgram_out::sample_fits(info.format, out_channels);
955        if fits && features::dgram_request(o, a, allowed) {
956            let peer = stream.peer_addr()?;
957            if let Some(sock) = crate::dgram_out::bind(peer) {
958                let cookie = crate::dgram_out::cookie();
959                let port = sock.local_addr()?.port();
960                a.push(features::DgramParam { port, cookie }.token());
961                if trace {
962                    eprintln!("TRACE dgram: UDP port {port}");
963                }
964                dgram_socket = Some((sock, cookie, peer.ip()));
965            }
966        }
967    }
968
969    stream.write_all(
970        accepted
971            .to_wire_with(srv.configured_version, &info.uid, answered.as_deref())
972            .as_bytes(),
973    )?;
974
975    let order = match accepted.codec_order() {
976        Some(o) => o,
977        None => return Ok(()),
978    };
979    let codec = Codec::new(info.format, info.channel_count as usize, order)
980        .with_suppress_subnormals(accepted.suppress_subnormals);
981    let data_codec = Codec::new(info.format, out_channels, order)
982        .with_suppress_subnormals(accepted.suppress_subnormals);
983
984    // Two test pattern samples open every feed. SPEC.md 6.
985    let mut out = Vec::new();
986    for off in TEST_PATTERN_OFFSETS {
987        let s = labstream_wire::test_pattern(info.format, info.channel_count as usize, off);
988        codec
989            .encode(&s, &mut out)
990            .map_err(|e| std::io::Error::other(e.to_string()))?;
991    }
992    if trace {
993        eprintln!(
994            "TRACE accepted version={} buffer={} chunk={} order={:?} test-pattern={} bytes",
995            accepted.data_protocol_version,
996            accepted.max_buffer_length,
997            accepted.max_chunk_length,
998            accepted.codec_order(),
999            out.len()
1000        );
1001    }
1002    stream.write_all(&out)?;
1003    stream.flush()?;
1004
1005    // A buffer length of zero or less sends nothing more. SPEC.md 9.
1006    if accepted.max_buffer_length <= 0 {
1007        return Ok(());
1008    }
1009
1010    // A blocking outlet keeps the socket instead of a queue. The handover
1011    // happens here, after the headers and the test pattern, which is where
1012    // liblsl does it (`src/tcp_server.cpp:733`).
1013    if shared.sync_mode {
1014        if trace {
1015            eprintln!("TRACE handing the socket to the blocking writer");
1016        }
1017        let mut set = shared.sync.lock().unwrap();
1018        // A numbered consumer gets its first record at once, under the lock
1019        // that numbers the writes. `docs/extensions.md`.
1020        let numbering = if numbered {
1021            let mut n = Numbering::new();
1022            let mut record = Vec::new();
1023            n.start(set.next, &mut record);
1024            stream.write_all(&record)?;
1025            stream.flush()?;
1026            Some(n)
1027        } else {
1028            None
1029        };
1030        set.next_consumer_id = set.next_consumer_id.wrapping_add(1);
1031        let id = set.next_consumer_id;
1032        set.list.push(SyncConsumer {
1033            id,
1034            peer: peer_label,
1035            stream,
1036            codec,
1037            numbering,
1038        });
1039        return Ok(());
1040    }
1041
1042    let meta_enabled = answered
1043        .as_deref()
1044        .is_some_and(|a| features::has(a, features::META, 1));
1045    // Snapshot live metadata before registering this consumer in the fanout so
1046    // updates emitted right after `wait_for_consumers()` are never coalesced
1047    // into the initial snapshot.
1048    let initial_meta = meta_enabled.then(|| shared.fanout.metadata_snapshot());
1049
1050    // Step 5 of `docs/extensions.md` (`shm`): wait up to 1 s for `shm-ok <token>`.
1051    // If the token matches, register the SHM ring directly in the fanout and
1052    // keep the TCP socket open to detect end-of-stream and recovery.
1053    // Otherwise unlink the segment and fall back cleanly to TCP/dgram.
1054    if let Some(writer) = shm_writer {
1055        if crate::shm::read_shm_reply(&mut stream, writer.token(), Duration::from_secs(1)) {
1056            if trace {
1057                eprintln!("TRACE shm: active on segment {:016x}", writer.id());
1058            }
1059            writer.unlink_name();
1060            drop(dgram_socket);
1061            let proj_channels = selected
1062                .as_ref()
1063                .and_then(|s| (!s.channels.is_empty()).then(|| s.channels.clone()));
1064            let _first_seq =
1065                shared
1066                    .fanout
1067                    .add_shm_with_peer(Arc::clone(&writer), peer_label, proj_channels);
1068            let _guard = RegisteredShm {
1069                fanout: &shared.fanout,
1070                writer: Arc::clone(&writer),
1071            };
1072            let mut meta_cursor = 0u64;
1073            let mut meta_buf = Vec::new();
1074            let mut meta_wire = Vec::new();
1075            if let Some((gen, snap)) = initial_meta {
1076                meta_cursor = gen;
1077                if !snap.is_empty() {
1078                    let mut vals: Vec<_> = snap.into_values().collect();
1079                    vals.sort_by_key(|u| u.seq);
1080                    for u in &vals {
1081                        labstream_proto::meta::write_record(&mut meta_wire, u);
1082                    }
1083                    if stream.write_all(&meta_wire).is_err() || stream.flush().is_err() {
1084                        let _ = stream.shutdown(std::net::Shutdown::Both);
1085                        return Ok(());
1086                    }
1087                    meta_wire.clear();
1088                }
1089            }
1090            let poll_timeout = if meta_enabled {
1091                Duration::from_millis(25)
1092            } else {
1093                Duration::from_millis(200)
1094            };
1095            let _ = stream.set_read_timeout(Some(poll_timeout));
1096            let mut probe = [0u8; 64];
1097            loop {
1098                if *shared.stop.lock().unwrap() || writer.is_closed() {
1099                    break;
1100                }
1101                if meta_enabled {
1102                    meta_buf.clear();
1103                    shared
1104                        .fanout
1105                        .read_metadata_since(&mut meta_cursor, &mut meta_buf);
1106                    if !meta_buf.is_empty() {
1107                        meta_wire.clear();
1108                        for u in &meta_buf {
1109                            labstream_proto::meta::write_record(&mut meta_wire, u);
1110                        }
1111                        if stream.write_all(&meta_wire).is_err() || stream.flush().is_err() {
1112                            break;
1113                        }
1114                    }
1115                }
1116                match stream.read(&mut probe) {
1117                    Ok(0) => break,
1118                    Ok(_) => {}
1119                    Err(ref e)
1120                        if e.kind() == std::io::ErrorKind::WouldBlock
1121                            || e.kind() == std::io::ErrorKind::TimedOut => {}
1122                    Err(_) => break,
1123                }
1124            }
1125            let _ = stream.shutdown(std::net::Shutdown::Both);
1126            return Ok(());
1127        } else if trace {
1128            eprintln!(
1129                "TRACE shm: fallback to TCP for segment {:016x}",
1130                writer.id()
1131            );
1132        }
1133        // `writer` drops here, unlinking the unused SHM segment immediately.
1134    }
1135
1136    // The header carries a count of samples, already converted from whatever
1137    // unit the peer's API used. SPEC.md 8.6.
1138    let (consumer, resend) = match resumed {
1139        Some((c, r)) => (c, Some(r)),
1140        None if resume_fresh_for_shm => {
1141            let (queue, n) = shared
1142                .fanout
1143                .add_resumable_with_peer(accepted.max_buffer_length.max(1) as usize, peer_label);
1144            (
1145                Registered {
1146                    fanout: &shared.fanout,
1147                    queue,
1148                },
1149                Some(Resend {
1150                    from: None,
1151                    until: n,
1152                }),
1153            )
1154        }
1155        None if decimating => (
1156            Registered {
1157                fanout: &shared.fanout,
1158                queue: shared
1159                    .fanout
1160                    .add_resumable_with_peer(accepted.max_buffer_length.max(1) as usize, peer_label)
1161                    .0,
1162            },
1163            None,
1164        ),
1165        None => (
1166            Registered {
1167                fanout: &shared.fanout,
1168                queue: shared
1169                    .fanout
1170                    .add_with_peer(accepted.max_buffer_length.max(1) as usize, peer_label),
1171            },
1172            None,
1173        ),
1174    };
1175
1176    // A chunk decides when one write happens. It is not a wire unit. SPEC.md 9.
1177    // A value of zero means no limit (`src/tcp_server.cpp:749-753`). This
1178    // outlet has no chunk size of its own.
1179    let max_chunk = if accepted.max_chunk_length > 0 {
1180        accepted.max_chunk_length as usize
1181    } else {
1182        usize::MAX
1183    };
1184
1185    // The inlet writes its requests on TCP. A thread reads them.
1186    let dgram = match dgram_socket {
1187        Some((socket, cookie, peer)) => Some(crate::dgram_out::Setup {
1188            socket,
1189            cookie,
1190            peer,
1191            requests: crate::dgram_out::read_requests(
1192                stream.try_clone()?,
1193                Arc::clone(&consumer.queue),
1194            ),
1195            queue: Arc::clone(&consumer.queue),
1196            tcp: stream.try_clone()?,
1197        }),
1198        None => None,
1199    };
1200
1201    let selector = selected.map(|sel| {
1202        labstream_proto::select::StreamSelector::new(sel, info.format, info.channel_count as usize)
1203    });
1204
1205    let meta_feed = initial_meta.map(|(gen, snap)| (&shared.fanout, gen, snap));
1206    let stop = || *shared.stop.lock().unwrap();
1207    let sent = if let Some(key) = enc_key {
1208        let mut enc_stream = crate::enc::EncWriter::new(&mut stream, &key)?;
1209        // Send an empty authenticated frame immediately so mismatched PSKs are
1210        // caught at connect time even on a quiet stream.
1211        enc_stream.write_frame(&[])?;
1212        enc_stream.flush()?;
1213        feed_with(
1214            &consumer.queue,
1215            &data_codec,
1216            &mut enc_stream,
1217            max_chunk,
1218            numbered,
1219            compressed,
1220            meta_feed,
1221            resend.as_ref().map(|r| (&shared.fanout, r)),
1222            dgram,
1223            selector,
1224            &stop,
1225            trace,
1226        )
1227    } else {
1228        feed_with(
1229            &consumer.queue,
1230            &data_codec,
1231            &mut stream,
1232            max_chunk,
1233            numbered,
1234            compressed,
1235            meta_feed,
1236            resend.as_ref().map(|r| (&shared.fanout, r)),
1237            dgram,
1238            selector,
1239            &stop,
1240            trace,
1241        )
1242    };
1243    // Shut down the shared TCP socket so the `dgram` request reader exits
1244    // immediately and the peer receives FIN without waiting for a watchdog.
1245    let _ = stream.shutdown(std::net::Shutdown::Both);
1246    if trace {
1247        eprintln!("TRACE session over after {sent} samples");
1248    }
1249    Ok(())
1250}
1251
1252/// A consumer queue in the fanout. The drop removes it, also when a write
1253/// fails before the session starts.
1254struct Registered<'a> {
1255    fanout: &'a Fanout,
1256    queue: Arc<SampleQueue>,
1257}
1258
1259impl Drop for Registered<'_> {
1260    fn drop(&mut self) {
1261        self.fanout.remove(&self.queue);
1262    }
1263}
1264
1265/// An active `shm/1` consumer ring in the fanout. Removing it on drop closes
1266/// the segment and unregisters it from future pushes.
1267struct RegisteredShm<'a> {
1268    fanout: &'a Fanout,
1269    writer: Arc<crate::shm::ShmWriter>,
1270}
1271
1272impl Drop for RegisteredShm<'_> {
1273    fn drop(&mut self) {
1274        self.writer.close();
1275        self.fanout.remove_shm(&self.writer);
1276    }
1277}
1278
1279/// What a `resume` connection sends from the history.
1280#[derive(Debug, Clone, Copy)]
1281struct Resend {
1282    /// The number `R` from the inlet, or `None` when nothing goes again.
1283    from: Option<u64>,
1284    /// `N`: the first number of the queue. The history sends only numbers
1285    /// below it.
1286    until: u64,
1287}
1288
1289/// The largest count of samples that one read of the history copies. A push
1290/// waits for at most one such copy. `docs/extensions.md`, resend rule 6.
1291pub(crate) const RESEND_BLOCK: usize = 256;
1292
1293/// Copy the samples of one consumer queue to its socket.
1294///
1295/// liblsl writes when a sample carries the push-through flag, or when the
1296/// count reaches the chunk size (`src/tcp_server.cpp:782`). Each push call of
1297/// liblsl sets the flag on its last sample by default
1298/// (`src/stream_outlet_impl.h:74`, `src/stream_outlet_impl.h:208-209`).
1299///
1300/// Here, the samples of one push call go into the queue with one lock. The
1301/// writer takes all samples that wait, and it writes when the count reaches
1302/// the chunk size or when the queue is empty. An empty queue therefore acts
1303/// as the push-through flag. When the writer is slower than the source, one
1304/// write can carry more than one push call. No sample waits for a later push.
1305///
1306/// When `numbered` is true, the consumer agreed to `seq/1`. A numbering
1307/// record then goes before the first sample, and before each sample whose
1308/// number does not follow the one before it. A record does not count toward
1309/// the chunk size. `docs/extensions.md`.
1310///
1311/// The result is the number of samples written.
1312#[cfg(test)]
1313fn feed<W: Write>(
1314    queue: &SampleQueue,
1315    codec: &Codec,
1316    out: &mut W,
1317    max_chunk: usize,
1318    numbered: bool,
1319    stop: &dyn Fn() -> bool,
1320    trace: bool,
1321) -> usize {
1322    feed_with(
1323        queue, codec, out, max_chunk, numbered, false, None, None, None, None, stop, trace,
1324    )
1325}
1326
1327/// Copy the samples of one consumer queue to its socket, with an optional
1328/// resend for the `resume` feature and optional channel/rate selection
1329/// (`select/1`) and lossless compression (`comp/1`).
1330///
1331/// With a resend, the connection first sends the history samples from `R`
1332/// up to `N - 1`, in blocks, each sample with its full timestamp. Then it
1333/// sends the queue. The first sample of the connection, and each sample
1334/// whose number does not follow the number before it, also carry the full
1335/// timestamp. `docs/extensions.md`, section `resume`.
1336#[allow(clippy::too_many_arguments)]
1337fn feed_with<W: Write>(
1338    queue: &SampleQueue,
1339    codec: &Codec,
1340    out: &mut W,
1341    max_chunk: usize,
1342    numbered: bool,
1343    compressed: bool,
1344    meta_init: Option<(
1345        &Fanout,
1346        u64,
1347        std::collections::BTreeMap<String, labstream_proto::meta::MetadataUpdate>,
1348    )>,
1349    resend: Option<(&Fanout, &Resend)>,
1350    dgram: Option<crate::dgram_out::Setup>,
1351    mut selector: Option<labstream_proto::select::StreamSelector>,
1352    stop: &dyn Fn() -> bool,
1353    trace: bool,
1354) -> usize {
1355    let decimating = selector.as_ref().is_some_and(|s| s.param().decimate > 1);
1356    let mut numbering = numbered.then(Numbering::new);
1357    let mut tcp_comp = (compressed && labstream_proto::comp::CompState::supports(codec.format))
1358        .then(|| labstream_proto::comp::CompState::new(codec.format, codec.channels));
1359    // The first history block decides the number of the first record.
1360    let mut history: Vec<PackedSample> = Vec::new();
1361    let mut block = match resend {
1362        Some((fanout, r)) => r
1363            .from
1364            .and_then(|from| fanout.read_history_packed(from, r.until, RESEND_BLOCK, &mut history)),
1365        None => None,
1366    };
1367    // The first record goes out at once, before any sample. A gap before
1368    // this connection is then visible on a quiet stream too.
1369    if let Some(n) = numbering.as_mut() {
1370        let next = if decimating {
1371            0
1372        } else {
1373            match block {
1374                Some((first, _)) => first,
1375                None => {
1376                    queue
1377                        .pop_many_numbered_packed(&mut Vec::new(), 0, Duration::ZERO)
1378                        .1
1379                }
1380            }
1381        };
1382        let mut record = Vec::new();
1383        n.start(next, &mut record);
1384        if out.write_all(&record).is_err() {
1385            return 0;
1386        }
1387        let _ = out.flush();
1388    }
1389    let mut meta_cursor: u64 = 0;
1390    let mut meta_queue: std::collections::VecDeque<labstream_proto::meta::MetadataUpdate> =
1391        std::collections::VecDeque::new();
1392    let mut meta_scratch: Vec<labstream_proto::meta::MetadataUpdate> = Vec::new();
1393    let meta_fanout = meta_init.as_ref().map(|(f, _, _)| *f);
1394    if let Some((_, gen, snap)) = meta_init {
1395        meta_cursor = gen;
1396        if !snap.is_empty() {
1397            let mut vals: Vec<_> = snap.into_values().collect();
1398            vals.sort_by_key(|u| u.seq);
1399            let mut init_meta = Vec::new();
1400            for u in &vals {
1401                labstream_proto::meta::write_record(&mut init_meta, u);
1402            }
1403            if out.write_all(&init_meta).is_err() {
1404                return 0;
1405            }
1406            let _ = out.flush();
1407        }
1408    }
1409    let mut batch: Vec<PackedSample> = Vec::new();
1410    let mut pending: Vec<u8> = Vec::new();
1411    let mut count = 0usize;
1412    let mut sent = 0usize;
1413    let mut write = |pending: &mut Vec<u8>, count: &mut usize, sent: &mut usize| -> bool {
1414        if trace && *sent == 0 {
1415            eprintln!("TRACE first data write, {} bytes", pending.len());
1416        }
1417        if let Err(e) = out.write_all(pending) {
1418            if trace {
1419                eprintln!("TRACE write failed after {sent} samples: {e}");
1420            }
1421            return false;
1422        }
1423        let _ = out.flush();
1424        *sent += *count;
1425        pending.clear();
1426        *count = 0;
1427        true
1428    };
1429
1430    let proj_channels: Option<Vec<u16>> = selector
1431        .as_ref()
1432        .and_then(|s| (!s.param().channels.is_empty()).then(|| s.param().channels.clone()));
1433
1434    // The resend. Each history sample has its full timestamp.
1435    let mut last: Option<u64> = None;
1436    while let Some((first, taken)) = block {
1437        if stop() {
1438            return sent;
1439        }
1440        for (i, s) in history.iter().enumerate() {
1441            let number = first.wrapping_add(i as u64);
1442            if let Some(n) = numbering.as_mut() {
1443                n.before(number, &mut pending);
1444            }
1445            let enc = match (proj_channels.as_deref(), tcp_comp.as_mut()) {
1446                (Some(chs), Some(c)) => {
1447                    let p = labstream_proto::select::project_packed(s, chs);
1448                    c.encode_tcp_sample(codec, &p, p.timestamp, &mut pending)
1449                }
1450                (None, Some(c)) => c.encode_tcp_sample(codec, s, s.timestamp, &mut pending),
1451                (Some(chs), None) => {
1452                    let p = labstream_proto::select::project_packed(s, chs);
1453                    codec.encode_packed(&p, &mut pending)
1454                }
1455                (None, None) => codec.encode_packed(s, &mut pending),
1456            };
1457            if enc.is_err() {
1458                return sent;
1459            }
1460            last = Some(number);
1461            count += 1;
1462            if count >= max_chunk && !write(&mut pending, &mut count, &mut sent) {
1463                return sent;
1464            }
1465        }
1466        // Each block goes out at once. The resend thus holds at most one
1467        // block of bytes, and a dead socket ends it after one block.
1468        if !pending.is_empty() && !write(&mut pending, &mut count, &mut sent) {
1469            return sent;
1470        }
1471        history.clear();
1472        let (fanout, r) = resend.expect("a block comes only from a resend");
1473        let next = first.wrapping_add(taken as u64);
1474        block = fanout.read_history_packed(next, r.until, RESEND_BLOCK, &mut history);
1475    }
1476    if !pending.is_empty() && !write(&mut pending, &mut count, &mut sent) {
1477        return sent;
1478    }
1479    if trace && last.is_some() {
1480        eprintln!("TRACE resume: resent {sent} samples");
1481    }
1482
1483    // A `dgram` connection runs its own live part. It needs `seq` and
1484    // `resume`, so the numbering and the fanout exist.
1485    // The numbering moves to that part only when it runs.
1486    if let (Some(setup), true, Some((fanout, _))) = (dgram, numbering.is_some(), resend) {
1487        let numbering = numbering.take().expect("checked above");
1488        return sent
1489            + crate::dgram_out::Live {
1490                queue,
1491                fanout,
1492                codec,
1493                channels: proj_channels,
1494                compressed: tcp_comp.is_some(),
1495                meta_enabled: meta_fanout.is_some(),
1496                meta_cursor,
1497                out,
1498                numbering,
1499                last,
1500                tcp_comp,
1501                setup,
1502                trace,
1503            }
1504            .run(stop);
1505    }
1506
1507    let mut full = Vec::new();
1508    let mut prev_raw: Option<u64> = None;
1509    let mut decimated_seq: u64 = 0;
1510    loop {
1511        if stop() || queue.is_closed() {
1512            break;
1513        }
1514        batch.clear();
1515        full.clear();
1516        let (taken, first) = if resend.is_some() || decimating {
1517            queue.pop_many_full_packed(
1518                &mut batch,
1519                &mut full,
1520                usize::MAX,
1521                Duration::from_millis(200),
1522            )
1523        } else {
1524            queue.pop_many_numbered_packed(&mut batch, usize::MAX, Duration::from_millis(200))
1525        };
1526        if taken == 0 {
1527            if let Some(f) = meta_fanout {
1528                meta_scratch.clear();
1529                f.read_metadata_since(&mut meta_cursor, &mut meta_scratch);
1530                meta_queue.extend(meta_scratch.drain(..));
1531                if !meta_queue.is_empty() {
1532                    while let Some(u) = meta_queue.pop_front() {
1533                        labstream_proto::meta::write_record(&mut pending, &u);
1534                    }
1535                    if !write(&mut pending, &mut count, &mut sent) {
1536                        return sent;
1537                    }
1538                }
1539            }
1540            continue;
1541        }
1542        if let Some(f) = meta_fanout {
1543            meta_scratch.clear();
1544            f.read_metadata_since(&mut meta_cursor, &mut meta_scratch);
1545            meta_queue.extend(meta_scratch.drain(..));
1546        }
1547        if decimating {
1548            let sel = selector.as_mut().expect("decimating requires selector");
1549            for (i, s) in batch.iter().enumerate() {
1550                let raw_num = first.wrapping_add(i as u64);
1551                while let Some(front) = meta_queue.front() {
1552                    if front.seq <= raw_num {
1553                        let u = meta_queue.pop_front().unwrap();
1554                        labstream_proto::meta::write_record(&mut pending, &u);
1555                    } else {
1556                        break;
1557                    }
1558                }
1559                if let Some(prev) = prev_raw {
1560                    let expected = prev.wrapping_add(1);
1561                    if raw_num > expected {
1562                        let raw_lost = raw_num - expected;
1563                        decimated_seq =
1564                            decimated_seq.wrapping_add(raw_lost / sel.param().decimate as u64);
1565                    }
1566                }
1567                prev_raw = Some(raw_num);
1568                if let Some(emitted) = sel.push(s, full[i]) {
1569                    if let Some(n) = numbering.as_mut() {
1570                        n.before(decimated_seq, &mut pending);
1571                    }
1572                    decimated_seq = decimated_seq.wrapping_add(1);
1573                    let enc = match tcp_comp.as_mut() {
1574                        Some(c) => {
1575                            c.encode_tcp_sample(codec, &emitted, emitted.timestamp, &mut pending)
1576                        }
1577                        None => codec.encode_packed(&emitted, &mut pending),
1578                    };
1579                    if enc.is_err() {
1580                        return sent;
1581                    }
1582                    count += 1;
1583                    if count >= max_chunk && !write(&mut pending, &mut count, &mut sent) {
1584                        return sent;
1585                    }
1586                }
1587            }
1588        } else {
1589            for (i, s) in batch.iter().enumerate() {
1590                let number = first.wrapping_add(i as u64);
1591                while let Some(front) = meta_queue.front() {
1592                    if front.seq <= number {
1593                        let u = meta_queue.pop_front().unwrap();
1594                        labstream_proto::meta::write_record(&mut pending, &u);
1595                    } else {
1596                        break;
1597                    }
1598                }
1599                if let Some(n) = numbering.as_mut() {
1600                    n.before(number, &mut pending);
1601                }
1602                // After a gap, a deduced timestamp has no correct sample before
1603                // it. `docs/extensions.md`, rule 5 of the resend timestamps.
1604                let ts = if resend.is_some() {
1605                    let use_ts = if last.map(|l| l.wrapping_add(1)) != Some(number) {
1606                        full[i]
1607                    } else {
1608                        s.timestamp
1609                    };
1610                    last = Some(number);
1611                    use_ts
1612                } else {
1613                    s.timestamp
1614                };
1615                let enc = match (proj_channels.as_deref(), tcp_comp.as_mut()) {
1616                    (Some(chs), Some(c)) => {
1617                        let p = labstream_proto::select::project_packed(s, chs);
1618                        c.encode_tcp_sample(codec, &p, ts, &mut pending)
1619                    }
1620                    (None, Some(c)) => c.encode_tcp_sample(codec, s, ts, &mut pending),
1621                    (Some(chs), None) => {
1622                        let p = labstream_proto::select::project_packed(s, chs);
1623                        codec.encode_packed_at(&p, ts, &mut pending)
1624                    }
1625                    (None, None) => codec.encode_packed_at(s, ts, &mut pending),
1626                };
1627                if enc.is_err() {
1628                    return sent;
1629                }
1630                count += 1;
1631                if count >= max_chunk && !write(&mut pending, &mut count, &mut sent) {
1632                    return sent;
1633                }
1634            }
1635        }
1636        // Flush any metadata updates emitted after the last sample in this batch.
1637        while let Some(u) = meta_queue.pop_front() {
1638            labstream_proto::meta::write_record(&mut pending, &u);
1639        }
1640        // The queue was empty when the batch came out, so nothing more is on
1641        // the way. Write what is left.
1642        if !pending.is_empty() && !write(&mut pending, &mut count, &mut sent) {
1643            return sent;
1644        }
1645    }
1646    sent
1647}
1648
1649fn find_double_crlf(buf: &[u8]) -> Option<usize> {
1650    buf.windows(4).position(|w| w == b"\r\n\r\n").map(|p| p + 4)
1651}
1652
1653impl Outlet {
1654    /// Send several samples that share one timestamp, with one lock.
1655    ///
1656    /// This is the same call as [`Outlet::push_chunk`]. It stays for the
1657    /// programs that use it.
1658    pub fn push_chunk_fast(&self, samples: &[Sample], timestamp: f64) {
1659        self.push_chunk(samples, timestamp);
1660    }
1661
1662    /// Send several samples, each with its own timestamp, with one lock.
1663    ///
1664    /// The timestamp rules of [`Outlet::push`] apply to each sample. A
1665    /// consumer receives the samples of one call together, so a consumer
1666    /// connection writes them with one socket write. SPEC.md 9.
1667    ///
1668    /// A blocking outlet writes the samples to each consumer with one write,
1669    /// before the call returns.
1670    pub fn push_samples(&self, samples: Vec<Sample>) {
1671        if samples.is_empty() {
1672            return;
1673        }
1674        let packed: Vec<PackedSample> = samples.into_iter().map(PackedSample::from).collect();
1675        self.push_samples_packed(packed);
1676    }
1677
1678    /// Send several [`PackedSample`]s, each with its own timestamp, with one lock.
1679    pub fn push_samples_packed(&self, mut samples: Vec<PackedSample>) {
1680        if samples.is_empty() {
1681            return;
1682        }
1683        for s in &mut samples {
1684            s.timestamp = self.stamp(s.timestamp);
1685        }
1686        if self.shared.sync_mode {
1687            write_blocking_many_packed(&self.shared, &samples);
1688            return;
1689        }
1690        self.shared.fanout.push_many_packed(&samples);
1691    }
1692
1693    /// Compute the timestamp of the first sample in a chunk of `count` samples.
1694    fn chunk_first_timestamp(&self, count: usize, timestamp: f64) -> f64 {
1695        let mut first = if timestamp == 0.0 {
1696            crate::clock()
1697        } else {
1698            timestamp
1699        };
1700        if self.info.nominal_srate != 0.0 && count > 1 {
1701            first -= (count - 1) as f64 / self.info.nominal_srate;
1702        }
1703        first
1704    }
1705
1706    /// Apply the two timestamp rules of [`Outlet::push`].
1707    fn stamp(&self, t: f64) -> f64 {
1708        if config::get().force_default_timestamps || t == 0.0 {
1709            clock()
1710        } else {
1711            t
1712        }
1713    }
1714
1715    /// Send several samples that share one timestamp. SPEC.md 9.2.
1716    ///
1717    /// The timestamp names the **last** sample. A stream with a rate counts
1718    /// backward from it, so the first sample is dated
1719    /// `timestamp - (count - 1) / rate`. Only that first sample carries a
1720    /// timestamp on the wire, and the rest carry the deduced tag.
1721    ///
1722    /// An application that acquires a block and stamps it on arrival therefore
1723    /// gets the right time for every sample in the block.
1724    ///
1725    /// The samples go to each consumer with one lock, and a consumer
1726    /// connection writes them with one socket write. SPEC.md 9.
1727    pub fn push_chunk(&self, samples: &[Sample], timestamp: f64) {
1728        if samples.is_empty() {
1729            return;
1730        }
1731        let first = self.chunk_first_timestamp(samples.len(), timestamp);
1732        let block: Vec<PackedSample> = samples
1733            .iter()
1734            .enumerate()
1735            .map(|(k, s)| {
1736                let t = if k == 0 {
1737                    first
1738                } else {
1739                    labstream_wire::DEDUCED_TIMESTAMP
1740                };
1741                PackedSample::from_sample(s).with_timestamp(t)
1742            })
1743            .collect();
1744        self.push_samples_packed(block);
1745    }
1746
1747    /// Send several [`PackedSample`]s that share one end timestamp.
1748    pub fn push_chunk_packed(&self, samples: &[PackedSample], timestamp: f64) {
1749        if samples.is_empty() {
1750            return;
1751        }
1752        let first = self.chunk_first_timestamp(samples.len(), timestamp);
1753        let block: Vec<PackedSample> = samples
1754            .iter()
1755            .enumerate()
1756            .map(|(k, s)| {
1757                let t = if k == 0 {
1758                    first
1759                } else {
1760                    labstream_wire::DEDUCED_TIMESTAMP
1761                };
1762                s.with_timestamp(t)
1763            })
1764            .collect();
1765        self.push_samples_packed(block);
1766    }
1767
1768    /// Send a flat interleaved chunk of `f32` channel values sharing `timestamp`.
1769    pub fn push_chunk_f32(&self, data: &[f32], timestamp: f64) {
1770        self.push_chunk_flat(data, timestamp, PackedSample::from_f32);
1771    }
1772
1773    /// Send a flat interleaved chunk of `f64` channel values sharing `timestamp`.
1774    pub fn push_chunk_f64(&self, data: &[f64], timestamp: f64) {
1775        self.push_chunk_flat(data, timestamp, PackedSample::from_f64);
1776    }
1777
1778    /// Send a flat interleaved chunk of `i32` channel values sharing `timestamp`.
1779    pub fn push_chunk_i32(&self, data: &[i32], timestamp: f64) {
1780        self.push_chunk_flat(data, timestamp, PackedSample::from_i32);
1781    }
1782
1783    /// Send a flat interleaved chunk of `i16` channel values sharing `timestamp`.
1784    pub fn push_chunk_i16(&self, data: &[i16], timestamp: f64) {
1785        self.push_chunk_flat(data, timestamp, PackedSample::from_i16);
1786    }
1787
1788    /// Send a flat interleaved chunk of `i8` channel values sharing `timestamp`.
1789    pub fn push_chunk_i8(&self, data: &[i8], timestamp: f64) {
1790        self.push_chunk_flat(data, timestamp, PackedSample::from_i8);
1791    }
1792
1793    /// Send a flat interleaved chunk of `i64` channel values sharing `timestamp`.
1794    pub fn push_chunk_i64(&self, data: &[i64], timestamp: f64) {
1795        self.push_chunk_flat(data, timestamp, PackedSample::from_i64);
1796    }
1797
1798    fn push_chunk_flat<T>(&self, data: &[T], timestamp: f64, pack: fn(f64, &[T]) -> PackedSample) {
1799        let chans = self.info.channel_count as usize;
1800        if chans == 0 || data.is_empty() || data.len() % chans != 0 {
1801            return;
1802        }
1803        let count = data.len() / chans;
1804        let first = self.chunk_first_timestamp(count, timestamp);
1805        let block: Vec<PackedSample> = data
1806            .chunks_exact(chans)
1807            .enumerate()
1808            .map(|(k, row)| {
1809                let t = if k == 0 {
1810                    first
1811                } else {
1812                    labstream_wire::DEDUCED_TIMESTAMP
1813                };
1814                pack(t, row)
1815            })
1816            .collect();
1817        self.push_samples_packed(block);
1818    }
1819}
1820
1821#[cfg(test)]
1822mod tests {
1823    use super::*;
1824    use labstream_wire::{ByteOrder, Format, Value};
1825    use std::sync::atomic::{AtomicBool, Ordering};
1826
1827    /// A writer that counts its calls and keeps the bytes.
1828    #[derive(Default)]
1829    struct Counting {
1830        writes: usize,
1831        bytes: Vec<u8>,
1832    }
1833
1834    impl Write for Counting {
1835        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1836            self.writes += 1;
1837            self.bytes.extend_from_slice(buf);
1838            Ok(buf.len())
1839        }
1840        fn flush(&mut self) -> std::io::Result<()> {
1841            Ok(())
1842        }
1843    }
1844
1845    fn samples(n: usize) -> Vec<Sample> {
1846        (0..n)
1847            .map(|k| Sample {
1848                timestamp: k as f64,
1849                values: vec![Value::F32(k as f32), Value::F32(0.5)],
1850            })
1851            .collect()
1852    }
1853
1854    /// Feed the queue that the caller filled, then stop.
1855    fn run(queue: &SampleQueue, max_chunk: usize) -> (usize, Counting) {
1856        let codec = Codec::new(Format::Float32, 2, ByteOrder::native());
1857        let mut out = Counting::default();
1858        let once = AtomicBool::new(false);
1859        // The first call to `stop` lets one round run. The second one stops.
1860        let stop = || once.swap(true, Ordering::SeqCst);
1861        let sent = feed(queue, &codec, &mut out, max_chunk, false, &stop, false);
1862        (sent, out)
1863    }
1864
1865    #[test]
1866    fn a_chunk_with_no_limit_goes_out_in_one_write() {
1867        let q = SampleQueue::new(1000);
1868        q.push_many(&samples(100));
1869        let (sent, out) = run(&q, usize::MAX);
1870        assert_eq!(sent, 100);
1871        assert_eq!(out.writes, 1, "one write for the whole chunk");
1872    }
1873
1874    #[test]
1875    fn a_chunk_limit_splits_the_writes() {
1876        let q = SampleQueue::new(1000);
1877        q.push_many(&samples(100));
1878        let (sent, out) = run(&q, 16);
1879        assert_eq!(sent, 100);
1880        // Six full chunks of 16, then the last 4 samples.
1881        assert_eq!(out.writes, 7);
1882    }
1883
1884    #[test]
1885    fn a_single_sample_is_not_held_back() {
1886        // A limit that one sample does not reach. The sample still goes out
1887        // at once, as the push-through flag of liblsl does.
1888        let q = SampleQueue::new(1000);
1889        q.push_many(&samples(1));
1890        let (sent, out) = run(&q, 16);
1891        assert_eq!(sent, 1);
1892        assert_eq!(out.writes, 1);
1893    }
1894
1895    /// Feed a numbered queue once, and read the records and samples back.
1896    fn run_numbered(
1897        queue: &SampleQueue,
1898        max_chunk: usize,
1899        order: ByteOrder,
1900    ) -> (Vec<Sample>, Vec<u64>, Counting) {
1901        use labstream_proto::seq::{peek, Next, RECORD_LEN};
1902        let codec = Codec::new(Format::Float32, 2, order);
1903        let mut out = Counting::default();
1904        let once = AtomicBool::new(false);
1905        let stop = || once.swap(true, Ordering::SeqCst);
1906        feed(queue, &codec, &mut out, max_chunk, true, &stop, false);
1907        let mut pos = 0;
1908        let (mut got, mut records) = (Vec::new(), Vec::new());
1909        while pos < out.bytes.len() {
1910            if let Next::Record(n) = peek(&out.bytes[pos..]) {
1911                records.push(n);
1912                pos += RECORD_LEN;
1913                continue;
1914            }
1915            let (s, used) = codec.decode(&out.bytes[pos..]).unwrap();
1916            got.push(s);
1917            pos += used;
1918        }
1919        (got, records, out)
1920    }
1921
1922    #[test]
1923    fn a_numbered_feed_starts_with_a_record() {
1924        for order in [ByteOrder::Little, ByteOrder::Big] {
1925            let q = SampleQueue::with_first_number(1000, 500);
1926            let sent = samples(20);
1927            q.push_many(&sent);
1928            let (got, records, _) = run_numbered(&q, usize::MAX, order);
1929            assert_eq!(got, sent);
1930            assert_eq!(records, vec![500], "one record, at the start");
1931        }
1932    }
1933
1934    #[test]
1935    fn a_full_queue_shows_as_a_gap_in_the_numbers() {
1936        // A queue of 4 that gets 10 samples keeps numbers 106 to 109.
1937        let q = SampleQueue::with_first_number(4, 100);
1938        q.push_many(&samples(10));
1939        let (got, records, _) = run_numbered(&q, usize::MAX, ByteOrder::native());
1940        assert_eq!(got.len(), 4);
1941        assert_eq!(records, vec![106]);
1942    }
1943
1944    #[test]
1945    fn a_record_does_not_count_toward_the_chunk_size() {
1946        let q = SampleQueue::with_first_number(1000, 7);
1947        q.push_many(&samples(32));
1948        let (got, records, out) = run_numbered(&q, 16, ByteOrder::native());
1949        assert_eq!(got.len(), 32);
1950        assert_eq!(records, vec![7]);
1951        // The opening record is a write of its own, at the start of the
1952        // connection. Then 16 samples go in each write.
1953        assert_eq!(out.writes, 3, "the record, then two chunks of 16");
1954    }
1955
1956    #[test]
1957    fn the_bytes_decode_to_the_same_samples() {
1958        let q = SampleQueue::new(1000);
1959        let sent = samples(50);
1960        q.push_many(&sent);
1961        let (_, out) = run(&q, 7);
1962        let codec = Codec::new(Format::Float32, 2, ByteOrder::native());
1963        let (got, used) = codec.decode_all(&out.bytes).unwrap();
1964        assert_eq!(used, out.bytes.len());
1965        assert_eq!(got, sent);
1966    }
1967
1968    // The `resume` resend. `docs/extensions.md`, section `resume`.
1969
1970    const RATE: f64 = 300.0;
1971
1972    /// Chunks of `len` samples, as `Outlet::push_chunk` makes them: a
1973    /// timestamp on the first sample, and the deduced tag on the others.
1974    fn push_chunks(f: &Fanout, from: i32, to: i32, len: i32) {
1975        let mut k = from;
1976        while k < to {
1977            let end = (k + len).min(to);
1978            let block: Vec<Sample> = (k..end)
1979                .map(|i| Sample {
1980                    timestamp: if i == k {
1981                        1000.0 + i as f64 / RATE + 0.000_123
1982                    } else {
1983                        labstream_wire::DEDUCED_TIMESTAMP
1984                    },
1985                    values: vec![Value::I32(i)],
1986                })
1987                .collect();
1988            f.push_many(&block);
1989            k = end;
1990        }
1991    }
1992
1993    /// A plain queue that gets every push, for a reference.
1994    fn witness(f: &Fanout) -> Arc<SampleQueue> {
1995        f.add(usize::MAX)
1996    }
1997
1998    /// The full timestamp of each sample that the witness got, as an inlet
1999    /// with no loss calculates it. The index is the value of the sample.
2000    fn reference(witness: &SampleQueue) -> Vec<u64> {
2001        let mut out = Vec::new();
2002        witness.pop_many(&mut out, usize::MAX, Duration::ZERO);
2003        let mut d = labstream_wire::TimestampDeducer::new(RATE);
2004        out.iter().map(|s| d.apply(s.timestamp).to_bits()).collect()
2005    }
2006
2007    struct Received {
2008        /// The value, the wire timestamp, and the full timestamp of each
2009        /// sample, as an inlet reads them.
2010        samples: Vec<(i32, f64, u64)>,
2011        records: Vec<u64>,
2012    }
2013
2014    /// Run one resume connection once, and read it back as an inlet does.
2015    fn run_resume(f: &Fanout, queue: &SampleQueue, resend: Resend) -> Received {
2016        // The resend asks once, and must go on. Then the live part stops
2017        // when the queue is empty.
2018        let calls = std::sync::atomic::AtomicUsize::new(0);
2019        let stop = || calls.fetch_add(1, Ordering::SeqCst) >= 1 && queue.is_empty();
2020        run_resume_with(f, queue, resend, &stop).0
2021    }
2022
2023    /// [`run_resume`] with the stop function of the caller. The result also
2024    /// gives the count of writes.
2025    fn run_resume_with(
2026        f: &Fanout,
2027        queue: &SampleQueue,
2028        resend: Resend,
2029        stop: &dyn Fn() -> bool,
2030    ) -> (Received, usize) {
2031        use labstream_proto::seq::{peek, Next, RECORD_LEN};
2032        let codec = Codec::new(Format::Int32, 1, ByteOrder::native());
2033        let mut out = Counting::default();
2034        feed_with(
2035            queue,
2036            &codec,
2037            &mut out,
2038            usize::MAX,
2039            true,
2040            false,
2041            None,
2042            Some((f, &resend)),
2043            None,
2044            None,
2045            stop,
2046            false,
2047        );
2048        let mut deducer = labstream_wire::TimestampDeducer::new(RATE);
2049        let mut got = Received {
2050            samples: Vec::new(),
2051            records: Vec::new(),
2052        };
2053        let mut pos = 0;
2054        while pos < out.bytes.len() {
2055            if let Next::Record(n) = peek(&out.bytes[pos..]) {
2056                got.records.push(n);
2057                pos += RECORD_LEN;
2058                continue;
2059            }
2060            let (s, used) = codec.decode(&out.bytes[pos..]).unwrap();
2061            let v = match s.values[0] {
2062                Value::I32(v) => v,
2063                _ => unreachable!(),
2064            };
2065            let full = deducer.apply(s.timestamp).to_bits();
2066            got.samples.push((v, s.timestamp, full));
2067            pos += used;
2068        }
2069        (got, out.writes)
2070    }
2071
2072    #[test]
2073    fn a_resend_gives_each_missing_sample_once_with_its_timestamp() {
2074        let f = Fanout::with_rate(RATE, crate::history::HistoryLimits::DEFAULT);
2075        f.start_history();
2076        let all = witness(&f);
2077        push_chunks(&f, 0, 30, 9);
2078        let (queue, n) = f.add_resumable(1000);
2079        assert_eq!(n, 30);
2080        push_chunks(&f, 30, 45, 9);
2081
2082        // Sample 10 is in the middle of a chunk.
2083        let got = run_resume(
2084            &f,
2085            &queue,
2086            Resend {
2087                from: Some(10),
2088                until: n,
2089            },
2090        );
2091        assert_eq!(got.records, vec![10], "the numbers have no gap");
2092        let values: Vec<i32> = got.samples.iter().map(|s| s.0).collect();
2093        assert_eq!(values, (10..45).collect::<Vec<_>>());
2094
2095        let want = reference(&all);
2096        for &(v, wire, full) in &got.samples {
2097            if v < 30 {
2098                assert_ne!(wire, labstream_wire::DEDUCED_TIMESTAMP, "resent sample {v}");
2099            }
2100            assert_eq!(full, want[v as usize], "sample {v}");
2101        }
2102        // The live samples keep the tags of their push. Sample 30 starts a
2103        // chunk, and sample 31 does not.
2104        let tag = |v: i32| got.samples.iter().find(|s| s.0 == v).unwrap().1;
2105        assert_ne!(tag(30), labstream_wire::DEDUCED_TIMESTAMP);
2106        assert_eq!(tag(31), labstream_wire::DEDUCED_TIMESTAMP);
2107    }
2108
2109    #[test]
2110    fn a_resend_starts_at_the_oldest_sample_when_the_history_is_too_short() {
2111        let limits = crate::history::HistoryLimits {
2112            seconds: 20.0 / RATE,
2113            bytes: usize::MAX,
2114            ..crate::history::HistoryLimits::DEFAULT
2115        };
2116        let f = Fanout::with_rate(RATE, limits);
2117        f.start_history();
2118        let all = witness(&f);
2119        push_chunks(&f, 0, 50, 7);
2120        let (queue, n) = f.add_resumable(1000);
2121        let got = run_resume(
2122            &f,
2123            &queue,
2124            Resend {
2125                from: Some(5),
2126                until: n,
2127            },
2128        );
2129        // The inlet counts 30 - 5 lost samples from this record.
2130        assert_eq!(got.records, vec![30]);
2131        assert_eq!(got.samples.first().map(|s| s.0), Some(30));
2132        assert_eq!(got.samples.len(), 20);
2133        let want = reference(&all);
2134        for &(v, _, full) in &got.samples {
2135            assert_eq!(full, want[v as usize], "sample {v}");
2136        }
2137    }
2138
2139    #[test]
2140    fn a_connection_with_nothing_to_resend_starts_at_the_queue() {
2141        // No number, a number equal to N, and a number above N.
2142        for from in [None, Some(20), Some(500)] {
2143            let f = Fanout::with_rate(RATE, crate::history::HistoryLimits::DEFAULT);
2144            f.start_history();
2145            let all = witness(&f);
2146            push_chunks(&f, 0, 20, 9);
2147            let (queue, n) = f.add_resumable(1000);
2148            assert_eq!(n, 20);
2149            // Sample 20 is in the middle of a chunk that starts at 18.
2150            push_chunks(&f, 20, 30, 9);
2151            let got = run_resume(&f, &queue, Resend { from, until: n });
2152            assert_eq!(got.records, vec![20], "from {from:?}");
2153            let values: Vec<i32> = got.samples.iter().map(|s| s.0).collect();
2154            assert_eq!(values, (20..30).collect::<Vec<_>>(), "from {from:?}");
2155            // The first sample of the connection carries its full timestamp.
2156            assert_ne!(got.samples[0].1, labstream_wire::DEDUCED_TIMESTAMP);
2157            let want = reference(&all);
2158            for &(v, _, full) in &got.samples {
2159                assert_eq!(full, want[v as usize], "from {from:?}, sample {v}");
2160            }
2161        }
2162    }
2163
2164    #[test]
2165    fn a_drop_in_the_queue_gives_a_full_timestamp_after_the_gap() {
2166        let f = Fanout::with_rate(RATE, crate::history::HistoryLimits::DEFAULT);
2167        f.start_history();
2168        let all = witness(&f);
2169        let (queue, n) = f.add_resumable(5);
2170        assert_eq!(n, 0);
2171        // One chunk of 12 into a queue of 5. The queue keeps 7 to 11, and the
2172        // only explicit timestamp, on sample 0, is gone.
2173        push_chunks(&f, 0, 12, 12);
2174        let got = run_resume(
2175            &f,
2176            &queue,
2177            Resend {
2178                from: None,
2179                until: n,
2180            },
2181        );
2182        // The queue dropped 0 to 6 before the first record.
2183        assert_eq!(got.records, vec![7]);
2184        let values: Vec<i32> = got.samples.iter().map(|s| s.0).collect();
2185        assert_eq!(values, vec![7, 8, 9, 10, 11]);
2186        assert_ne!(got.samples[0].1, labstream_wire::DEDUCED_TIMESTAMP);
2187        let want = reference(&all);
2188        for &(v, _, full) in &got.samples {
2189            assert_eq!(full, want[v as usize], "sample {v}");
2190        }
2191    }
2192
2193    #[test]
2194    fn a_long_resend_goes_out_block_by_block() {
2195        let f = Fanout::with_rate(RATE, crate::history::HistoryLimits::DEFAULT);
2196        f.start_history();
2197        let all = witness(&f);
2198        push_chunks(&f, 0, 1000, 9);
2199        let (queue, n) = f.add_resumable(5000);
2200        push_chunks(&f, 1000, 1010, 9);
2201        let calls = std::sync::atomic::AtomicUsize::new(0);
2202        // Four blocks of the resend ask first. Then the live part stops when
2203        // the queue is empty.
2204        let stop = || calls.fetch_add(1, Ordering::SeqCst) >= 4 && queue.is_empty();
2205        let (got, writes) = run_resume_with(
2206            &f,
2207            &queue,
2208            Resend {
2209                from: Some(0),
2210                until: n,
2211            },
2212            &stop,
2213        );
2214        assert_eq!(got.records, vec![0]);
2215        let values: Vec<i32> = got.samples.iter().map(|s| s.0).collect();
2216        assert_eq!(values, (0..1010).collect::<Vec<_>>());
2217        // The record, four history blocks, and the live samples.
2218        assert_eq!(writes, 6);
2219        let want = reference(&all);
2220        for &(v, _, full) in &got.samples {
2221            assert_eq!(full, want[v as usize], "sample {v}");
2222        }
2223    }
2224
2225    #[test]
2226    fn samples_that_leave_the_history_during_a_resend_show_as_gaps() {
2227        // A history of 600 samples.
2228        let limits = crate::history::HistoryLimits {
2229            seconds: 2.0,
2230            bytes: usize::MAX,
2231            ..crate::history::HistoryLimits::DEFAULT
2232        };
2233        let f = Fanout::with_rate(RATE, limits);
2234        f.start_history();
2235        let all = witness(&f);
2236        push_chunks(&f, 0, 600, 9);
2237        let (queue, n) = f.add_resumable(5000);
2238        assert_eq!(n, 600);
2239        // Before the first two blocks go out, the outlet pushes 300 more
2240        // samples each time. The history then loses its oldest samples.
2241        let calls = std::sync::atomic::AtomicUsize::new(0);
2242        let stop = || {
2243            let c = calls.fetch_add(1, Ordering::SeqCst);
2244            if c < 2 {
2245                let from = 600 + 300 * c as i32;
2246                push_chunks(&f, from, from + 300, 9);
2247                false
2248            } else {
2249                queue.is_empty()
2250            }
2251        };
2252        let (got, _) = run_resume_with(
2253            &f,
2254            &queue,
2255            Resend {
2256                from: Some(0),
2257                until: n,
2258            },
2259            &stop,
2260        );
2261        // Block 0 was read before the first removal. The second read starts
2262        // at the oldest sample, 300. The third read finds nothing below 600.
2263        assert_eq!(got.records, vec![0, 300, 600]);
2264        let mut want_values: Vec<i32> = (0..256).collect();
2265        want_values.extend(300..556);
2266        want_values.extend(600..1200);
2267        let values: Vec<i32> = got.samples.iter().map(|s| s.0).collect();
2268        assert_eq!(values, want_values);
2269        // The first sample after each gap carries its full timestamp, so each
2270        // timestamp is correct.
2271        let want = reference(&all);
2272        for &(v, wire, full) in &got.samples {
2273            assert_eq!(full, want[v as usize], "sample {v}");
2274            if v == 600 {
2275                assert_ne!(wire, labstream_wire::DEDUCED_TIMESTAMP);
2276            }
2277        }
2278    }
2279}