Skip to main content

labstream_net/
inlet.rs

1//! The inlet: a resolver and a TCP feed client.
2
3use crate::clock::{ClockState, LiveSource};
4use crate::config;
5use crate::health::{Gap, GapKind, GapTracker, InletHealth, LatencyProbe, MAX_GAPS};
6use crate::info::StreamInfo;
7use crate::queue::SampleQueue;
8use labstream_proto::discovery;
9use labstream_proto::features;
10use labstream_proto::feed::{FeedClient, FeedParams, State, TestPatternError};
11use labstream_time::{flags, PostProcessor};
12use labstream_wire::{PackedSample, Sample};
13use std::collections::VecDeque;
14use std::io::{Read, Write};
15use std::net::{Shutdown, SocketAddr, TcpStream, UdpSocket};
16use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
17use std::sync::{Arc, Mutex};
18use std::time::{Duration, Instant};
19
20/// Send a discovery query and collect the answers. SPEC.md 2.
21///
22/// The query identifier is an opaque token. This function builds one, sends
23/// it, and drops any answer that carries a different value. It never derives
24/// the value of another implementation. SPEC.md 2.3.
25pub fn resolve(query: &str, minimum: usize, timeout: Duration) -> std::io::Result<Vec<StreamInfo>> {
26    let cfg = config::get();
27    let mut wave = QueryWave::open()?;
28    let end = Instant::now() + timeout;
29    let mut found: Vec<StreamInfo> = Vec::new();
30    let mut round: u32 = 0;
31
32    while Instant::now() < end {
33        wave.send(query);
34        let run_fallback = match cfg.fallback_discovery {
35            config::FallbackDiscovery::Off => false,
36            config::FallbackDiscovery::Subnet => true,
37            config::FallbackDiscovery::Auto => round > 0 && found.len() < minimum,
38        };
39        if !run_fallback {
40            let left = end.saturating_duration_since(Instant::now());
41            let window = left.min(Duration::from_millis(300));
42            collect_into(&mut wave, window, &mut found);
43            if found.len() >= minimum {
44                return Ok(found);
45            }
46        } else {
47            // Phase A: directed subnet broadcast and ARP neighbors (zero cold ARP misses).
48            wave.send_fallback_fast(query);
49            let left = end.saturating_duration_since(Instant::now());
50            let fast_window = left.min(Duration::from_millis(150));
51            collect_into(&mut wave, fast_window, &mut found);
52            if found.len() >= minimum {
53                return Ok(found);
54            }
55
56            // Phase B: local /24 (or smaller) unicast probe on port 16571 first,
57            // then base_port range if still unanswered.
58            if Instant::now() < end {
59                wave.send_fallback_subnet_mcast_port(query);
60                let left = end.saturating_duration_since(Instant::now());
61                let sub_window = left.min(Duration::from_millis(150));
62                collect_into(&mut wave, sub_window, &mut found);
63                if found.len() >= minimum {
64                    return Ok(found);
65                }
66            }
67            if Instant::now() < end {
68                wave.send_fallback_subnet_data_ports(query, round.saturating_sub(1));
69                let left = end.saturating_duration_since(Instant::now());
70                let sub_window = left.min(Duration::from_millis(150));
71                collect_into(&mut wave, sub_window, &mut found);
72                if found.len() >= minimum {
73                    return Ok(found);
74                }
75            }
76
77            // Phase C: when UDP to KnownPeers finds nothing, try TCP LSL:shortinfo
78            // so a network that drops all UDP still discovers known peers.
79            if !cfg.known_peers.is_empty() && Instant::now() < end {
80                let tcp_budget = end
81                    .saturating_duration_since(Instant::now())
82                    .min(Duration::from_millis(400));
83                for info in probe_peers_tcp(&cfg.known_peers, query, tcp_budget) {
84                    if !found.iter().any(|f| f.uid == info.uid) {
85                        found.push(info);
86                    }
87                }
88                if found.len() >= minimum {
89                    return Ok(found);
90                }
91            }
92        }
93        round = round.saturating_add(1);
94    }
95    Ok(found)
96}
97
98fn collect_into(wave: &mut QueryWave, window: Duration, found: &mut Vec<StreamInfo>) {
99    if window.is_zero() {
100        return;
101    }
102    let seen: Vec<String> = found.iter().map(|f| f.uid.clone()).collect();
103    for info in wave.collect(window, |uid| seen.iter().any(|u| u == uid)) {
104        if !found.iter().any(|f| f.uid == info.uid) {
105            found.push(info);
106        }
107    }
108}
109
110/// One set of sockets that sends a query and reads the answers.
111///
112/// A one-shot resolve and a background resolver send the same wave, so the
113/// sockets live here and both callers borrow them.
114///
115/// # One leg for each protocol
116///
117/// liblsl runs a separate attempt per protocol. Its receiving socket has one
118/// protocol, and it sends only to the groups of that protocol
119/// (`src/resolve_attempt_udp.cpp:174`). The same shape is used here, because
120/// the query carries the port that the answer must return to, and that port
121/// belongs to one socket.
122pub(crate) struct QueryWave {
123    legs: Vec<Leg>,
124    /// The token that this wave carries. An answer with a different token
125    /// belongs to another resolver. SPEC.md 2.3.
126    query_id: String,
127    buf: Vec<u8>,
128}
129
130struct Leg {
131    /// True when this leg speaks IPv6.
132    v6: bool,
133    /// The socket that answers arrive on. Unicast queries leave from this
134    /// socket too, so the reply returns on the same 5-tuple and passes
135    /// stateful firewalls such as Windows Defender Firewall.
136    rx: UdpSocket,
137    /// One socket for each local address, plus one bound to any address.
138    senders: Vec<UdpSocket>,
139    return_port: u16,
140    targets: Vec<String>,
141}
142
143impl QueryWave {
144    pub(crate) fn open() -> std::io::Result<QueryWave> {
145        let cfg = config::get();
146        let mut legs = Vec::new();
147        if cfg.allow_ipv4 {
148            if let Ok(leg) = Leg::open(false) {
149                legs.push(leg);
150            }
151        }
152        if cfg.allow_ipv6 {
153            if let Ok(leg) = Leg::open(true) {
154                legs.push(leg);
155            }
156        }
157        if legs.is_empty() {
158            return Err(std::io::Error::other(
159                "no socket could be opened for a query",
160            ));
161        }
162        Ok(QueryWave {
163            legs,
164            query_id: crate::make_query_id(),
165            buf: vec![0u8; 65536],
166        })
167    }
168
169    /// Send one wave of queries, on every protocol.
170    pub(crate) fn send(&self, query: &str) {
171        let cfg = config::get();
172        self.send_multicast_only(query);
173        if !cfg.known_peers.is_empty() {
174            self.send_peers_only(query, &cfg.known_peers);
175        }
176    }
177
178    /// Send only to configured multicast and broadcast targets, with no
179    /// `KnownPeers` and no fallback paths.
180    pub(crate) fn send_multicast_only(&self, query: &str) {
181        let cfg = config::get();
182        for leg in &self.legs {
183            let msg = discovery::build_query(query, leg.return_port, &self.query_id);
184            for s in std::iter::once(&leg.rx).chain(leg.senders.iter()) {
185                // A multicast or broadcast query goes to the multicast port.
186                // SPEC.md 1.1.
187                for addr in &leg.targets {
188                    let _ = s.send_to(&msg, (addr.as_str(), cfg.multicast_port));
189                }
190                for p in cfg.base_port..cfg.base_port + cfg.port_range {
191                    for addr in &leg.targets {
192                        let _ = s.send_to(&msg, (addr.as_str(), p));
193                    }
194                }
195            }
196        }
197    }
198
199    /// Send unicast queries to `peers` directly from `leg.rx` so the reply
200    /// returns on the same port and passes stateful firewalls.
201    pub(crate) fn send_peers_only(&self, query: &str, peers: &[String]) {
202        let cfg = config::get();
203        for leg in &self.legs {
204            let msg = discovery::build_query(query, leg.return_port, &self.query_id);
205            for addr in peers {
206                let _ = leg.rx.send_to(&msg, (addr.as_str(), cfg.multicast_port));
207                for p in cfg.base_port..cfg.base_port + cfg.port_range {
208                    let _ = leg.rx.send_to(&msg, (addr.as_str(), p));
209                }
210            }
211        }
212    }
213
214    /// Send all UDP fallback discovery paths (directed broadcast, ARP
215    /// neighbors, and local `/24` unicast probes). `docs/discovery.md`.
216    pub(crate) fn send_fallback(&self, query: &str, round: u32) {
217        self.send_fallback_fast(query);
218        self.send_fallback_subnet_mcast_port(query);
219        self.send_fallback_subnet_data_ports(query, round);
220    }
221
222    /// Send directed subnet broadcasts and ARP neighbor unicast queries.
223    pub(crate) fn send_fallback_fast(&self, query: &str) {
224        let cfg = config::get();
225        let ifaces = crate::netif::local_ipv4_interfaces();
226        let neighbors = crate::netif::local_ipv4_neighbors();
227        for leg in &self.legs {
228            if leg.v6 {
229                continue;
230            }
231            let msg = discovery::build_query(query, leg.return_port, &self.query_id);
232            // 1. Directed subnet broadcast on each active non-loopback IPv4 interface.
233            for iface in &ifaces {
234                if let Some(bcast) = iface.broadcast {
235                    let _ = leg.rx.send_to(&msg, (bcast, cfg.multicast_port));
236                    for s in &leg.senders {
237                        let _ = s.send_to(&msg, (bcast, cfg.multicast_port));
238                    }
239                    for p in cfg.base_port..cfg.base_port + cfg.port_range {
240                        let _ = leg.rx.send_to(&msg, (bcast, p));
241                    }
242                }
243            }
244            // 2. Unicast to known ARP/neighbor cache peers across the full port range.
245            for ip in &neighbors {
246                let _ = leg.rx.send_to(&msg, (*ip, cfg.multicast_port));
247                for p in cfg.base_port..cfg.base_port + cfg.port_range {
248                    let _ = leg.rx.send_to(&msg, (*ip, p));
249                }
250            }
251        }
252    }
253
254    /// Probe local `/24` (or smaller) hosts on `multicast_port` (`16571`).
255    ///
256    /// Both liblsl and labstream outlets answer unicast on port 16571, so one
257    /// packet per host stays well inside the kernel send buffer even on a cold
258    /// ARP table.
259    pub(crate) fn send_fallback_subnet_mcast_port(&self, query: &str) {
260        let cfg = config::get();
261        let ifaces = crate::netif::local_ipv4_interfaces();
262        let neighbors = crate::netif::local_ipv4_neighbors();
263        for leg in &self.legs {
264            if leg.v6 {
265                continue;
266            }
267            let msg = discovery::build_query(query, leg.return_port, &self.query_id);
268            for iface in &ifaces {
269                for peer in iface.subnet_peers() {
270                    if neighbors.contains(&peer) {
271                        continue;
272                    }
273                    let _ = leg.rx.send_to(&msg, (peer, cfg.multicast_port));
274                }
275            }
276        }
277    }
278
279    /// Probe local `/24` (or smaller) hosts on `base_port` and subsequent ports.
280    pub(crate) fn send_fallback_subnet_data_ports(&self, query: &str, round: u32) {
281        let cfg = config::get();
282        let ifaces = crate::netif::local_ipv4_interfaces();
283        let neighbors = crate::netif::local_ipv4_neighbors();
284        let extra_ports = if round == 0 {
285            1u16
286        } else {
287            8u16.min(cfg.port_range)
288        };
289        for leg in &self.legs {
290            if leg.v6 {
291                continue;
292            }
293            let msg = discovery::build_query(query, leg.return_port, &self.query_id);
294            for iface in &ifaces {
295                for peer in iface.subnet_peers() {
296                    if neighbors.contains(&peer) {
297                        continue;
298                    }
299                    for p in cfg.base_port..cfg.base_port + extra_ports {
300                        let _ = leg.rx.send_to(&msg, (peer, p));
301                    }
302                }
303            }
304        }
305    }
306
307    /// Read answers until the time runs out.
308    ///
309    /// `skip` drops an answer whose identifier the caller already holds.
310    pub(crate) fn collect(
311        &mut self,
312        window: Duration,
313        skip: impl Fn(&str) -> bool,
314    ) -> Vec<StreamInfo> {
315        let mut out: Vec<StreamInfo> = Vec::new();
316        let end = Instant::now() + window;
317        // Each socket is read in turn, with a short wait, so one quiet
318        // protocol does not hold up the other.
319        while Instant::now() < end {
320            let mut got_any = false;
321            for leg in &self.legs {
322                loop {
323                    match leg.rx.recv_from(&mut self.buf) {
324                        Ok((n, from)) => {
325                            got_any = true;
326                            let answer = match discovery::parse_answer(&self.buf[..n]) {
327                                Some(a) => a,
328                                None => continue,
329                            };
330                            // An answer to another query is dropped.
331                            if answer.query_id != self.query_id {
332                                continue;
333                            }
334                            if let Some(mut info) = StreamInfo::from_shortinfo_xml(&answer.xml) {
335                                stamp_address(&mut info, from);
336                                if !skip(&info.uid) && !out.iter().any(|f| f.uid == info.uid) {
337                                    out.push(info);
338                                }
339                            }
340                        }
341                        // Windows Winsock queues WSAECONNRESET (10054) on a UDP
342                        // socket when a prior send hits a closed port. Drain it
343                        // immediately so replies behind it are read without delay.
344                        Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => continue,
345                        Err(_) => break,
346                    }
347                }
348            }
349            if !got_any {
350                std::thread::sleep(Duration::from_millis(5));
351            }
352        }
353        out
354    }
355}
356
357/// Write the address that an answer came from into the description.
358///
359/// An outlet leaves the field empty, and the resolver of the peer fills it in
360/// (`src/resolve_attempt_udp.cpp:135-140`). Without this an inlet has no
361/// address to connect to.
362fn stamp_address(info: &mut StreamInfo, from: SocketAddr) {
363    match from {
364        SocketAddr::V4(a) => {
365            if info.v4address.is_empty() {
366                info.v4address = a.ip().to_string();
367            }
368        }
369        SocketAddr::V6(a) => {
370            if info.v6address.is_empty() {
371                // A link-local address only names a machine together with the
372                // interface it arrived on. Without that number a connection
373                // fails with an invalid argument. asio writes the same form,
374                // and liblsl stores it as it stands
375                // (`src/resolve_attempt_udp.cpp:140`).
376                info.v6address = if a.scope_id() != 0 {
377                    format!("{}%{}", a.ip(), a.scope_id())
378                } else {
379                    a.ip().to_string()
380                };
381            }
382        }
383    }
384}
385
386impl Leg {
387    fn open(v6: bool) -> std::io::Result<Leg> {
388        let cfg = config::get();
389        let any: std::net::IpAddr = if v6 {
390            std::net::Ipv6Addr::UNSPECIFIED.into()
391        } else {
392            std::net::Ipv4Addr::UNSPECIFIED.into()
393        };
394        let rx = UdpSocket::bind((any, 0))?;
395        if v6 {
396            let _ = rx.set_multicast_loop_v6(true);
397            let _ = socket2::SockRef::from(&rx).set_multicast_hops_v6(cfg.multicast_ttl);
398        } else {
399            rx.set_broadcast(true)?;
400            let _ = rx.set_multicast_ttl_v4(cfg.multicast_ttl);
401            let _ = rx.set_multicast_loop_v4(true);
402        }
403        // Keep `rx` non-blocking so neither `collect` nor a cold-ARP `/24`
404        // fallback sweep ever stalls on a blocking send or receive timeout.
405        rx.set_nonblocking(true)?;
406        let _ = socket2::SockRef::from(&rx).set_send_buffer_size(1024 * 1024);
407        let return_port = rx.local_addr()?.port();
408
409        // A query must leave by every interface that carries multicast,
410        // because a peer joins the group on one of them. liblsl walks the same
411        // list (`src/resolve_attempt_udp.cpp`, send_next_query).
412        //
413        // The standard library has no call that selects the outgoing interface
414        // for a multicast send. Binding a socket to a local address does the
415        // same thing, so this opens one socket for each address.
416        let mut senders: Vec<UdpSocket> = Vec::new();
417        if !v6 {
418            for a in crate::local_ipv4_addresses() {
419                if let Ok(s) = UdpSocket::bind((a, 0)) {
420                    let _ = s.set_broadcast(true);
421                    let _ = s.set_multicast_ttl_v4(cfg.multicast_ttl);
422                    let _ = s.set_multicast_loop_v4(true);
423                    senders.push(s);
424                }
425            }
426        }
427        // The query reaches as far as the scope of the configuration. liblsl
428        // sets the same value (`src/resolve_attempt_udp.cpp:45`).
429        let one = UdpSocket::bind((any, 0))?;
430        if v6 {
431            let _ = one.set_multicast_loop_v6(true);
432            let _ = socket2::SockRef::from(&one).set_multicast_hops_v6(cfg.multicast_ttl);
433        } else {
434            one.set_broadcast(true)?;
435            let _ = one.set_multicast_ttl_v4(cfg.multicast_ttl);
436            let _ = one.set_multicast_loop_v4(true);
437        }
438        senders.push(one);
439
440        // Only the groups of this protocol.
441        let mut targets: Vec<String> = cfg
442            .multicast_addresses
443            .iter()
444            .filter(|a| match a.parse::<std::net::IpAddr>() {
445                Ok(std::net::IpAddr::V6(_)) => v6,
446                Ok(std::net::IpAddr::V4(_)) => !v6,
447                Err(_) => false,
448            })
449            .cloned()
450            .collect();
451        if v6 && !targets.iter().any(|t| t == "::1") {
452            // The loopback carries no group, so a stream on this machine needs
453            // its address named directly.
454            targets.push("::1".to_string());
455        }
456
457        Ok(Leg {
458            v6,
459            rx,
460            senders,
461            return_port,
462            targets,
463        })
464    }
465}
466
467/// Probe `peers` over TCP using `LSL:shortinfo` on `base_port..base_port + port_range`.
468///
469/// Both liblsl (`src/tcp_server.cpp:502-555`) and labstream answer
470/// `LSL:shortinfo` on TCP, so this finds streams on `KnownPeers` even when a
471/// firewall drops all UDP packets.
472pub(crate) fn probe_peers_tcp(peers: &[String], query: &str, budget: Duration) -> Vec<StreamInfo> {
473    use std::net::ToSocketAddrs;
474    let cfg = config::get();
475    let mut targets: Vec<SocketAddr> = Vec::new();
476    for peer in peers {
477        let mut addrs: Vec<std::net::IpAddr> = Vec::new();
478        if let Ok(ip) = peer.parse::<std::net::IpAddr>() {
479            addrs.push(ip);
480        } else if let Ok(iter) = (peer.as_str(), cfg.base_port).to_socket_addrs() {
481            for sa in iter {
482                if !addrs.contains(&sa.ip()) {
483                    addrs.push(sa.ip());
484                }
485            }
486        }
487        for ip in addrs {
488            for p in cfg.base_port..cfg.base_port + cfg.port_range {
489                targets.push(SocketAddr::new(ip, p));
490            }
491        }
492    }
493    if targets.is_empty() {
494        return Vec::new();
495    }
496    let connect_timeout = budget.min(Duration::from_millis(200));
497    let req = format!("LSL:shortinfo\r\n{query}\r\n");
498    let found: Arc<Mutex<Vec<StreamInfo>>> = Arc::new(Mutex::new(Vec::new()));
499    // Probe in small concurrent batches so closed/filtered ports do not serialize.
500    let mut handles = Vec::new();
501    let chunk_size = (targets.len() / 8).max(1);
502    for chunk in targets.chunks(chunk_size) {
503        let chunk = chunk.to_vec();
504        let req = req.clone();
505        let found = Arc::clone(&found);
506        let deadline = Instant::now() + budget;
507        handles.push(std::thread::spawn(move || {
508            for addr in chunk {
509                if Instant::now() >= deadline {
510                    break;
511                }
512                let left = deadline.saturating_duration_since(Instant::now());
513                let Ok(mut stream) = TcpStream::connect_timeout(&addr, connect_timeout.min(left))
514                else {
515                    continue;
516                };
517                let _ = stream.set_read_timeout(Some(Duration::from_millis(200)));
518                let _ = stream.set_write_timeout(Some(Duration::from_millis(200)));
519                if stream.write_all(req.as_bytes()).is_err() || stream.flush().is_err() {
520                    continue;
521                }
522                let mut xml = String::new();
523                let _ = stream.read_to_string(&mut xml);
524                if let Some(mut info) = StreamInfo::from_shortinfo_xml(&xml) {
525                    stamp_address(&mut info, addr);
526                    let mut list = found.lock().unwrap();
527                    if !list.iter().any(|s| s.uid == info.uid) {
528                        list.push(info);
529                    }
530                }
531            }
532        }));
533    }
534    for h in handles {
535        let _ = h.join();
536    }
537    match Arc::try_unwrap(found) {
538        Ok(m) => m.into_inner().unwrap(),
539        Err(a) => a.lock().unwrap().clone(),
540    }
541}
542
543/// Where the data of a stream lives.
544///
545/// A description that discovery returned carries the address that the answer
546/// came from. A description that a program built by hand carries none, and the
547/// stream can then only be on this machine.
548///
549/// liblsl takes the IPv4 endpoint when the description holds one, and the IPv6
550/// endpoint otherwise (`src/inlet_connection.cpp:115-125`).
551pub(crate) fn data_endpoint(info: &StreamInfo) -> std::io::Result<SocketAddr> {
552    endpoint(
553        &info.v4address,
554        info.v4data_port,
555        &info.v6address,
556        info.v6data_port,
557    )
558}
559
560/// The host and port that answer a time probe.
561pub(crate) fn service_endpoint(info: &StreamInfo) -> Option<SocketAddr> {
562    if !info.v4address.is_empty() && info.v4service_port != 0 {
563        return format!("{}:{}", info.v4address, info.v4service_port)
564            .parse()
565            .ok();
566    }
567    if !info.v6address.is_empty() && info.v6service_port != 0 {
568        return v6_endpoint(&info.v6address, info.v6service_port).ok();
569    }
570    format!("127.0.0.1:{}", info.v4service_port).parse().ok()
571}
572
573fn endpoint(v4: &str, v4port: u16, v6: &str, v6port: u16) -> std::io::Result<SocketAddr> {
574    if !v4.is_empty() && v4port != 0 {
575        return format!("{v4}:{v4port}")
576            .parse()
577            .map_err(|_| std::io::Error::other(format!("cannot read the address {v4}")));
578    }
579    if !v6.is_empty() && v6port != 0 {
580        return v6_endpoint(v6, v6port);
581    }
582    // No address arrived, so the stream can only be on this machine.
583    format!("127.0.0.1:{v4port}")
584        .parse()
585        .map_err(|_| std::io::Error::other("cannot read the loopback address"))
586}
587
588/// Build an IPv6 endpoint, with the interface number when the text carries one.
589///
590/// A link-local address names a machine only together with the interface that
591/// reaches it. The text holds that number after a `%`, and the standard
592/// library reads neither the `%` nor the number, so both parts are taken
593/// apart here.
594pub(crate) fn v6_endpoint(text: &str, port: u16) -> std::io::Result<SocketAddr> {
595    let (host, scope) = match text.split_once('%') {
596        Some((h, s)) => (h, s.parse::<u32>().unwrap_or(0)),
597        None => (text, 0),
598    };
599    let addr: std::net::Ipv6Addr = host
600        .parse()
601        .map_err(|_| std::io::Error::other(format!("cannot read the address {text}")))?;
602    Ok(SocketAddr::V6(std::net::SocketAddrV6::new(
603        addr, port, 0, scope,
604    )))
605}
606
607/// Build the query that liblsl builds for a property.
608///
609/// `src/resolver_impl.cpp:66-73`.
610pub fn build_property_query(session_id: &str, prop: &str, value: &str) -> String {
611    format!("session_id='{session_id}' and {prop}='{value}'")
612}
613
614/// A connected inlet.
615///
616/// A background thread reads the socket and decodes samples into a bounded
617/// queue. The application pulls from that queue.
618///
619/// The split matters. A reader that decoded inside `pull` would leave the
620/// socket unread while the application worked, so a loss would land in the
621/// outlet's queue instead of this one. liblsl runs the same background thread
622/// (`src/data_receiver.h`).
623pub struct Inlet {
624    queue: Arc<SampleQueue>,
625    info: StreamInfo,
626    clock: Arc<ClockState>,
627    source: LiveSource,
628    post: PostProcessor,
629    /// Active post-processing flags so gap timestamps match `CLOCKSYNC`.
630    post_options: u32,
631    /// True once the caller explicitly set a device delay override.
632    device_delay_explicit: bool,
633    /// Reusable scratch buffer for sparse skip offsets during `pull_chunk`.
634    skip_scratch: Vec<(usize, u64)>,
635    /// Reusable scratch buffer for packed samples during typed chunk pulls.
636    packed_scratch: Vec<PackedSample>,
637    /// Reusable scratch buffer for SHM metadata during chunk pulls.
638    shm_meta_scratch: Vec<crate::shm::ShmSampleMeta>,
639    /// Fast-path handle to the active `shm/1` ring (no mutex on `pull`).
640    shm: Option<Arc<crate::shm::ShmReader>>,
641    /// Matches `conn.shm_gen`; refreshed only across a recovery transition.
642    shm_gen: u64,
643    /// Next expected `seq/1` sample number on the current SHM segment.
644    shm_expected_seq: Option<u64>,
645    /// Timestamp of the last sample pulled from the current SHM segment.
646    shm_last_ts: Option<f64>,
647    /// Counter used to sample latency probe once per 32 SHM samples.
648    shm_latency_ticks: u64,
649    /// Set once the reader thread stops.
650    reader_done: Arc<AtomicBool>,
651    conn: Arc<ConnState>,
652}
653
654/// What the reader thread and the application share about the connection.
655/// Maximum number of unread live metadata updates kept in the inlet inbox.
656const MAX_META_INBOX: usize = 4096;
657
658#[derive(Debug, Default)]
659struct MetadataInbox {
660    pending: VecDeque<labstream_proto::meta::MetadataUpdate>,
661    latest: std::collections::BTreeMap<String, labstream_proto::meta::MetadataUpdate>,
662}
663
664impl MetadataInbox {
665    fn push(&mut self, upd: labstream_proto::meta::MetadataUpdate) {
666        if self.pending.len() >= MAX_META_INBOX {
667            self.pending.pop_front();
668        }
669        self.latest.insert(upd.key.clone(), upd.clone());
670        self.pending.push_back(upd);
671    }
672}
673
674struct ConnState {
675    /// True when the inlet finds the stream again after its source restarts.
676    recover: bool,
677    /// How many times the connection has been rebuilt.
678    recoveries: AtomicU64,
679    /// False while the reader is between connections.
680    connected: AtomicBool,
681    /// The description of the stream that the reader is attached to. A
682    /// recovery replaces it, and the instance identifier changes.
683    info: Mutex<StreamInfo>,
684    /// Active `select/1` parameters agreed with the outlet, if any.
685    selection: Mutex<Option<features::SelectParam>>,
686    /// Active `shm/1` shared-memory ring, if negotiated.
687    shm: Mutex<Option<Arc<crate::shm::ShmReader>>>,
688    /// Bumped whenever `shm` is replaced or cleared on recovery.
689    shm_gen: AtomicU64,
690    /// True while samples arrive through shared memory (`shm/1`).
691    on_shm: AtomicBool,
692    /// True while wire compression (`comp/1`) is active on this connection.
693    compressed: AtomicBool,
694    /// True while negotiated transport encryption (`enc/1`) is active.
695    encrypted: AtomicBool,
696    /// True when the current connection negotiated `meta/1` live metadata.
697    meta_enabled: AtomicBool,
698    /// Live metadata updates received over `meta/1`.
699    metadata: Mutex<MetadataInbox>,
700    /// Compressed (or fallback) wire payload bytes received on this connection.
701    wire_bytes: Arc<AtomicU64>,
702    /// Equivalent uncompressed wire payload bytes received on this connection.
703    raw_bytes: Arc<AtomicU64>,
704    /// Next expected `seq/1` number observed on SHM (`u64::MAX` = none yet).
705    shm_next_expected: AtomicU64,
706    /// Cumulative SHM drops from earlier recovered SHM segments.
707    shm_dropped_prev: AtomicU64,
708    /// Finalized `GapKind::Dropped` intervals observed on SHM.
709    shm_drop_gaps: Mutex<VecDeque<Gap>>,
710    /// Timestamp bits of the last pulled SHM sample (for pending drop gaps).
711    shm_last_ts_bits: AtomicU64,
712    /// Cloned TCP handle so `Inlet::drop` wakes the SHM watcher immediately.
713    tcp_shutdown: Mutex<Option<TcpStream>>,
714    /// True when the current connection uses `seq/1`. `docs/extensions.md`.
715    numbered: AtomicBool,
716    /// The samples that never arrived, from the `seq/1` numbers. The thread
717    /// of `dgram/1` also writes it.
718    lost: Arc<AtomicU64>,
719    /// True while the samples of the connection arrive on UDP.
720    on_udp: AtomicBool,
721    /// True when the current connection uses `resume/1`. `docs/extensions.md`,
722    /// section `resume`.
723    resumed: AtomicBool,
724    /// The samples that came from the history of an outlet.
725    resent: AtomicU64,
726    /// Recorded `GapKind::Lost` intervals from `seq/1`, `dgram/1`, and `shm/1`.
727    gaps: Arc<Mutex<GapTracker>>,
728    /// Lock-free latency probe updated once per delivered batch.
729    latency: Arc<LatencyProbe>,
730}
731
732/// How long without data before the reader treats the source as gone.
733///
734/// liblsl checks on the same period and uses the same threshold
735/// (`src/api_config.cpp:302-303`).
736fn watchdog_threshold() -> Duration {
737    Duration::from_secs_f64(config::get().watchdog_time_threshold)
738}
739
740impl Inlet {
741    /// Open a feed to a resolved stream. SPEC.md 4 and 6.
742    ///
743    /// The call runs the whole handshake, including the two test pattern
744    /// samples that open every feed.
745    pub fn open(info: &StreamInfo, timeout: Duration) -> std::io::Result<Self> {
746        Inlet::open_with_buffer(info, timeout, 3600)
747    }
748
749    /// Open a feed and choose the size of the queue, in samples.
750    ///
751    /// The value also goes out in `Max-Buffer-Length`, which carries a count of
752    /// samples. A caller that thinks in seconds converts first. SPEC.md 8.6.
753    pub fn open_with_buffer(
754        info: &StreamInfo,
755        timeout: Duration,
756        buffer_samples: i32,
757    ) -> std::io::Result<Self> {
758        Inlet::open_full(info, timeout, buffer_samples, false, None)
759    }
760
761    /// Open a feed and choose whether the inlet finds the stream again after a
762    /// restart of its source. SPEC.md 10.1.
763    ///
764    /// liblsl enables recovery by default (`include/lsl_cpp.h:915`).
765    pub fn open_recovering(
766        info: &StreamInfo,
767        timeout: Duration,
768        buffer_samples: i32,
769    ) -> std::io::Result<Self> {
770        Inlet::open_full(info, timeout, buffer_samples, true, None)
771    }
772
773    /// Open a feed requesting channel and/or rate selection (`select/1`,
774    /// `docs/roadmap.md`, step 6).
775    ///
776    /// If the outlet supports `select/1`, the returned inlet delivers only the
777    /// selected channels at the selected rate, and [`Inlet::info`] and
778    /// [`Inlet::fullinfo`] reflect the narrowed stream. If the outlet does not
779    /// support `select/1` (for example a `liblsl` outlet), the inlet falls back
780    /// cleanly to the full stream and [`Inlet::selection`] returns `None`.
781    pub fn open_selected(
782        info: &StreamInfo,
783        timeout: Duration,
784        buffer_samples: i32,
785        recover: bool,
786        selection: features::SelectParam,
787    ) -> std::io::Result<Self> {
788        let sel = selection.is_active().then_some(selection);
789        Inlet::open_full(info, timeout, buffer_samples, recover, sel)
790    }
791
792    fn open_full(
793        info: &StreamInfo,
794        timeout: Duration,
795        buffer_samples: i32,
796        recover: bool,
797        requested_selection: Option<features::SelectParam>,
798    ) -> std::io::Result<Self> {
799        let hs = handshake(
800            info,
801            timeout,
802            buffer_samples,
803            None,
804            requested_selection.as_ref(),
805        )?;
806        let (stream, client, data_codec, active_selection, shm, enc_reader, buf) = (
807            hs.stream,
808            hs.client,
809            hs.codec,
810            hs.selection,
811            hs.shm,
812            hs.enc_reader,
813            hs.carry,
814        );
815        debug_assert_eq!(client.state(), State::Streaming);
816        let numbered = uses_seq(&client);
817        let meta_enabled = features::has(client.features(), features::META, 1);
818        let resume = features::resume_answer(client.features());
819        let encrypted_init = enc_reader.is_some();
820        let compressed = shm.is_none() && features::comp_answer(client.features());
821        let dgram = if shm.is_some() {
822            None
823        } else {
824            features::dgram_answer(client.features())
825        };
826
827        let effective_info = match &active_selection {
828            Some(sel) => info.apply_selection(sel),
829            None => info.clone(),
830        };
831
832        // The queue holds what the application has not pulled yet. Its size is
833        // the value that went out in `Max-Buffer-Length`, which is a count of
834        // samples. SPEC.md 8.6.
835        let queue = Arc::new(SampleQueue::new(buffer_samples.max(1) as usize));
836        let reader_done = Arc::new(AtomicBool::new(false));
837
838        // The offset thread runs for the life of the inlet. It answers on the
839        // service port, which is separate from the data port. SPEC.md 3.
840        let clock = Arc::new(ClockState::default());
841        let seed = Arc::new(Mutex::new(
842            std::process::id() as u64 ^ 0x9E37_79B9_7F4A_7C15,
843        ));
844        if let Some(target) = service_endpoint(info) {
845            crate::clock::start(target, Arc::clone(&clock), seed);
846        }
847
848        let tcp_shutdown = stream.try_clone().ok();
849        let on_shm_init = shm.is_some();
850        let conn = Arc::new(ConnState {
851            recover,
852            recoveries: AtomicU64::new(0),
853            connected: AtomicBool::new(true),
854            info: Mutex::new(info.clone()),
855            selection: Mutex::new(active_selection),
856            shm: Mutex::new(shm.clone()),
857            shm_gen: AtomicU64::new(0),
858            on_shm: AtomicBool::new(on_shm_init),
859            compressed: AtomicBool::new(compressed),
860            encrypted: AtomicBool::new(encrypted_init),
861            meta_enabled: AtomicBool::new(meta_enabled),
862            metadata: Mutex::new(MetadataInbox::default()),
863            wire_bytes: Arc::new(AtomicU64::new(0)),
864            raw_bytes: Arc::new(AtomicU64::new(0)),
865            shm_next_expected: AtomicU64::new(u64::MAX),
866            shm_dropped_prev: AtomicU64::new(0),
867            shm_drop_gaps: Mutex::new(VecDeque::new()),
868            shm_last_ts_bits: AtomicU64::new(f64::NAN.to_bits()),
869            tcp_shutdown: Mutex::new(tcp_shutdown),
870            numbered: AtomicBool::new(numbered),
871            lost: Arc::new(AtomicU64::new(0)),
872            on_udp: AtomicBool::new(false),
873            resumed: AtomicBool::new(resume.is_some()),
874            resent: AtomicU64::new(0),
875            gaps: Arc::new(Mutex::new(GapTracker::new())),
876            latency: Arc::new(LatencyProbe::default()),
877        });
878
879        // One thread owns the connection for its whole life: it reads, and when
880        // the source goes away it finds the stream again and starts over.
881        {
882            let q = Arc::clone(&queue);
883            let done = Arc::clone(&reader_done);
884            let clk = Arc::clone(&clock);
885            let state = Arc::clone(&conn);
886            let shm_bg = shm.clone();
887            std::thread::spawn(move || {
888                read_and_recover(
889                    stream,
890                    buf,
891                    data_codec,
892                    q,
893                    done,
894                    clk,
895                    state,
896                    buffer_samples,
897                    resume,
898                    dgram,
899                    shm_bg,
900                    enc_reader,
901                    compressed,
902                    requested_selection,
903                );
904            });
905        }
906
907        Ok(Inlet {
908            queue,
909            reader_done,
910            conn,
911            source: LiveSource::new(Arc::clone(&clock), effective_info.nominal_srate),
912            info: effective_info,
913            clock,
914            // No stage runs until a caller asks for one. liblsl uses the same
915            // default (`include/lsl/common.h:103`).
916            post: PostProcessor::new(),
917            post_options: 0,
918            device_delay_explicit: false,
919            skip_scratch: Vec::new(),
920            packed_scratch: Vec::new(),
921            shm_meta_scratch: Vec::new(),
922            shm,
923            shm_gen: 0,
924            shm_expected_seq: None,
925            shm_last_ts: None,
926            shm_latency_ticks: 0,
927        })
928    }
929
930    /// Choose the post-processing stages. SPEC.md 8.5.
931    ///
932    /// The default applies none, so a timestamp arrives as the sender wrote it.
933    /// When `flags::DEVICE_DELAY` is enabled and no explicit delay was set via
934    /// [`Inlet::set_device_delay`], the inlet reads
935    /// `<desc><synchronization><offset_mean>` from the stream description.
936    pub fn set_postprocessing(&mut self, options: u32) {
937        if (options & flags::DEVICE_DELAY) != 0 && !self.device_delay_explicit {
938            let delay = self.info.device_delay().or_else(|| {
939                self.fullinfo(Duration::from_secs(2))
940                    .ok()
941                    .and_then(|f| f.device_delay())
942            });
943            if let Some(d) = delay {
944                self.post.set_device_delay(d);
945            }
946        }
947        self.post_options = options;
948        self.post.set_options(options);
949    }
950
951    /// Set an explicit calibrated device delay (in seconds) subtracted when
952    /// `flags::DEVICE_DELAY` is enabled (`docs/roadmap.md`, step 15).
953    pub fn set_device_delay(&mut self, delay_s: f64) {
954        self.device_delay_explicit = true;
955        self.post.set_device_delay(delay_s);
956    }
957
958    /// The device delay (in seconds) currently configured on the post-processor.
959    pub fn device_delay(&self) -> f64 {
960        self.post.device_delay()
961    }
962
963    /// Apply every stage: clock sync, then jitter removal, then the clamp.
964    pub fn set_postprocessing_all(&mut self) {
965        let all = flags::CLOCKSYNC | flags::DEJITTER | flags::MONOTONIZE;
966        self.post_options = all;
967        self.post.set_options(all);
968    }
969
970    /// The measured offset between the two clocks, or `None` before the first
971    /// burst finishes.
972    ///
973    /// Add this value to a timestamp to move it onto the local clock. The
974    /// `CLOCKSYNC` stage does that on its own.
975    pub fn time_correction(&self) -> Option<f64> {
976        self.clock.offset()
977    }
978
979    /// Wait for a first offset measurement.
980    pub fn wait_for_time_correction(&self, timeout: Duration) -> Option<f64> {
981        self.clock.wait(timeout)
982    }
983
984    /// The round-trip time of the estimate that the offset came from.
985    pub fn time_uncertainty(&self) -> Option<f64> {
986        self.clock.uncertainty()
987    }
988
989    /// Estimated relative clock drift (`d(offset)/d(t_local)` in s/s) from the
990    /// opt-in drift clock (`docs/roadmap.md`, step 17), or `None` before the
991    /// first burst completes.
992    pub fn clock_drift(&self) -> Option<f64> {
993        self.clock.drift()
994    }
995
996    /// Smooth offset `local - remote` evaluated for `remote_ts` using the
997    /// opt-in drift clock (`docs/roadmap.md`, step 17).
998    pub fn smooth_time_correction(&self, remote_ts: f64) -> Option<f64> {
999        self.clock.smooth_offset_at(remote_ts)
1000    }
1001
1002    /// The description of the connected stream.
1003    ///
1004    /// This is the short description that discovery returned. It carries an
1005    /// empty description tree. Call [`Inlet::fullinfo`] for the tree.
1006    pub fn info(&self) -> &StreamInfo {
1007        &self.info
1008    }
1009
1010    /// Read the whole description, with the description tree.
1011    ///
1012    /// The short description that a discovery answer carries has no tree
1013    /// (`src/stream_info_impl.cpp:160`). The tree travels on the data port.
1014    /// This opens its own connection, the way `info_receiver` does
1015    /// (`src/info_receiver.cpp:60`), and leaves the feed connection alone.
1016    ///
1017    /// When `select/1` is active on this connection, the returned description
1018    /// carries the selected channel count, selected rate, and selected channel
1019    /// metadata under `<desc><channels>`.
1020    pub fn fullinfo(&self, timeout: Duration) -> std::io::Result<StreamInfo> {
1021        let known = self.conn.info.lock().unwrap().clone();
1022        let full = read_fullinfo(&known, timeout)?;
1023        Ok(match self.conn.selection.lock().unwrap().as_ref() {
1024            Some(sel) => full.apply_selection(sel),
1025            None => full,
1026        })
1027    }
1028
1029    /// The active `select/1` selection negotiated with the outlet, or `None`
1030    /// when the full stream is delivered.
1031    pub fn selection(&self) -> Option<features::SelectParam> {
1032        self.conn.selection.lock().unwrap().clone()
1033    }
1034
1035    /// Read one sample.
1036    ///
1037    /// Returns `Ok(None)` when the timeout passes with no whole sample.
1038    ///
1039    /// The timestamp passes through the post-processing stages that
1040    /// [`Inlet::set_postprocessing`] selected. With none selected the value is
1041    /// the one that the sender wrote.
1042    ///
1043    /// With `CLOCKSYNC` selected, the first call waits for the first offset
1044    /// measurement, for up to 5 s. The timeout of the call does not limit that
1045    /// wait. liblsl waits the same time (`src/stream_inlet_impl.h:44`).
1046    pub fn pull(&mut self, timeout: Duration) -> std::io::Result<Option<Sample>> {
1047        Ok(self.pull_packed(timeout)?.map(|s| s.to_sample()))
1048    }
1049
1050    /// Refresh the local SHM handle if a recovery replaced or cleared it.
1051    #[inline]
1052    fn sync_shm(&mut self) {
1053        let gen = self.conn.shm_gen.load(Ordering::Acquire);
1054        if gen == self.shm_gen {
1055            return;
1056        }
1057        if let Some(old) = self.shm.take() {
1058            self.conn
1059                .shm_dropped_prev
1060                .fetch_add(old.total_dropped(), Ordering::Release);
1061        }
1062        self.shm = self.conn.shm.lock().unwrap().clone();
1063        self.shm_gen = gen;
1064        self.shm_expected_seq = None;
1065        self.shm_last_ts = None;
1066    }
1067
1068    /// Update sequence loss, drop gaps, dejitter skips, latency probe, and
1069    /// post-processing for one sample popped from SHM.
1070    #[inline]
1071    fn apply_shm_meta(&mut self, meta: crate::shm::ShmSampleMeta) -> f64 {
1072        if meta.lapped_drops > 0 {
1073            let start = self.shm_last_ts.unwrap_or(meta.timestamp);
1074            if start.is_finite() && meta.timestamp.is_finite() {
1075                let mut q = self.conn.shm_drop_gaps.lock().unwrap();
1076                if q.len() >= MAX_GAPS {
1077                    q.pop_front();
1078                }
1079                q.push_back(Gap {
1080                    start,
1081                    end: meta.timestamp,
1082                    count: meta.lapped_drops,
1083                    kind: GapKind::Dropped,
1084                });
1085            }
1086        }
1087        let mut lost_delta = 0u64;
1088        if let Some(exp) = self.shm_expected_seq {
1089            let total_gap = meta.sample_seq.saturating_sub(exp);
1090            lost_delta = total_gap.saturating_sub(meta.lapped_drops);
1091            if lost_delta > 0 {
1092                self.conn.lost.fetch_add(lost_delta, Ordering::Relaxed);
1093                let mut g = self.conn.gaps.lock().unwrap();
1094                if let Some(prev) = self.shm_last_ts {
1095                    g.on_sample(prev);
1096                }
1097                g.record_lost(lost_delta);
1098                g.on_sample(meta.timestamp);
1099            }
1100        }
1101        let total_skip = lost_delta.saturating_add(meta.lapped_drops);
1102        if total_skip > 0 && self.conn.numbered.load(Ordering::Relaxed) {
1103            self.post
1104                .skip_samples(u32::try_from(total_skip).unwrap_or(u32::MAX));
1105        }
1106        let next_exp = meta.sample_seq.wrapping_add(1);
1107        self.shm_expected_seq = Some(next_exp);
1108        self.conn
1109            .shm_next_expected
1110            .store(next_exp, Ordering::Relaxed);
1111        self.shm_last_ts = Some(meta.timestamp);
1112        self.conn
1113            .shm_last_ts_bits
1114            .store(meta.timestamp.to_bits(), Ordering::Relaxed);
1115        if self.shm_latency_ticks & 31 == 0 {
1116            self.conn.latency.record(meta.timestamp);
1117        }
1118        self.shm_latency_ticks = self.shm_latency_ticks.wrapping_add(1);
1119        self.post.process(meta.timestamp, &mut self.source)
1120    }
1121
1122    /// Read one numeric sample directly into `dst` (native-endian bytes),
1123    /// returning its timestamp.
1124    ///
1125    /// On a `shm/1` connection, copies directly from shared memory into `dst`
1126    /// with zero heap allocation and zero mutex locks.
1127    pub fn pull_numeric_into(
1128        &mut self,
1129        format: labstream_wire::Format,
1130        dst: &mut [u8],
1131        timeout: Duration,
1132    ) -> std::io::Result<Option<f64>> {
1133        // Ultra-fast path: already-ready sample in SHM avoids `Instant::now()`
1134        // and `Arc::clone()` completely.
1135        self.sync_shm();
1136        if let Some(ref reader) = self.shm {
1137            if reader.format() == format {
1138                if let Some(meta) = reader.try_pop_into(dst) {
1139                    let ts = self.apply_shm_meta(meta);
1140                    return Ok(Some(ts));
1141                }
1142            }
1143        }
1144        let deadline = if timeout.is_zero() {
1145            None
1146        } else {
1147            Some(Instant::now() + timeout)
1148        };
1149        loop {
1150            self.sync_shm();
1151            if let Some(reader) = self.shm.as_ref().cloned() {
1152                if reader.format() == format {
1153                    let wait = match deadline {
1154                        Some(d) => d.saturating_duration_since(Instant::now()),
1155                        None => Duration::ZERO,
1156                    };
1157                    if let Some(meta) = reader.pop_into(dst, wait) {
1158                        let ts = self.apply_shm_meta(meta);
1159                        return Ok(Some(ts));
1160                    }
1161                    if reader.is_closed()
1162                        && self.conn.recover
1163                        && !self.reader_done.load(Ordering::Acquire)
1164                        && deadline.is_some_and(|d| Instant::now() < d)
1165                    {
1166                        std::thread::sleep(Duration::from_millis(5));
1167                        continue;
1168                    }
1169                    return Ok(None);
1170                }
1171            }
1172            let wait = match deadline {
1173                Some(d) => d.saturating_duration_since(Instant::now()),
1174                None => Duration::ZERO,
1175            };
1176            return match self.pull_packed_queue(wait)? {
1177                Some(s) => {
1178                    if let Some(bytes) = s.as_numeric_bytes(format) {
1179                        let n = bytes.len().min(dst.len());
1180                        dst[..n].copy_from_slice(&bytes[..n]);
1181                    }
1182                    Ok(Some(s.timestamp))
1183                }
1184                None => Ok(None),
1185            };
1186        }
1187    }
1188
1189    /// Read one [`PackedSample`] without allocating a `Vec<Value>`.
1190    pub fn pull_packed(&mut self, timeout: Duration) -> std::io::Result<Option<PackedSample>> {
1191        let deadline = if timeout.is_zero() {
1192            None
1193        } else {
1194            Some(Instant::now() + timeout)
1195        };
1196        loop {
1197            self.sync_shm();
1198            if let Some(reader) = self.shm.as_ref().cloned() {
1199                let wait = match deadline {
1200                    Some(d) => d.saturating_duration_since(Instant::now()),
1201                    None => Duration::ZERO,
1202                };
1203                if let Some((mut sample, meta)) = reader.pop_packed(wait) {
1204                    sample.timestamp = self.apply_shm_meta(meta);
1205                    return Ok(Some(sample));
1206                }
1207                if reader.is_closed()
1208                    && self.conn.recover
1209                    && !self.reader_done.load(Ordering::Acquire)
1210                    && deadline.is_some_and(|d| Instant::now() < d)
1211                {
1212                    std::thread::sleep(Duration::from_millis(5));
1213                    continue;
1214                }
1215                return Ok(None);
1216            }
1217            let wait = match deadline {
1218                Some(d) => d.saturating_duration_since(Instant::now()),
1219                None => Duration::ZERO,
1220            };
1221            return self.pull_packed_queue(wait);
1222        }
1223    }
1224
1225    fn pull_packed_queue(&mut self, timeout: Duration) -> std::io::Result<Option<PackedSample>> {
1226        match self.queue.pop_packed_with_skip(timeout) {
1227            Some((mut s, skipped)) => {
1228                // Step 2: advance the dejitterer across lost/dropped samples
1229                // only when `seq/1` is active on this connection.
1230                if skipped > 0 && self.conn.numbered.load(Ordering::Relaxed) {
1231                    self.post
1232                        .skip_samples(u32::try_from(skipped).unwrap_or(u32::MAX));
1233                }
1234                // Every stage runs here, in the fixed order. SPEC.md 8.5.
1235                s.timestamp = self.post.process(s.timestamp, &mut self.source);
1236                Ok(Some(s))
1237            }
1238            None => Ok(None),
1239        }
1240    }
1241
1242    /// Read every sample that waits, up to `max`, with one lock.
1243    ///
1244    /// The samples go to the end of `out`. The call gives how many it added.
1245    /// Every timestamp passes through the stages that
1246    /// [`Inlet::set_postprocessing`] selected, in the order of one
1247    /// [`Inlet::pull`] for each sample.
1248    ///
1249    /// The timeout applies to the first sample only. The call never waits for
1250    /// `max` samples, because a program that shows live signals must show what
1251    /// arrived.
1252    ///
1253    /// With `CLOCKSYNC` selected, the first call can wait up to 5 s for the
1254    /// first offset measurement, as [`Inlet::pull`] does.
1255    ///
1256    /// This is the call for a fast stream. [`Inlet::pull`] takes the queue lock
1257    /// and reads the clock for each sample. A stream of 8 channels at 1000 Hz
1258    /// therefore costs 1000 locks each second with `pull`, and one lock for each
1259    /// block here.
1260    pub fn pull_chunk(
1261        &mut self,
1262        out: &mut Vec<Sample>,
1263        max: usize,
1264        timeout: Duration,
1265    ) -> std::io::Result<usize> {
1266        let mut scratch = std::mem::take(&mut self.packed_scratch);
1267        scratch.clear();
1268        let got = self.pull_chunk_packed(&mut scratch, max, timeout)?;
1269        out.extend(scratch.iter().map(PackedSample::to_sample));
1270        self.packed_scratch = scratch;
1271        Ok(got)
1272    }
1273
1274    /// Read every waiting [`PackedSample`], up to `max`, with one lock and
1275    /// without allocating a `Vec<Value>`.
1276    pub fn pull_chunk_packed(
1277        &mut self,
1278        out: &mut Vec<PackedSample>,
1279        max: usize,
1280        timeout: Duration,
1281    ) -> std::io::Result<usize> {
1282        let deadline = if timeout.is_zero() {
1283            None
1284        } else {
1285            Some(Instant::now() + timeout)
1286        };
1287        loop {
1288            self.sync_shm();
1289            if let Some(reader) = self.shm.as_ref().cloned() {
1290                let first = out.len();
1291                let mut metas = std::mem::take(&mut self.shm_meta_scratch);
1292                metas.clear();
1293                let wait = match deadline {
1294                    Some(d) => d.saturating_duration_since(Instant::now()),
1295                    None => Duration::ZERO,
1296                };
1297                let got = reader.pop_many_packed(out, &mut metas, max, wait);
1298                if got > 0 {
1299                    for (s, meta) in out[first..].iter_mut().zip(metas.iter().copied()) {
1300                        s.timestamp = self.apply_shm_meta(meta);
1301                    }
1302                    self.shm_meta_scratch = metas;
1303                    return Ok(got);
1304                }
1305                self.shm_meta_scratch = metas;
1306                if reader.is_closed()
1307                    && self.conn.recover
1308                    && !self.reader_done.load(Ordering::Acquire)
1309                    && deadline.is_some_and(|d| Instant::now() < d)
1310                {
1311                    std::thread::sleep(Duration::from_millis(5));
1312                    continue;
1313                }
1314                return Ok(0);
1315            }
1316            let first = out.len();
1317            self.skip_scratch.clear();
1318            let numbered = self.conn.numbered.load(Ordering::Relaxed);
1319            let wait = match deadline {
1320                Some(d) => d.saturating_duration_since(Instant::now()),
1321                None => Duration::ZERO,
1322            };
1323            let got = self.queue.pop_many_packed_with_skips(
1324                out,
1325                numbered.then_some(&mut self.skip_scratch),
1326                max,
1327                wait,
1328            );
1329            // Every stage runs here, in the fixed order, one sample after another.
1330            // SPEC.md 8.5. The state of the filter carries across the block, so a
1331            // block gives the timestamps that the same samples get one at a time.
1332            if self.skip_scratch.is_empty() {
1333                for s in &mut out[first..] {
1334                    s.timestamp = self.post.process(s.timestamp, &mut self.source);
1335                }
1336            } else {
1337                let mut next_skip = 0usize;
1338                for (idx, s) in out[first..].iter_mut().enumerate() {
1339                    while next_skip < self.skip_scratch.len()
1340                        && self.skip_scratch[next_skip].0 == idx
1341                    {
1342                        let n = self.skip_scratch[next_skip].1;
1343                        self.post.skip_samples(u32::try_from(n).unwrap_or(u32::MAX));
1344                        next_skip += 1;
1345                    }
1346                    s.timestamp = self.post.process(s.timestamp, &mut self.source);
1347                }
1348            }
1349            return Ok(got);
1350        }
1351    }
1352
1353    /// Read up to `max_samples` into flat `f32` and timestamp buffers with one lock.
1354    pub fn pull_chunk_f32(
1355        &mut self,
1356        data: &mut Vec<f32>,
1357        timestamps: &mut Vec<f64>,
1358        max_samples: usize,
1359        timeout: Duration,
1360    ) -> std::io::Result<usize> {
1361        self.pull_chunk_flat(
1362            data,
1363            timestamps,
1364            max_samples,
1365            timeout,
1366            PackedSample::push_into_f32,
1367        )
1368    }
1369
1370    /// Read up to `max_samples` into flat `f64` and timestamp buffers with one lock.
1371    pub fn pull_chunk_f64(
1372        &mut self,
1373        data: &mut Vec<f64>,
1374        timestamps: &mut Vec<f64>,
1375        max_samples: usize,
1376        timeout: Duration,
1377    ) -> std::io::Result<usize> {
1378        self.pull_chunk_flat(
1379            data,
1380            timestamps,
1381            max_samples,
1382            timeout,
1383            PackedSample::push_into_f64,
1384        )
1385    }
1386
1387    /// Read up to `max_samples` into flat `i32` and timestamp buffers with one lock.
1388    pub fn pull_chunk_i32(
1389        &mut self,
1390        data: &mut Vec<i32>,
1391        timestamps: &mut Vec<f64>,
1392        max_samples: usize,
1393        timeout: Duration,
1394    ) -> std::io::Result<usize> {
1395        self.pull_chunk_flat(
1396            data,
1397            timestamps,
1398            max_samples,
1399            timeout,
1400            PackedSample::push_into_i32,
1401        )
1402    }
1403
1404    /// Read up to `max_samples` into flat `i16` and timestamp buffers with one lock.
1405    pub fn pull_chunk_i16(
1406        &mut self,
1407        data: &mut Vec<i16>,
1408        timestamps: &mut Vec<f64>,
1409        max_samples: usize,
1410        timeout: Duration,
1411    ) -> std::io::Result<usize> {
1412        self.pull_chunk_flat(
1413            data,
1414            timestamps,
1415            max_samples,
1416            timeout,
1417            PackedSample::push_into_i16,
1418        )
1419    }
1420
1421    /// Read up to `max_samples` into flat `i8` and timestamp buffers with one lock.
1422    pub fn pull_chunk_i8(
1423        &mut self,
1424        data: &mut Vec<i8>,
1425        timestamps: &mut Vec<f64>,
1426        max_samples: usize,
1427        timeout: Duration,
1428    ) -> std::io::Result<usize> {
1429        self.pull_chunk_flat(
1430            data,
1431            timestamps,
1432            max_samples,
1433            timeout,
1434            PackedSample::push_into_i8,
1435        )
1436    }
1437
1438    /// Read up to `max_samples` into flat `i64` and timestamp buffers with one lock.
1439    pub fn pull_chunk_i64(
1440        &mut self,
1441        data: &mut Vec<i64>,
1442        timestamps: &mut Vec<f64>,
1443        max_samples: usize,
1444        timeout: Duration,
1445    ) -> std::io::Result<usize> {
1446        self.pull_chunk_flat(
1447            data,
1448            timestamps,
1449            max_samples,
1450            timeout,
1451            PackedSample::push_into_i64,
1452        )
1453    }
1454
1455    fn pull_chunk_flat<T>(
1456        &mut self,
1457        data: &mut Vec<T>,
1458        timestamps: &mut Vec<f64>,
1459        max_samples: usize,
1460        timeout: Duration,
1461        unpack: fn(&PackedSample, &mut Vec<T>),
1462    ) -> std::io::Result<usize> {
1463        let mut scratch = std::mem::take(&mut self.packed_scratch);
1464        scratch.clear();
1465        let got = self.pull_chunk_packed(&mut scratch, max_samples, timeout)?;
1466        let chans = self.info.channel_count as usize;
1467        data.reserve(got * chans);
1468        timestamps.reserve(got);
1469        for s in &scratch {
1470            unpack(s, data);
1471            timestamps.push(s.timestamp);
1472        }
1473        self.packed_scratch = scratch;
1474        Ok(got)
1475    }
1476
1477    /// How many samples wait for the application.
1478    pub fn samples_available(&self) -> usize {
1479        let shm_len = self
1480            .conn
1481            .shm
1482            .lock()
1483            .unwrap()
1484            .as_ref()
1485            .map_or(0, |r| r.len());
1486        self.queue.len() + shm_len
1487    }
1488
1489    /// How many samples the queue has dropped.
1490    ///
1491    /// Nothing on the wire carries this number, so a peer cannot learn it.
1492    /// SPEC.md 8.7. This exists for a local report only.
1493    pub fn samples_dropped(&self) -> u64 {
1494        let shm_cur = self
1495            .conn
1496            .shm
1497            .lock()
1498            .unwrap()
1499            .as_ref()
1500            .map_or(0, |r| r.total_dropped());
1501        self.queue.dropped() + self.conn.shm_dropped_prev.load(Ordering::Acquire) + shm_cur
1502    }
1503
1504    /// How many samples never reached this inlet, since it opened.
1505    ///
1506    /// The count comes from the `seq/1` numbers (`docs/extensions.md`). It
1507    /// shows a sample that the outlet dropped from a full queue, and the
1508    /// samples between a lost connection and the next one. The value is
1509    /// `None` when the current connection does not use `seq/1`, for example
1510    /// with a liblsl outlet. `None` means unknown, not zero.
1511    ///
1512    /// The inlet queue drops after this count, so a full total adds
1513    /// [`Inlet::samples_dropped`].
1514    pub fn samples_lost(&self) -> Option<u64> {
1515        if self.conn.numbered.load(Ordering::SeqCst) {
1516            Some(self.conn.lost.load(Ordering::SeqCst))
1517        } else {
1518            None
1519        }
1520    }
1521
1522    /// How many samples came from the history of the outlet, since the
1523    /// inlet opened.
1524    ///
1525    /// After a lost connection, an outlet with the `resume/1` feature sends
1526    /// the samples of the dropout again (`docs/extensions.md`, section
1527    /// `resume`). These samples arrive late, with their original
1528    /// timestamps. [`Inlet::samples_lost`] does not count them.
1529    ///
1530    /// The value is `None` when the current connection does not use
1531    /// `resume/1`. `None` means unknown, not zero.
1532    pub fn samples_resent(&self) -> Option<u64> {
1533        if self.conn.resumed.load(Ordering::SeqCst) {
1534            Some(self.conn.resent.load(Ordering::SeqCst))
1535        } else {
1536            None
1537        }
1538    }
1539
1540    /// True while the samples of the connection arrive on UDP, with the
1541    /// `dgram/1` feature. `docs/extensions.md`, section `dgram`.
1542    pub fn on_udp(&self) -> bool {
1543        self.conn.on_udp.load(Ordering::SeqCst)
1544    }
1545
1546    /// True while the samples of the connection arrive through shared memory,
1547    /// with the `shm/1` feature (`docs/extensions.md`, section `shm`).
1548    pub fn on_shm(&self) -> bool {
1549        self.conn.on_shm.load(Ordering::SeqCst)
1550    }
1551
1552    /// True while wire compression (`comp/1`) is active on this connection.
1553    pub fn is_compressed(&self) -> bool {
1554        self.conn.compressed.load(Ordering::SeqCst)
1555    }
1556
1557    /// True while negotiated transport encryption (`enc/1`) is active on this
1558    /// connection (`docs/roadmap.md`, step 14).
1559    pub fn is_encrypted(&self) -> bool {
1560        self.conn.encrypted.load(Ordering::SeqCst)
1561    }
1562
1563    /// True when the current connection negotiated `meta/1` live metadata
1564    /// (`docs/roadmap.md`, step 16).
1565    pub fn has_live_metadata(&self) -> bool {
1566        self.conn.meta_enabled.load(Ordering::SeqCst)
1567    }
1568
1569    /// Number of unread live metadata updates currently queued on this inlet.
1570    pub fn pending_metadata_count(&self) -> usize {
1571        self.conn.metadata.lock().unwrap().pending.len()
1572    }
1573
1574    /// Adjust a raw outlet metadata timestamp with the inlet's active clock
1575    /// synchronization and device-delay settings (opt-in flags match sample
1576    /// timestamps).
1577    fn adjust_metadata_timestamp(&self, raw: f64) -> f64 {
1578        let mut ts = raw;
1579        let flags = self.post.options();
1580        if flags & labstream_time::flags::DRIFT != 0 {
1581            if let Some(off) = self.clock.smooth_offset_at(ts) {
1582                ts += off;
1583            } else if let Some(off) = self.clock.offset() {
1584                ts += off;
1585            }
1586        } else if flags & labstream_time::flags::CLOCKSYNC != 0 {
1587            if let Some(off) = self.clock.offset() {
1588                ts += off;
1589            }
1590        }
1591        if flags & labstream_time::flags::DEVICE_DELAY != 0 {
1592            let d = self.post.device_delay();
1593            if d.is_finite() {
1594                ts -= d;
1595            }
1596        }
1597        ts
1598    }
1599
1600    /// Drain all pending live metadata updates in order.
1601    pub fn pull_metadata(&self) -> Vec<labstream_proto::meta::MetadataUpdate> {
1602        let mut drained: Vec<labstream_proto::meta::MetadataUpdate> = {
1603            let mut inbox = self.conn.metadata.lock().unwrap();
1604            inbox.pending.drain(..).collect()
1605        };
1606        for u in &mut drained {
1607            u.timestamp = self.adjust_metadata_timestamp(u.timestamp);
1608        }
1609        drained
1610    }
1611
1612    /// Pop the oldest pending live metadata update, if any.
1613    pub fn pull_metadata_one(&self) -> Option<labstream_proto::meta::MetadataUpdate> {
1614        let mut u = self.conn.metadata.lock().unwrap().pending.pop_front()?;
1615        u.timestamp = self.adjust_metadata_timestamp(u.timestamp);
1616        Some(u)
1617    }
1618
1619    /// Snapshot the latest live metadata value received for each key.
1620    pub fn metadata(
1621        &self,
1622    ) -> std::collections::BTreeMap<String, labstream_proto::meta::MetadataUpdate> {
1623        let mut map = self.conn.metadata.lock().unwrap().latest.clone();
1624        for u in map.values_mut() {
1625            u.timestamp = self.adjust_metadata_timestamp(u.timestamp);
1626        }
1627        map
1628    }
1629
1630    /// Ratio `wire_bytes / raw_bytes` observed on this connection when
1631    /// `comp/1` is active, or `None` when uncompressed or before data arrives.
1632    pub fn compression_ratio(&self) -> Option<f64> {
1633        if !self.is_compressed() {
1634            return None;
1635        }
1636        let raw = self.conn.raw_bytes.load(Ordering::Relaxed);
1637        if raw == 0 {
1638            return None;
1639        }
1640        let wire = self.conn.wire_bytes.load(Ordering::Relaxed);
1641        Some(wire as f64 / raw as f64)
1642    }
1643
1644    /// The size of the queue, in samples.
1645    pub fn buffer_capacity(&self) -> usize {
1646        self.queue.capacity()
1647    }
1648
1649    /// True once the connection ended and every sample has been pulled.
1650    pub fn is_finished(&self) -> bool {
1651        self.reader_done.load(Ordering::SeqCst) && self.samples_available() == 0
1652    }
1653
1654    /// Snapshot the health of this inlet in one call. `docs/health.md`.
1655    pub fn health(&self) -> InletHealth {
1656        let pending_shm_drop = {
1657            let guard = self.conn.shm.lock().unwrap();
1658            if let Some(r) = guard.as_ref() {
1659                if self.conn.latency.measure(self.clock.offset()).is_none() {
1660                    if let Some(ts) = r.peek_latest_timestamp() {
1661                        self.conn.latency.record(ts);
1662                    }
1663                }
1664                usize::from(r.pending_drops() > 0)
1665            } else {
1666                0
1667            }
1668        };
1669        let gap_count = self.conn.gaps.lock().unwrap().len()
1670            + self.queue.drop_gap_count()
1671            + self.conn.shm_drop_gaps.lock().unwrap().len()
1672            + pending_shm_drop;
1673        InletHealth {
1674            latency: self.conn.latency.measure(self.clock.offset()),
1675            lost: self.samples_lost(),
1676            dropped: self.samples_dropped(),
1677            resent: self.samples_resent(),
1678            clock_uncertainty: self.time_uncertainty(),
1679            clock_drift: self.clock_drift(),
1680            recoveries: self.recoveries(),
1681            connected: self.is_connected(),
1682            on_udp: self.on_udp(),
1683            on_shm: self.on_shm(),
1684            compressed: self.is_compressed(),
1685            encrypted: self.is_encrypted(),
1686            compression_ratio: self.compression_ratio(),
1687            buffered: self.samples_available(),
1688            buffer_capacity: self.buffer_capacity(),
1689            gap_count,
1690        }
1691    }
1692
1693    fn gap_clock_shift(&self) -> f64 {
1694        if (self.post_options & flags::CLOCKSYNC) != 0 {
1695            self.clock.offset().unwrap_or(0.0)
1696        } else {
1697            0.0
1698        }
1699    }
1700
1701    /// Snapshot every gap recorded on this inlet, sorted by start timestamp.
1702    ///
1703    /// Includes both network/outlet losses (`GapKind::Lost`) and local buffer
1704    /// overflows (`GapKind::Dropped`).
1705    pub fn gaps(&self) -> Vec<Gap> {
1706        let shift = self.gap_clock_shift();
1707        let mut out = self.conn.gaps.lock().unwrap().snapshot(shift);
1708        out.extend(self.queue.drop_gaps(shift));
1709        for g in self.conn.shm_drop_gaps.lock().unwrap().iter() {
1710            out.push(Gap {
1711                start: g.start + shift,
1712                end: g.end + shift,
1713                count: g.count,
1714                kind: g.kind,
1715            });
1716        }
1717        if let Some(r) = self.conn.shm.lock().unwrap().as_ref() {
1718            let pending = r.pending_drops();
1719            if pending > 0 {
1720                if let Some(end_ts) = r.peek_latest_timestamp() {
1721                    let last = f64::from_bits(self.conn.shm_last_ts_bits.load(Ordering::Relaxed));
1722                    let start = if last.is_finite() { last } else { end_ts };
1723                    out.push(Gap {
1724                        start: start + shift,
1725                        end: end_ts + shift,
1726                        count: pending,
1727                        kind: GapKind::Dropped,
1728                    });
1729                }
1730            }
1731        }
1732        out.sort_by(|a, b| a.start.total_cmp(&b.start));
1733        out
1734    }
1735
1736    /// Drain and return every finalized gap recorded since the last call,
1737    /// sorted by start timestamp.
1738    pub fn take_gaps(&self) -> Vec<Gap> {
1739        let shift = self.gap_clock_shift();
1740        let mut out = self.conn.gaps.lock().unwrap().take(shift);
1741        out.extend(self.queue.take_drop_gaps(shift));
1742        for g in self.conn.shm_drop_gaps.lock().unwrap().drain(..) {
1743            out.push(Gap {
1744                start: g.start + shift,
1745                end: g.end + shift,
1746                count: g.count,
1747                kind: g.kind,
1748            });
1749        }
1750        out.sort_by(|a, b| a.start.total_cmp(&b.start));
1751        out
1752    }
1753}
1754
1755impl Drop for Inlet {
1756    fn drop(&mut self) {
1757        self.clock.stop();
1758        self.queue.close();
1759        if let Some(r) = self.conn.shm.lock().unwrap().as_ref() {
1760            r.close_local();
1761        }
1762        if let Some(s) = self.conn.tcp_shutdown.lock().unwrap().take() {
1763            let _ = s.shutdown(Shutdown::Both);
1764        }
1765    }
1766}
1767
1768/// Read samples, and rebuild the connection when the source goes away.
1769///
1770/// SPEC.md 10.1 records what liblsl does: the inlet finds the stream again by
1771/// name, type, source identifier, channel count, and channel format. The
1772/// instance identifier changes across a restart, and the clock state clears
1773/// because the old fit describes a process that no longer exists.
1774#[allow(clippy::too_many_arguments)]
1775fn read_and_recover(
1776    mut sock: TcpStream,
1777    mut carry: Vec<u8>,
1778    mut codec: labstream_wire::Codec,
1779    queue: Arc<SampleQueue>,
1780    done: Arc<AtomicBool>,
1781    clock: Arc<ClockState>,
1782    conn: Arc<ConnState>,
1783    buffer_samples: i32,
1784    resume: Option<features::ResumeParam>,
1785    dgram: Option<features::DgramParam>,
1786    mut shm: Option<Arc<crate::shm::ShmReader>>,
1787    mut enc_reader: Option<crate::enc::EncReader>,
1788    initial_compressed: bool,
1789    requested_selection: Option<features::SelectParam>,
1790) {
1791    let mut tmp = vec![0u8; 65536];
1792    let mut batch: Vec<PackedSample> = Vec::new();
1793    let mut batch_skips: Vec<(usize, u64)> = Vec::new();
1794    let _ = sock.set_read_timeout(Some(Duration::from_millis(200)));
1795    let mut last_data = Instant::now();
1796    let mut tcp_comp = initial_compressed
1797        .then(|| labstream_proto::comp::CompState::new(codec.format, codec.channels));
1798
1799    // Most samples of a chunk carry no timestamp. The reader rebuilds each one
1800    // from the position in the stream, and the accumulator runs for the life of
1801    // the connection. SPEC.md 8.1.
1802    let srate = {
1803        let base = conn.info.lock().unwrap().nominal_srate;
1804        match conn.selection.lock().unwrap().as_ref() {
1805            Some(sel) => sel.output_srate(base),
1806            None => base,
1807        }
1808    };
1809    let mut deducer = labstream_wire::TimestampDeducer::new(srate);
1810
1811    // The `seq/1` count. It lives as long as the inlet, so the first record
1812    // after a reconnect to the same outlet shows the gap.
1813    let mut counter = labstream_proto::seq::Counter::new();
1814
1815    // The `resume/1` state. The epoch identifies the run of the outlet, and
1816    // `until` is the first live number of the current connection. A sample
1817    // below it came from the history. `docs/extensions.md`, section `resume`.
1818    let mut epoch = resume.map(|p| p.epoch);
1819    let mut until = resume.map(|p| p.number);
1820    let mut resent: u64 = 0;
1821
1822    // The `dgram/1` part of the current connection, if it agreed to it.
1823    // `docs/extensions.md`, section `dgram`.
1824    let start_dgram = |param: Option<features::DgramParam>,
1825                       sock: &TcpStream,
1826                       codec: labstream_wire::Codec,
1827                       until: Option<u64>|
1828     -> Option<crate::dgram_in::DgramIn> {
1829        crate::dgram_in::DgramIn::start(
1830            param?,
1831            sock,
1832            codec,
1833            Arc::clone(&queue),
1834            Arc::clone(&conn.lost),
1835            Arc::clone(&conn.gaps),
1836            Arc::clone(&conn.latency),
1837            Arc::clone(&conn.wire_bytes),
1838            Arc::clone(&conn.raw_bytes),
1839            until,
1840        )
1841    };
1842    let mut dg = start_dgram(dgram, &sock, codec, until);
1843
1844    loop {
1845        if queue.is_closed() {
1846            break;
1847        }
1848
1849        // While `shm/1` is active, samples travel through shared memory and
1850        // the TCP socket carries end-of-stream, recovery triggers, and `meta/1`
1851        // live metadata records.
1852        let ended = if let Some(ref reader) = shm {
1853            match sock.read(&mut tmp) {
1854                Ok(0) => Some(Ending::Closed),
1855                Ok(n) => {
1856                    if conn.meta_enabled.load(Ordering::SeqCst) {
1857                        carry.extend_from_slice(&tmp[..n]);
1858                        let mut pos = 0usize;
1859                        loop {
1860                            match labstream_proto::meta::peek(&carry[pos..]) {
1861                                labstream_proto::meta::Next::Record(upd, used) => {
1862                                    conn.metadata.lock().unwrap().push(upd);
1863                                    pos += used;
1864                                }
1865                                labstream_proto::meta::Next::Incomplete => break,
1866                                labstream_proto::meta::Next::Other
1867                                | labstream_proto::meta::Next::Invalid => {
1868                                    pos = carry.len();
1869                                    break;
1870                                }
1871                            }
1872                        }
1873                        if pos > 0 {
1874                            carry.drain(..pos);
1875                        }
1876                    }
1877                    None
1878                }
1879                Err(ref e) if read_timed_out(e) => {
1880                    if reader.is_closed() {
1881                        Some(Ending::Closed)
1882                    } else {
1883                        None
1884                    }
1885                }
1886                Err(_) => Some(Ending::Closed),
1887            }
1888        } else {
1889            // Decode everything already buffered before reading more. The whole
1890            // read goes into the queue with one lock.
1891            let numbered = conn.numbered.load(Ordering::SeqCst);
1892            let meta_on = conn.meta_enabled.load(Ordering::SeqCst);
1893            batch_skips.clear();
1894            let decoded = decode_buffered(
1895                &codec,
1896                &mut carry,
1897                &mut deducer,
1898                numbered.then_some(&mut counter),
1899                until.map(|n| (n, &mut resent)),
1900                dg.as_ref(),
1901                Some(&conn.gaps),
1902                tcp_comp.as_mut(),
1903                Some((&conn.wire_bytes, &conn.raw_bytes)),
1904                meta_on.then_some(&conn.metadata),
1905                &mut batch_skips,
1906                &mut batch,
1907            );
1908            match dg.as_ref() {
1909                // The merged stream owns loss, gaps, and dejitter skips for a
1910                // `dgram` connection.
1911                Some(d) => {
1912                    d.deliver(&queue, &conn.lost);
1913                    conn.on_udp.store(d.on_udp(), Ordering::SeqCst);
1914                }
1915                None => conn.lost.store(counter.lost(), Ordering::SeqCst),
1916            }
1917            conn.resent.store(resent, Ordering::SeqCst);
1918            if !batch.is_empty() {
1919                last_data = Instant::now();
1920                if let Some(last) = batch.last() {
1921                    conn.latency.record(last.timestamp);
1922                }
1923                queue.push_owned_packed_with_skips(&mut batch, &batch_skips);
1924            } else if dg.is_none() && !batch_skips.is_empty() {
1925                for &(_, count) in &batch_skips {
1926                    queue.record_skipped(count);
1927                }
1928            }
1929            if let Err(ref e) = decoded {
1930                if std::env::var_os("LSL_TRACE_RECOVER").is_some()
1931                    || std::env::var_os("LSL_TRACE_DGRAM").is_some()
1932                {
1933                    eprintln!("TRACE decode error (closing inlet): {e:?}");
1934                }
1935                // A stream that cannot be decoded is not worth recovering.
1936                // The bytes are wrong, not missing.
1937                done.store(true, Ordering::SeqCst);
1938                clock.stop();
1939                queue.close();
1940                return;
1941            }
1942
1943            match sock.read(&mut tmp) {
1944                Ok(0) => Some(Ending::Closed),
1945                Ok(n) => {
1946                    if let Some(ref mut er) = enc_reader {
1947                        if er.decrypt_into(&tmp[..n], &mut carry).is_err() {
1948                            done.store(true, Ordering::SeqCst);
1949                            clock.stop();
1950                            queue.close();
1951                            return;
1952                        }
1953                    } else {
1954                        carry.extend_from_slice(&tmp[..n]);
1955                    }
1956                    last_data = Instant::now();
1957                    None
1958                }
1959                Err(ref e) if read_timed_out(e) => {
1960                    // A source that stopped without closing looks exactly like a
1961                    // quiet one. The watchdog is what tells them apart. On UDP,
1962                    // no byte arrives on TCP, and the datagrams are the data.
1963                    let threshold = watchdog_threshold();
1964                    let on_udp = dg.as_ref().is_some_and(|d| d.heard_within(threshold));
1965                    if on_udp {
1966                        last_data = Instant::now();
1967                    }
1968                    if last_data.elapsed() > threshold {
1969                        Some(Ending::Quiet)
1970                    } else {
1971                        None
1972                    }
1973                }
1974                Err(_) => Some(Ending::Closed),
1975            }
1976        };
1977
1978        let ending = match ended {
1979            Some(e) => e,
1980            None => continue,
1981        };
1982        let trace = std::env::var_os("LSL_TRACE_RECOVER").is_some();
1983        if trace {
1984            eprintln!("TRACE recover: {ending:?}, recover={}", conn.recover);
1985        }
1986        if ending == Ending::Closed {
1987            if let Some(old_shm) = shm.take() {
1988                if conn.recover {
1989                    if let Some(exp) = old_shm.close_for_recovery() {
1990                        counter.resync(exp);
1991                    }
1992                } else {
1993                    old_shm.close_local();
1994                }
1995            }
1996            conn.on_shm.store(false, Ordering::SeqCst);
1997        }
1998        if !conn.recover {
1999            break;
2000        }
2001        let known = conn.info.lock().unwrap().clone();
2002        if trace {
2003            eprintln!(
2004                "TRACE recover: query {:?} recoverable={}",
2005                known.recovery_query(),
2006                known.is_recoverable()
2007            );
2008        }
2009        if !known.is_recoverable() {
2010            // Without a source identifier the query can match another stream,
2011            // so liblsl refuses to recover. SPEC.md 10.1.
2012            break;
2013        }
2014        if ending == Ending::Closed {
2015            conn.connected.store(false, Ordering::SeqCst);
2016        }
2017
2018        // With `dgram`, the merged stream knows the next number. The count
2019        // takes it, and the next connection asks from it. A quiet
2020        // connection can still continue, so its `dgram` part stays until a
2021        // new connection replaces the socket.
2022        if ending == Ending::Closed {
2023            if let Some(e) = dg.take().and_then(|d| d.close()) {
2024                counter.resync(e);
2025            }
2026            conn.on_udp.store(false, Ordering::SeqCst);
2027        }
2028
2029        // Try until a connection exists again, or the inlet closes.
2030        loop {
2031            if queue.is_closed() {
2032                conn.connected.store(false, Ordering::SeqCst);
2033                done.store(true, Ordering::SeqCst);
2034                clock.stop();
2035                return;
2036            }
2037
2038            // A closed connection to an outlet that still runs is the usual
2039            // case after a network fault. The handshake sends the old
2040            // instance identifier, and the outlet answers with its own, so a
2041            // different outlet on the same port cannot attach. liblsl
2042            // connects again to the same endpoint after an error
2043            // (`src/data_receiver.cpp:331-345`).
2044            if ending == Ending::Closed {
2045                // With `resume/1`, the request asks for the samples from the
2046                // number that the count expects. `docs/extensions.md`,
2047                // negotiation rule 5.
2048                let from = epoch
2049                    .zip(counter.expected())
2050                    .map(|(epoch, number)| features::ResumeParam { epoch, number });
2051                if let Ok(hs) = handshake(
2052                    &known,
2053                    Duration::from_secs(1),
2054                    buffer_samples,
2055                    from,
2056                    requested_selection.as_ref(),
2057                ) {
2058                    let (s, c, new_codec, new_sel, new_shm, new_enc, rest) = (
2059                        hs.stream,
2060                        hs.client,
2061                        hs.codec,
2062                        hs.selection,
2063                        hs.shm,
2064                        hs.enc_reader,
2065                        hs.carry,
2066                    );
2067                    if trace {
2068                        eprintln!("TRACE recover: connected again to {}", known.uid);
2069                    }
2070                    let _ = s.set_read_timeout(Some(Duration::from_millis(200)));
2071                    *conn.tcp_shutdown.lock().unwrap() = s.try_clone().ok();
2072                    sock = s;
2073                    carry = rest;
2074                    codec = new_codec;
2075                    enc_reader = new_enc;
2076                    conn.encrypted.store(enc_reader.is_some(), Ordering::SeqCst);
2077                    let eff_srate = new_sel.as_ref().map_or(known.nominal_srate, |sel| {
2078                        sel.output_srate(known.nominal_srate)
2079                    });
2080                    *conn.selection.lock().unwrap() = new_sel;
2081                    let answer = features::resume_answer(c.features());
2082                    // A new epoch is a new run of the outlet with the old
2083                    // instance identifier. Its counter, its timestamps, and
2084                    // its clock offset are new. `docs/extensions.md`,
2085                    // negotiation rule 8.
2086                    if let (Some(old), Some(a)) = (epoch, answer) {
2087                        if old != a.epoch {
2088                            if trace {
2089                                eprintln!("TRACE recover: a new run of the outlet");
2090                            }
2091                            counter.restart();
2092                            conn.shm_next_expected.store(u64::MAX, Ordering::Release);
2093                            deducer = labstream_wire::TimestampDeducer::new(eff_srate);
2094                            clock.reset_offset();
2095                            conn.gaps.lock().unwrap().reset_cursor();
2096                            queue.clear_skips();
2097                        }
2098                    }
2099                    if let Some(a) = answer {
2100                        epoch = Some(a.epoch);
2101                    }
2102                    until = answer.map(|a| a.number);
2103                    *conn.shm.lock().unwrap() = new_shm.clone();
2104                    conn.on_shm.store(new_shm.is_some(), Ordering::SeqCst);
2105                    conn.shm_gen.fetch_add(1, Ordering::Release);
2106                    let new_comp = new_shm.is_none() && features::comp_answer(c.features());
2107                    conn.compressed.store(new_comp, Ordering::SeqCst);
2108                    tcp_comp = new_comp.then(|| {
2109                        labstream_proto::comp::CompState::new(codec.format, codec.channels)
2110                    });
2111                    shm = new_shm;
2112                    dg = if shm.is_some() {
2113                        None
2114                    } else {
2115                        start_dgram(features::dgram_answer(c.features()), &sock, codec, until)
2116                    };
2117                    conn.resumed.store(answer.is_some(), Ordering::SeqCst);
2118                    conn.numbered.store(uses_seq(&c), Ordering::SeqCst);
2119                    conn.meta_enabled.store(
2120                        features::has(c.features(), features::META, 1),
2121                        Ordering::SeqCst,
2122                    );
2123                    conn.recoveries.fetch_add(1, Ordering::SeqCst);
2124                    conn.connected.store(true, Ordering::SeqCst);
2125                    last_data = Instant::now();
2126                    break;
2127                }
2128            }
2129
2130            let found = find_again(&known);
2131            if trace {
2132                eprintln!("TRACE recover: found {found:?}");
2133            }
2134            match found {
2135                Found::Moved(fresh) => {
2136                    match handshake(
2137                        &fresh,
2138                        Duration::from_secs(5),
2139                        buffer_samples,
2140                        None,
2141                        requested_selection.as_ref(),
2142                    ) {
2143                        Ok(hs) => {
2144                            let (s, c, new_codec, new_sel, new_shm, new_enc, rest) = (
2145                                hs.stream,
2146                                hs.client,
2147                                hs.codec,
2148                                hs.selection,
2149                                hs.shm,
2150                                hs.enc_reader,
2151                                hs.carry,
2152                            );
2153                            // The old connection ends here. No sample of it
2154                            // goes to the queue after this point.
2155                            if let Some(old) = dg.take() {
2156                                old.close();
2157                            }
2158                            conn.on_udp.store(false, Ordering::SeqCst);
2159                            let _ = s.set_read_timeout(Some(Duration::from_millis(200)));
2160                            *conn.tcp_shutdown.lock().unwrap() = s.try_clone().ok();
2161                            sock = s;
2162                            carry = rest;
2163                            codec = new_codec;
2164                            enc_reader = new_enc;
2165                            conn.encrypted.store(enc_reader.is_some(), Ordering::SeqCst);
2166                            let eff_srate = new_sel.as_ref().map_or(fresh.nominal_srate, |sel| {
2167                                sel.output_srate(fresh.nominal_srate)
2168                            });
2169                            *conn.selection.lock().unwrap() = new_sel;
2170                            // The old offset, the old fit, and the timestamp
2171                            // accumulator all describe a process that has
2172                            // gone. The probes go to the new service port
2173                            // (`src/time_receiver.cpp:26-33`).
2174                            // The new target goes in first, so that a burst to
2175                            // the old target cannot publish after the reset.
2176                            if let Some(target) = service_endpoint(&fresh) {
2177                                clock.retarget(target);
2178                            }
2179                            clock.reset_offset();
2180                            deducer = labstream_wire::TimestampDeducer::new(eff_srate);
2181                            // A new outlet has a new counter and a new epoch.
2182                            counter.restart();
2183                            conn.shm_next_expected.store(u64::MAX, Ordering::Release);
2184                            conn.gaps.lock().unwrap().reset_cursor();
2185                            queue.clear_skips();
2186                            let answer = features::resume_answer(c.features());
2187                            epoch = answer.map(|a| a.epoch);
2188                            until = answer.map(|a| a.number);
2189                            *conn.shm.lock().unwrap() = new_shm.clone();
2190                            conn.on_shm.store(new_shm.is_some(), Ordering::SeqCst);
2191                            conn.shm_gen.fetch_add(1, Ordering::Release);
2192                            let new_comp = new_shm.is_none() && features::comp_answer(c.features());
2193                            conn.compressed.store(new_comp, Ordering::SeqCst);
2194                            conn.wire_bytes.store(0, Ordering::Relaxed);
2195                            conn.raw_bytes.store(0, Ordering::Relaxed);
2196                            tcp_comp = new_comp.then(|| {
2197                                labstream_proto::comp::CompState::new(codec.format, codec.channels)
2198                            });
2199                            shm = new_shm;
2200                            dg = if shm.is_some() {
2201                                None
2202                            } else {
2203                                start_dgram(
2204                                    features::dgram_answer(c.features()),
2205                                    &sock,
2206                                    codec,
2207                                    until,
2208                                )
2209                            };
2210                            conn.resumed.store(answer.is_some(), Ordering::SeqCst);
2211                            conn.numbered.store(uses_seq(&c), Ordering::SeqCst);
2212                            conn.meta_enabled.store(
2213                                features::has(c.features(), features::META, 1),
2214                                Ordering::SeqCst,
2215                            );
2216                            *conn.info.lock().unwrap() = *fresh;
2217                            conn.recoveries.fetch_add(1, Ordering::SeqCst);
2218                            conn.connected.store(true, Ordering::SeqCst);
2219                            last_data = Instant::now();
2220                            break;
2221                        }
2222                        Err(_) => std::thread::sleep(Duration::from_millis(500)),
2223                    }
2224                }
2225                Found::Same | Found::Nothing if ending == Ending::Quiet => {
2226                    // The socket is still open. liblsl does nothing in this
2227                    // case and continues to read (`src/inlet_connection.cpp:187-188`).
2228                    // The next check comes after one more watchdog period.
2229                    last_data = Instant::now();
2230                    break;
2231                }
2232                Found::Same | Found::Nothing => {
2233                    // Wait a little so that the outlet does not see a flood of
2234                    // connections. liblsl waits the same time
2235                    // (`src/data_receiver.cpp:345`).
2236                    std::thread::sleep(Duration::from_millis(500));
2237                }
2238            }
2239        }
2240    }
2241
2242    conn.connected.store(false, Ordering::SeqCst);
2243    conn.on_shm.store(false, Ordering::SeqCst);
2244    if let Some(old_shm) = shm.take() {
2245        old_shm.close_local();
2246    }
2247    done.store(true, Ordering::SeqCst);
2248    // No new offset can matter now. A stop also ends a wait for the first one.
2249    clock.stop();
2250    queue.close();
2251}
2252
2253/// Decode every whole sample in `carry` and add it to `out`.
2254///
2255/// The bytes of the decoded samples leave `carry` with one move at the end.
2256/// A move after each sample costs time in proportion to the square of the
2257/// buffer size, and a burst of data fills the buffer.
2258///
2259/// The bytes of a sample that is not complete stay in `carry`.
2260///
2261/// `resent` holds `N`, the first live number of a `resume/1` connection, and
2262/// the count of samples below it. A numbered sample below `N` came from the
2263/// history of the outlet.
2264#[allow(clippy::too_many_arguments)]
2265fn decode_buffered(
2266    codec: &labstream_wire::Codec,
2267    carry: &mut Vec<u8>,
2268    deducer: &mut labstream_wire::TimestampDeducer,
2269    mut counter: Option<&mut labstream_proto::seq::Counter>,
2270    mut resent: Option<(u64, &mut u64)>,
2271    dg: Option<&crate::dgram_in::DgramIn>,
2272    tcp_gaps: Option<&Arc<Mutex<GapTracker>>>,
2273    mut comp: Option<&mut labstream_proto::comp::CompState>,
2274    byte_stats: Option<(&AtomicU64, &AtomicU64)>,
2275    meta_inbox: Option<&Mutex<MetadataInbox>>,
2276    batch_skips: &mut Vec<(usize, u64)>,
2277    out: &mut Vec<PackedSample>,
2278) -> Result<(), labstream_wire::Error> {
2279    use labstream_proto::dgram::{self, Record};
2280    use labstream_proto::seq::{peek, Next, RECORD_LEN};
2281    let mut pos = 0;
2282    let mut wire_acc = 0u64;
2283    let mut raw_acc = 0u64;
2284    let mut last_tcp_ts: Option<f64> = None;
2285    let mut first_tcp_ts: Option<f64> = None;
2286    let mut had_gap_event = false;
2287    let result = loop {
2288        // With `seq/1`, a numbering record can stand before a sample. A cut
2289        // record waits for more bytes, as a cut sample does.
2290        if let Some(c) = counter.as_deref_mut() {
2291            match peek(&carry[pos..]) {
2292                Next::Record(n) => {
2293                    let before = c.lost();
2294                    c.record(n);
2295                    let delta = c.lost().saturating_sub(before);
2296                    if let Some(d) = dg {
2297                        d.seq_record(n, c.lost(), delta);
2298                    } else if delta > 0 {
2299                        if let Some(g) = tcp_gaps {
2300                            let mut tracker = g.lock().unwrap();
2301                            if let (Some(first), Some(last)) =
2302                                (first_tcp_ts.take(), last_tcp_ts.take())
2303                            {
2304                                tracker.on_batch(first, last);
2305                            }
2306                            tracker.record_lost(delta);
2307                            had_gap_event = true;
2308                        }
2309                        batch_skips.push((out.len(), delta));
2310                    }
2311                    pos += RECORD_LEN;
2312                    continue;
2313                }
2314                Next::Incomplete => break Ok(()),
2315                Next::Sample => {}
2316            }
2317        }
2318        // With `dgram/1`, a path record can stand before a sample.
2319        if let Some(d) = dg {
2320            match dgram::peek(&carry[pos..]) {
2321                Record::Path { path, .. } => {
2322                    d.path(path);
2323                    pos += dgram::PATH_LEN;
2324                    continue;
2325                }
2326                Record::Incomplete => break Ok(()),
2327                _ => {}
2328            }
2329        }
2330        // With `meta/1`, a live metadata record can stand before a sample.
2331        if let Some(inbox) = meta_inbox {
2332            match labstream_proto::meta::peek(&carry[pos..]) {
2333                labstream_proto::meta::Next::Record(upd, used) => {
2334                    inbox.lock().unwrap().push(upd);
2335                    pos += used;
2336                    continue;
2337                }
2338                labstream_proto::meta::Next::Incomplete => break Ok(()),
2339                labstream_proto::meta::Next::Invalid => {
2340                    break Err(labstream_wire::Error::BadTag(labstream_proto::meta::TAG))
2341                }
2342                labstream_proto::meta::Next::Other => {}
2343            }
2344        }
2345        let step = match comp.as_deref_mut() {
2346            Some(c) => c.decode_tcp_sample(codec, &carry[pos..]),
2347            None => codec
2348                .decode_packed(&carry[pos..])
2349                .map(|(s, used)| (s, used, used)),
2350        };
2351        match step {
2352            Ok((mut sample, used, plain_wire)) => {
2353                pos += used;
2354                wire_acc += used as u64;
2355                raw_acc += plain_wire as u64;
2356                sample.timestamp = deducer.apply(sample.timestamp);
2357                let number = counter.as_deref().and_then(|c| c.expected());
2358                if let Some(c) = counter.as_deref_mut() {
2359                    if let (Some(number), Some((until, n))) = (c.expected(), resent.as_mut()) {
2360                        if number < *until {
2361                            **n += 1;
2362                        }
2363                    }
2364                    c.sample();
2365                }
2366                // A `dgram` connection merges its two paths by number.
2367                match (dg, number) {
2368                    (Some(d), Some(n)) => d.tcp_sample(n, sample),
2369                    _ => {
2370                        if first_tcp_ts.is_none() {
2371                            first_tcp_ts = Some(sample.timestamp);
2372                        }
2373                        last_tcp_ts = Some(sample.timestamp);
2374                        if had_gap_event {
2375                            if let Some(g) = tcp_gaps {
2376                                g.lock().unwrap().on_sample(sample.timestamp);
2377                            }
2378                            had_gap_event = false;
2379                            first_tcp_ts = None;
2380                        }
2381                        out.push(sample);
2382                    }
2383                }
2384            }
2385            Err(labstream_wire::Error::Truncated) => break Ok(()),
2386            Err(e) => break Err(e),
2387        }
2388    };
2389    if let (Some((wb, rb)), true) = (byte_stats, raw_acc > 0) {
2390        wb.fetch_add(wire_acc, Ordering::Relaxed);
2391        rb.fetch_add(raw_acc, Ordering::Relaxed);
2392    }
2393    if let (Some(g), Some(first), Some(last)) = (tcp_gaps, first_tcp_ts, last_tcp_ts) {
2394        g.lock().unwrap().on_batch(first, last);
2395    }
2396    carry.drain(..pos);
2397    result
2398}
2399
2400/// Why the reader stopped reading the current connection.
2401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2402enum Ending {
2403    /// The outlet closed the connection, or the socket reported an error.
2404    Closed,
2405    /// No data arrived for one watchdog period. The socket is still open.
2406    Quiet,
2407}
2408
2409/// The result of a search for a lost stream.
2410#[derive(Debug)]
2411enum Found {
2412    /// The stream with the old instance identifier is still visible.
2413    Same,
2414    /// Exactly one stream matches, and it has a new instance identifier.
2415    Moved(Box<StreamInfo>),
2416    /// No stream matches, or more than one does.
2417    Nothing,
2418}
2419
2420/// Find the stream again after its source restarted.
2421///
2422/// The query comes from [`StreamInfo::recovery_query`]. liblsl accepts the
2423/// result only when exactly one stream matches, because a source identifier
2424/// that is not unique would otherwise attach the inlet to the wrong stream
2425/// (`src/inlet_connection.cpp:188-192`).
2426fn find_again(known: &StreamInfo) -> Found {
2427    let found = match resolve(&known.recovery_query(), 1, Duration::from_secs(2)) {
2428        Ok(f) => f,
2429        Err(_) => return Found::Nothing,
2430    };
2431    // A result that still carries the old identifier means that the source
2432    // did not go away (`src/inlet_connection.cpp:186-188`).
2433    if found.iter().any(|f| f.uid == known.uid) {
2434        return Found::Same;
2435    }
2436    if found.len() != 1 {
2437        return Found::Nothing;
2438    }
2439    Found::Moved(Box::new(found.into_iter().next().unwrap()))
2440}
2441
2442/// True when a read ended because its read timeout ran out.
2443///
2444/// On Unix, a read timeout gives `EAGAIN` (`WouldBlock`). `ETIMEDOUT`
2445/// (`TimedOut`) there means that the kernel ended the connection, for example
2446/// after keepalive probes got no answer. That is a lost connection, not a
2447/// quiet one. Windows gives `WSAETIMEDOUT` for a read timeout, so on Windows
2448/// both kinds mean a quiet connection.
2449fn read_timed_out(e: &std::io::Error) -> bool {
2450    match e.kind() {
2451        std::io::ErrorKind::WouldBlock => true,
2452        std::io::ErrorKind::TimedOut => cfg!(not(unix)),
2453        _ => false,
2454    }
2455}
2456
2457/// Ask a data port for the whole description.
2458///
2459/// The exchange is one line out and a document back. The sender closes the
2460/// connection when the document is complete, so the reader reads to the end of
2461/// the stream (`src/info_receiver.cpp:60-67`).
2462///
2463/// A description that arrives with a created time of zero is not usable, and
2464/// liblsl retries. This returns an error instead, and the caller decides.
2465pub fn read_fullinfo(known: &StreamInfo, timeout: Duration) -> std::io::Result<StreamInfo> {
2466    let addr = data_endpoint(known)?;
2467    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
2468    stream.set_nodelay(true)?;
2469    stream.set_read_timeout(Some(timeout))?;
2470    stream.write_all(b"LSL:fullinfo\r\n")?;
2471    stream.flush()?;
2472
2473    let mut text = String::new();
2474    stream.read_to_string(&mut text)?;
2475    StreamInfo::from_fullinfo_xml(&text).map_err(std::io::Error::other)
2476}
2477
2478/// True when the connection of this client uses `seq/1`.
2479fn uses_seq(client: &FeedClient) -> bool {
2480    features::has(client.features(), features::SEQ, 1)
2481}
2482
2483/// Connect and run the whole handshake. SPEC.md 4 and 6.
2484///
2485/// The reader thread calls this again after a recovery, so it lives outside
2486/// [`Inlet`] and holds no state of its own.
2487///
2488/// `resume_from` is the epoch and the number for a `resume/1` request, or
2489/// `None` for a request with no parameter.
2490struct HandshakeResult {
2491    stream: TcpStream,
2492    client: FeedClient,
2493    codec: labstream_wire::Codec,
2494    selection: Option<features::SelectParam>,
2495    shm: Option<Arc<crate::shm::ShmReader>>,
2496    enc_reader: Option<crate::enc::EncReader>,
2497    carry: Vec<u8>,
2498}
2499
2500fn handshake(
2501    info: &StreamInfo,
2502    timeout: Duration,
2503    buffer_samples: i32,
2504    resume_from: Option<features::ResumeParam>,
2505    selection: Option<&features::SelectParam>,
2506) -> std::io::Result<HandshakeResult> {
2507    let addr = data_endpoint(info)?;
2508    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
2509    stream.set_nodelay(true)?;
2510    stream.set_read_timeout(Some(timeout))?;
2511    crate::keepalive::enable(&stream);
2512
2513    let mut params = FeedParams::new(&info.uid, info.format);
2514    params.hostname = crate::info::hostname();
2515    params.source_id = info.source_id.clone();
2516    params.session_id = info.session_id.clone();
2517    params.max_buffer_length = buffer_samples.max(1);
2518
2519    // A labstream outlet answers the offer, and any other outlet ignores it.
2520    // `docs/extensions.md`.
2521    let allowed = &crate::config::get().features;
2522    let enc_policy = crate::enc::effective_policy();
2523    let enc_kp = if enc_policy.enabled {
2524        Some(crate::enc::EphemeralKey::generate()?)
2525    } else {
2526        None
2527    };
2528    let mut offer = features::offer(allowed);
2529    offer.extend(features::offer_resume(allowed, resume_from));
2530    offer.extend(features::offer_dgram(allowed));
2531    offer.extend(features::offer_select(allowed, selection));
2532    offer.extend(features::offer_comp(
2533        allowed,
2534        info.format == labstream_wire::Format::String,
2535    ));
2536    if let Some(ref kp) = enc_kp {
2537        offer.push(features::offer_enc(kp.public_bytes()));
2538    }
2539    if crate::shm::supported()
2540        && info.format != labstream_wire::Format::String
2541        && selection.map_or(true, |s| s.decimate <= 1)
2542    {
2543        offer.extend(features::offer_shm(allowed));
2544    }
2545    let (mut client, request) =
2546        FeedClient::start_with(params, info.format, info.channel_count as usize, offer);
2547    stream.write_all(&request)?;
2548    stream.flush()?;
2549
2550    let mut buf = Vec::new();
2551    let mut tmp = [0u8; 8192];
2552
2553    // Read the answer headers.
2554    loop {
2555        match client.on_headers(&buf) {
2556            Ok(used) => {
2557                buf.drain(..used);
2558                break;
2559            }
2560            Err(labstream_proto::header::Error::Incomplete) => {}
2561            Err(e) => return Err(std::io::Error::other(e.to_string())),
2562        }
2563        let n = stream.read(&mut tmp)?;
2564        if n == 0 {
2565            return Err(std::io::Error::other(
2566                "the outlet closed during the handshake",
2567            ));
2568        }
2569        buf.extend_from_slice(&tmp[..n]);
2570    }
2571
2572    // Fail immediately after reading headers if encryption is required and the
2573    // outlet did not negotiate `enc/1`, before waiting for any test pattern.
2574    if enc_policy.required && features::enc_answer(client.features()).is_none() {
2575        return Err(std::io::Error::new(
2576            std::io::ErrorKind::PermissionDenied,
2577            "encryption is required (labstream.RequireEncryption = 1), but the outlet did not negotiate enc/1",
2578        ));
2579    }
2580
2581    // Read the two test pattern samples and compare them.
2582    loop {
2583        match client.on_test_pattern(&buf) {
2584            Ok(used) => {
2585                buf.drain(..used);
2586                break;
2587            }
2588            Err(TestPatternError::Incomplete) => {}
2589            Err(e) => {
2590                return Err(std::io::Error::other(format!(
2591                    "the test pattern did not match: {e:?}"
2592                )))
2593            }
2594        }
2595        let n = stream.read(&mut tmp)?;
2596        if n == 0 {
2597            return Err(std::io::Error::other(
2598                "the outlet closed before the test pattern",
2599            ));
2600        }
2601        buf.extend_from_slice(&tmp[..n]);
2602    }
2603
2604    debug_assert_eq!(client.state(), State::Streaming);
2605
2606    // Derive `enc/1` session key if both sides negotiated encryption, or fail
2607    // with a clear error when `labstream.RequireEncryption = 1`.
2608    let mut enc_reader = match (enc_kp, features::enc_answer(client.features())) {
2609        (Some(kp), Some(peer_enc)) => {
2610            let key = kp.derive_feed_key(peer_enc.pubkey, false, enc_policy.psk.as_deref())?;
2611            Some(crate::enc::EncReader::new(&key)?)
2612        }
2613        _ if enc_policy.required => {
2614            return Err(std::io::Error::new(
2615                std::io::ErrorKind::PermissionDenied,
2616                "encryption is required (labstream.RequireEncryption = 1), but the outlet did not negotiate enc/1",
2617            ));
2618        }
2619        _ => None,
2620    };
2621
2622    // Decrypt any post-test-pattern bytes already buffered during the handshake,
2623    // and verify the outlet's initial key-confirmation frame so PSK mismatches
2624    // fail immediately during `open`.
2625    let carry = if let Some(ref mut er) = enc_reader {
2626        let mut plain = Vec::new();
2627        if !buf.is_empty() {
2628            er.decrypt_into(&buf, &mut plain)?;
2629            buf.clear();
2630        }
2631        if plain.is_empty() {
2632            // Read at least the outlet's initial authenticated frame (20 bytes).
2633            let mut got_confirm = false;
2634            while !got_confirm {
2635                let n = stream.read(&mut tmp)?;
2636                if n == 0 {
2637                    return Err(std::io::Error::new(
2638                        std::io::ErrorKind::UnexpectedEof,
2639                        "outlet closed before encrypted key confirmation",
2640                    ));
2641                }
2642                let before = plain.len();
2643                er.decrypt_into(&tmp[..n], &mut plain)?;
2644                // `write_frame(&[])` produces 20 ciphertext bytes -> 0 plaintext
2645                // bytes, or combined with the initial `seq` record (>0 plaintext).
2646                // Once we have consumed at least 20 ciphertext bytes without
2647                // error, the first Poly1305 tag succeeded.
2648                if n >= 20 || plain.len() > before {
2649                    got_confirm = true;
2650                }
2651            }
2652        }
2653        plain
2654    } else {
2655        buf
2656    };
2657
2658    let active_selection = features::select_answer(client.features());
2659    let out_channels = active_selection
2660        .as_ref()
2661        .map_or(info.channel_count as usize, |sel| {
2662            sel.output_channels(info.channel_count as usize)
2663        });
2664    let data_codec = match (&active_selection, client.agreement()) {
2665        (Some(_), Some(ag)) => labstream_wire::Codec::new(info.format, out_channels, ag.order)
2666            .with_suppress_subnormals(ag.suppress_subnormals),
2667        _ => *client.codec().expect("the handshake set the codec"),
2668    };
2669
2670    // Steps 3-4 of `docs/extensions.md` (`shm`): open the segment, verify its
2671    // random token, and reply `shm-ok <token>` or `shm-no` on TCP.
2672    let shm = if enc_reader.is_none() {
2673        if let Some(sp) = features::shm_answer(client.features()) {
2674            match crate::shm::ShmReader::open(sp.id, info.format, out_channels) {
2675                Ok(reader) => {
2676                    crate::shm::write_shm_ok(&mut stream, reader.token())?;
2677                    Some(Arc::new(reader))
2678                }
2679                Err(_) => {
2680                    crate::shm::write_shm_no(&mut stream)?;
2681                    None
2682                }
2683            }
2684        } else {
2685            None
2686        }
2687    } else {
2688        None
2689    };
2690
2691    Ok(HandshakeResult {
2692        stream,
2693        client,
2694        codec: data_codec,
2695        selection: active_selection,
2696        shm,
2697        enc_reader,
2698        carry,
2699    })
2700}
2701
2702impl Inlet {
2703    /// True while the reader is attached to a source.
2704    ///
2705    /// A recovery sets this to false until the stream is found again.
2706    pub fn is_connected(&self) -> bool {
2707        self.conn.connected.load(Ordering::SeqCst)
2708    }
2709
2710    /// How many times the connection has been rebuilt. SPEC.md 10.1.
2711    pub fn recoveries(&self) -> u64 {
2712        self.conn.recoveries.load(Ordering::SeqCst)
2713    }
2714
2715    /// The stream that the reader is attached to now.
2716    ///
2717    /// A recovery replaces this, and the instance identifier changes while the
2718    /// name and the source identifier stay.
2719    pub fn current_info(&self) -> StreamInfo {
2720        let base = self.conn.info.lock().unwrap().clone();
2721        match self.conn.selection.lock().unwrap().as_ref() {
2722            Some(sel) => base.apply_selection(sel),
2723            None => base,
2724        }
2725    }
2726}
2727
2728#[cfg(test)]
2729mod tests {
2730    use super::*;
2731    use labstream_wire::{ByteOrder, Codec, Format, TimestampDeducer, Value, DEDUCED_TIMESTAMP};
2732
2733    fn stream(codec: &Codec, n: usize) -> (Vec<Sample>, Vec<u8>) {
2734        let mut bytes = Vec::new();
2735        let samples: Vec<Sample> = (0..n)
2736            .map(|k| Sample {
2737                timestamp: if k % 5 == 0 {
2738                    100.0 + k as f64
2739                } else {
2740                    DEDUCED_TIMESTAMP
2741                },
2742                values: vec![Value::F32(k as f32), Value::F32(-1.0), Value::F32(2.5)],
2743            })
2744            .collect();
2745        for s in &samples {
2746            codec.encode(s, &mut bytes).unwrap();
2747        }
2748        (samples, bytes)
2749    }
2750
2751    /// Decode the bytes that arrive in reads of the given sizes.
2752    fn decode_in_reads(codec: &Codec, bytes: &[u8], cuts: &[usize]) -> Vec<Sample> {
2753        let mut carry = Vec::new();
2754        let mut deducer = TimestampDeducer::new(100.0);
2755        let mut out: Vec<PackedSample> = Vec::new();
2756        let mut from = 0;
2757        for &to in cuts.iter().chain(std::iter::once(&bytes.len())) {
2758            carry.extend_from_slice(&bytes[from..to]);
2759            decode_buffered(
2760                codec,
2761                &mut carry,
2762                &mut deducer,
2763                None,
2764                None,
2765                None,
2766                None,
2767                None,
2768                None,
2769                None,
2770                &mut Vec::new(),
2771                &mut out,
2772            )
2773            .unwrap();
2774            from = to;
2775        }
2776        assert!(carry.is_empty(), "no byte stays behind at the end");
2777        out.iter().map(PackedSample::to_sample).collect()
2778    }
2779
2780    /// Decode in reads, with a `seq/1` counter. Give the samples and the
2781    /// counter at the end.
2782    fn decode_numbered(
2783        codec: &Codec,
2784        bytes: &[u8],
2785        cuts: &[usize],
2786    ) -> (Vec<Sample>, labstream_proto::seq::Counter) {
2787        let mut carry = Vec::new();
2788        let mut deducer = TimestampDeducer::new(100.0);
2789        let mut counter = labstream_proto::seq::Counter::new();
2790        let mut out: Vec<PackedSample> = Vec::new();
2791        let mut from = 0;
2792        for &to in cuts.iter().chain(std::iter::once(&bytes.len())) {
2793            carry.extend_from_slice(&bytes[from..to]);
2794            decode_buffered(
2795                codec,
2796                &mut carry,
2797                &mut deducer,
2798                Some(&mut counter),
2799                None,
2800                None,
2801                None,
2802                None,
2803                None,
2804                None,
2805                &mut Vec::new(),
2806                &mut out,
2807            )
2808            .unwrap();
2809            from = to;
2810        }
2811        assert!(carry.is_empty(), "no byte stays behind at the end");
2812        (out.iter().map(PackedSample::to_sample).collect(), counter)
2813    }
2814
2815    #[test]
2816    fn a_sample_below_the_first_live_number_counts_as_resent() {
2817        use labstream_proto::seq::{write_record, Counter};
2818        let codec = Codec::new(Format::Float32, 3, ByteOrder::native());
2819        let (samples, _) = stream(&codec, 10);
2820        // The history gives 20..26, and the first live number is 27. A
2821        // record then shows a drop in the queue, from 27 to 29.
2822        let mut bytes = Vec::new();
2823        write_record(&mut bytes, 20);
2824        for s in &samples[..7] {
2825            codec.encode(s, &mut bytes).unwrap();
2826        }
2827        write_record(&mut bytes, 29);
2828        for s in &samples[7..] {
2829            codec.encode(s, &mut bytes).unwrap();
2830        }
2831        let mut carry = bytes;
2832        let mut deducer = TimestampDeducer::new(100.0);
2833        let mut counter = Counter::new();
2834        let mut resent = 0u64;
2835        let mut out = Vec::new();
2836        decode_buffered(
2837            &codec,
2838            &mut carry,
2839            &mut deducer,
2840            Some(&mut counter),
2841            Some((27, &mut resent)),
2842            None,
2843            None,
2844            None,
2845            None,
2846            None,
2847            &mut Vec::new(),
2848            &mut out,
2849        )
2850        .unwrap();
2851        assert_eq!(out.len(), 10);
2852        assert_eq!(resent, 7);
2853        assert_eq!(counter.lost(), 2);
2854    }
2855
2856    #[test]
2857    fn a_numbered_stream_cut_at_any_byte_gives_the_same_samples_and_count() {
2858        use labstream_proto::seq::write_record;
2859        for order in [ByteOrder::Little, ByteOrder::Big] {
2860            let codec = Codec::new(Format::Float32, 3, order);
2861            let (samples, _) = stream(&codec, 12);
2862            // Numbers 40..45, then a gap of 3, then 48..54.
2863            let mut bytes = Vec::new();
2864            write_record(&mut bytes, 40);
2865            for s in &samples[..5] {
2866                codec.encode(s, &mut bytes).unwrap();
2867            }
2868            write_record(&mut bytes, 48);
2869            for s in &samples[5..] {
2870                codec.encode(s, &mut bytes).unwrap();
2871            }
2872            let (whole, c) = decode_numbered(&codec, &bytes, &[]);
2873            assert_eq!(whole.len(), 12);
2874            assert_eq!(c.lost(), 3);
2875            assert_eq!(c.expected(), Some(55));
2876            for cut in 1..bytes.len() {
2877                let (got, c) = decode_numbered(&codec, &bytes, &[cut]);
2878                assert_eq!(got, whole, "a cut at {cut}");
2879                assert_eq!(c.lost(), 3, "a cut at {cut}");
2880            }
2881        }
2882    }
2883
2884    #[test]
2885    fn a_plain_stream_never_reads_a_record() {
2886        // Without `seq/1`, the byte 0xFE is not a record. Here it can only
2887        // stand inside a value, and the codec reads it as data.
2888        let codec = Codec::new(Format::Int8, 1, ByteOrder::native());
2889        let s = Sample {
2890            timestamp: 1.0,
2891            values: vec![Value::I8(-2)],
2892        };
2893        let mut bytes = Vec::new();
2894        codec.encode(&s, &mut bytes).unwrap();
2895        assert!(bytes.contains(&0xFE));
2896        assert_eq!(decode_in_reads(&codec, &bytes, &[]), vec![s]);
2897    }
2898
2899    #[test]
2900    fn a_cut_at_any_byte_gives_the_same_samples() {
2901        let codec = Codec::new(Format::Float32, 3, ByteOrder::native());
2902        let (_, bytes) = stream(&codec, 40);
2903        let whole = decode_in_reads(&codec, &bytes, &[]);
2904        assert_eq!(whole.len(), 40);
2905        for cut in 1..bytes.len() {
2906            assert_eq!(
2907                decode_in_reads(&codec, &bytes, &[cut]),
2908                whole,
2909                "a cut at {cut}"
2910            );
2911        }
2912        // Many small reads, three bytes each.
2913        let cuts: Vec<usize> = (3..bytes.len()).step_by(3).collect();
2914        assert_eq!(decode_in_reads(&codec, &bytes, &cuts), whole);
2915    }
2916
2917    #[test]
2918    fn the_deduced_timestamps_follow_the_rate() {
2919        let codec = Codec::new(Format::Float32, 3, ByteOrder::native());
2920        let (_, bytes) = stream(&codec, 6);
2921        let got = decode_in_reads(&codec, &bytes, &[]);
2922        assert_eq!(got[0].timestamp, 100.0);
2923        assert!((got[1].timestamp - 100.01).abs() < 1e-9);
2924        assert_eq!(got[5].timestamp, 105.0);
2925    }
2926
2927    #[test]
2928    fn a_bad_tag_is_an_error_and_keeps_the_good_samples() {
2929        let codec = Codec::new(Format::Float32, 3, ByteOrder::native());
2930        let (_, mut bytes) = stream(&codec, 2);
2931        bytes.push(0xEE);
2932        let mut carry = bytes;
2933        let mut deducer = TimestampDeducer::new(100.0);
2934        let mut out = Vec::new();
2935        assert!(decode_buffered(
2936            &codec,
2937            &mut carry,
2938            &mut deducer,
2939            None,
2940            None,
2941            None,
2942            None,
2943            None,
2944            None,
2945            None,
2946            &mut Vec::new(),
2947            &mut out
2948        )
2949        .is_err());
2950        assert_eq!(out.len(), 2);
2951    }
2952
2953    #[test]
2954    fn decode_buffered_records_seq_gap_timestamps() {
2955        use crate::health::{GapKind, GapTracker};
2956        use labstream_proto::seq::{write_record, Counter};
2957        let codec = Codec::new(Format::Float32, 3, ByteOrder::native());
2958        let mut bytes = Vec::new();
2959        write_record(&mut bytes, 10);
2960        codec
2961            .encode(
2962                &Sample {
2963                    timestamp: 50.0,
2964                    values: vec![Value::F32(1.0), Value::F32(2.0), Value::F32(3.0)],
2965                },
2966                &mut bytes,
2967            )
2968            .unwrap();
2969        // Jump from 11 to 16 -> 5 lost samples.
2970        write_record(&mut bytes, 16);
2971        codec
2972            .encode(
2973                &Sample {
2974                    timestamp: 55.0,
2975                    values: vec![Value::F32(4.0), Value::F32(5.0), Value::F32(6.0)],
2976                },
2977                &mut bytes,
2978            )
2979            .unwrap();
2980        let mut carry = bytes;
2981        let mut deducer = TimestampDeducer::new(100.0);
2982        let mut counter = Counter::new();
2983        let gaps = Arc::new(Mutex::new(GapTracker::new()));
2984        let mut skips = Vec::new();
2985        let mut out = Vec::new();
2986        decode_buffered(
2987            &codec,
2988            &mut carry,
2989            &mut deducer,
2990            Some(&mut counter),
2991            None,
2992            None,
2993            Some(&gaps),
2994            None,
2995            None,
2996            None,
2997            &mut skips,
2998            &mut out,
2999        )
3000        .unwrap();
3001        assert_eq!(out.len(), 2);
3002        assert_eq!(counter.lost(), 5);
3003        assert_eq!(skips, vec![(1, 5)]);
3004        let recorded = gaps.lock().unwrap().snapshot(0.0);
3005        assert_eq!(recorded.len(), 1);
3006        assert_eq!(recorded[0].start, 50.0);
3007        assert_eq!(recorded[0].end, 55.0);
3008        assert_eq!(recorded[0].count, 5);
3009        assert_eq!(recorded[0].kind, GapKind::Lost);
3010    }
3011
3012    #[test]
3013    fn a_kernel_timeout_is_a_lost_connection_on_unix() {
3014        use std::io::{Error, ErrorKind};
3015        assert!(read_timed_out(&Error::from(ErrorKind::WouldBlock)));
3016        assert_eq!(
3017            read_timed_out(&Error::from(ErrorKind::TimedOut)),
3018            cfg!(not(unix))
3019        );
3020        assert!(!read_timed_out(&Error::from(ErrorKind::ConnectionReset)));
3021    }
3022
3023    #[test]
3024    fn a_query_socket_takes_the_multicast_ttl_of_the_configuration() {
3025        let leg = match Leg::open(false) {
3026            Ok(l) => l,
3027            Err(_) => {
3028                eprintln!("no local network; skipping");
3029                return;
3030            }
3031        };
3032        let want = config::get().multicast_ttl;
3033        for s in &leg.senders {
3034            assert_eq!(s.multicast_ttl_v4().unwrap(), want);
3035        }
3036    }
3037}