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::info::StreamInfo;
6use crate::queue::SampleQueue;
7use labstream_proto::discovery;
8use labstream_proto::feed::{FeedClient, FeedParams, State, TestPatternError};
9use labstream_time::{flags, PostProcessor};
10use labstream_wire::Sample;
11use std::io::{Read, Write};
12use std::net::{SocketAddr, TcpStream, UdpSocket};
13use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, Instant};
16
17/// Send a discovery query and collect the answers. SPEC.md 2.
18///
19/// The query identifier is an opaque token. This function builds one, sends
20/// it, and drops any answer that carries a different value. It never derives
21/// the value of another implementation. SPEC.md 2.3.
22pub fn resolve(query: &str, minimum: usize, timeout: Duration) -> std::io::Result<Vec<StreamInfo>> {
23    let mut wave = QueryWave::open()?;
24    let end = Instant::now() + timeout;
25    let mut found: Vec<StreamInfo> = Vec::new();
26
27    while Instant::now() < end {
28        wave.send(query);
29        let seen: Vec<String> = found.iter().map(|f| f.uid.clone()).collect();
30        for info in wave.collect(Duration::from_millis(400), |uid| {
31            seen.iter().any(|u| u == uid)
32        }) {
33            if !found.iter().any(|f| f.uid == info.uid) {
34                found.push(info);
35            }
36        }
37        if found.len() >= minimum {
38            return Ok(found);
39        }
40    }
41    Ok(found)
42}
43
44/// One set of sockets that sends a query and reads the answers.
45///
46/// A one-shot resolve and a background resolver send the same wave, so the
47/// sockets live here and both callers borrow them.
48///
49/// # One leg for each protocol
50///
51/// liblsl runs a separate attempt per protocol. Its receiving socket has one
52/// protocol, and it sends only to the groups of that protocol
53/// (`src/resolve_attempt_udp.cpp:174`). The same shape is used here, because
54/// the query carries the port that the answer must return to, and that port
55/// belongs to one socket.
56pub(crate) struct QueryWave {
57    legs: Vec<Leg>,
58    /// The token that this wave carries. An answer with a different token
59    /// belongs to another resolver. SPEC.md 2.3.
60    query_id: String,
61    buf: Vec<u8>,
62}
63
64struct Leg {
65    /// The socket that answers arrive on.
66    rx: UdpSocket,
67    /// One socket for each local address, plus one bound to any address.
68    senders: Vec<UdpSocket>,
69    return_port: u16,
70    targets: Vec<String>,
71}
72
73impl QueryWave {
74    pub(crate) fn open() -> std::io::Result<QueryWave> {
75        let cfg = config::get();
76        let mut legs = Vec::new();
77        if cfg.allow_ipv4 {
78            if let Ok(leg) = Leg::open(false) {
79                legs.push(leg);
80            }
81        }
82        if cfg.allow_ipv6 {
83            if let Ok(leg) = Leg::open(true) {
84                legs.push(leg);
85            }
86        }
87        if legs.is_empty() {
88            return Err(std::io::Error::other(
89                "no socket could be opened for a query",
90            ));
91        }
92        Ok(QueryWave {
93            legs,
94            query_id: crate::make_query_id(),
95            buf: vec![0u8; 65536],
96        })
97    }
98
99    /// Send one wave of queries, on every protocol.
100    pub(crate) fn send(&self, query: &str) {
101        let cfg = config::get();
102        for leg in &self.legs {
103            let msg = discovery::build_query(query, leg.return_port, &self.query_id);
104            for s in &leg.senders {
105                // A multicast or broadcast query goes to the multicast port.
106                // SPEC.md 1.1.
107                for addr in &leg.targets {
108                    let _ = s.send_to(&msg, (addr.as_str(), cfg.multicast_port));
109                }
110                // A unicast query walks the port range, and reaches every
111                // address that the configuration names as a peer.
112                for p in cfg.base_port..cfg.base_port + cfg.port_range {
113                    for addr in &leg.targets {
114                        let _ = s.send_to(&msg, (addr.as_str(), p));
115                    }
116                    for addr in &cfg.known_peers {
117                        let _ = s.send_to(&msg, (addr.as_str(), p));
118                    }
119                }
120            }
121        }
122    }
123
124    /// Read answers until the time runs out.
125    ///
126    /// `skip` drops an answer whose identifier the caller already holds.
127    pub(crate) fn collect(
128        &mut self,
129        window: Duration,
130        skip: impl Fn(&str) -> bool,
131    ) -> Vec<StreamInfo> {
132        let mut out: Vec<StreamInfo> = Vec::new();
133        let end = Instant::now() + window;
134        // Each socket is read in turn, with a short wait, so one quiet
135        // protocol does not hold up the other.
136        while Instant::now() < end {
137            let mut got_any = false;
138            for leg in &self.legs {
139                while let Ok((n, from)) = leg.rx.recv_from(&mut self.buf) {
140                    got_any = true;
141                    let answer = match discovery::parse_answer(&self.buf[..n]) {
142                        Some(a) => a,
143                        None => continue,
144                    };
145                    // An answer to another query is dropped.
146                    if answer.query_id != self.query_id {
147                        continue;
148                    }
149                    if let Some(mut info) = StreamInfo::from_shortinfo_xml(&answer.xml) {
150                        stamp_address(&mut info, from);
151                        if !skip(&info.uid) && !out.iter().any(|f| f.uid == info.uid) {
152                            out.push(info);
153                        }
154                    }
155                }
156            }
157            if !got_any {
158                std::thread::sleep(Duration::from_millis(5));
159            }
160        }
161        out
162    }
163}
164
165/// Write the address that an answer came from into the description.
166///
167/// An outlet leaves the field empty, and the resolver of the peer fills it in
168/// (`src/resolve_attempt_udp.cpp:135-140`). Without this an inlet has no
169/// address to connect to.
170fn stamp_address(info: &mut StreamInfo, from: SocketAddr) {
171    match from {
172        SocketAddr::V4(a) => {
173            if info.v4address.is_empty() {
174                info.v4address = a.ip().to_string();
175            }
176        }
177        SocketAddr::V6(a) => {
178            if info.v6address.is_empty() {
179                // A link-local address only names a machine together with the
180                // interface it arrived on. Without that number a connection
181                // fails with an invalid argument. asio writes the same form,
182                // and liblsl stores it as it stands
183                // (`src/resolve_attempt_udp.cpp:140`).
184                info.v6address = if a.scope_id() != 0 {
185                    format!("{}%{}", a.ip(), a.scope_id())
186                } else {
187                    a.ip().to_string()
188                };
189            }
190        }
191    }
192}
193
194impl Leg {
195    fn open(v6: bool) -> std::io::Result<Leg> {
196        let cfg = config::get();
197        let any: std::net::IpAddr = if v6 {
198            std::net::Ipv6Addr::UNSPECIFIED.into()
199        } else {
200            std::net::Ipv4Addr::UNSPECIFIED.into()
201        };
202        let rx = UdpSocket::bind((any, 0))?;
203        if !v6 {
204            rx.set_broadcast(true)?;
205        }
206        rx.set_read_timeout(Some(Duration::from_millis(40)))?;
207        let return_port = rx.local_addr()?.port();
208
209        // A query must leave by every interface that carries multicast,
210        // because a peer joins the group on one of them. liblsl walks the same
211        // list (`src/resolve_attempt_udp.cpp`, send_next_query).
212        //
213        // The standard library has no call that selects the outgoing interface
214        // for a multicast send. Binding a socket to a local address does the
215        // same thing, so this opens one socket for each address.
216        let mut senders: Vec<UdpSocket> = Vec::new();
217        if !v6 {
218            for a in crate::local_ipv4_addresses() {
219                if let Ok(s) = UdpSocket::bind((a, 0)) {
220                    let _ = s.set_broadcast(true);
221                    let _ = s.set_multicast_ttl_v4(1);
222                    let _ = s.set_multicast_loop_v4(true);
223                    senders.push(s);
224                }
225            }
226        }
227        let one = UdpSocket::bind((any, 0))?;
228        if v6 {
229            let _ = one.set_multicast_loop_v6(true);
230        } else {
231            one.set_broadcast(true)?;
232            let _ = one.set_multicast_ttl_v4(1);
233            let _ = one.set_multicast_loop_v4(true);
234        }
235        senders.push(one);
236
237        // Only the groups of this protocol.
238        let mut targets: Vec<String> = cfg
239            .multicast_addresses
240            .iter()
241            .filter(|a| match a.parse::<std::net::IpAddr>() {
242                Ok(std::net::IpAddr::V6(_)) => v6,
243                Ok(std::net::IpAddr::V4(_)) => !v6,
244                Err(_) => false,
245            })
246            .cloned()
247            .collect();
248        if v6 && !targets.iter().any(|t| t == "::1") {
249            // The loopback carries no group, so a stream on this machine needs
250            // its address named directly.
251            targets.push("::1".to_string());
252        }
253
254        Ok(Leg {
255            rx,
256            senders,
257            return_port,
258            targets,
259        })
260    }
261}
262
263/// Where the data of a stream lives.
264///
265/// A description that discovery returned carries the address that the answer
266/// came from. A description that a program built by hand carries none, and the
267/// stream can then only be on this machine.
268///
269/// liblsl takes the IPv4 endpoint when the description holds one, and the IPv6
270/// endpoint otherwise (`src/inlet_connection.cpp:115-125`).
271pub(crate) fn data_endpoint(info: &StreamInfo) -> std::io::Result<SocketAddr> {
272    endpoint(
273        &info.v4address,
274        info.v4data_port,
275        &info.v6address,
276        info.v6data_port,
277    )
278}
279
280/// The host and port that answer a time probe.
281pub(crate) fn service_endpoint(info: &StreamInfo) -> Option<SocketAddr> {
282    if !info.v4address.is_empty() && info.v4service_port != 0 {
283        return format!("{}:{}", info.v4address, info.v4service_port)
284            .parse()
285            .ok();
286    }
287    if !info.v6address.is_empty() && info.v6service_port != 0 {
288        return v6_endpoint(&info.v6address, info.v6service_port).ok();
289    }
290    format!("127.0.0.1:{}", info.v4service_port).parse().ok()
291}
292
293fn endpoint(v4: &str, v4port: u16, v6: &str, v6port: u16) -> std::io::Result<SocketAddr> {
294    if !v4.is_empty() && v4port != 0 {
295        return format!("{v4}:{v4port}")
296            .parse()
297            .map_err(|_| std::io::Error::other(format!("cannot read the address {v4}")));
298    }
299    if !v6.is_empty() && v6port != 0 {
300        return v6_endpoint(v6, v6port);
301    }
302    // No address arrived, so the stream can only be on this machine.
303    format!("127.0.0.1:{v4port}")
304        .parse()
305        .map_err(|_| std::io::Error::other("cannot read the loopback address"))
306}
307
308/// Build an IPv6 endpoint, with the interface number when the text carries one.
309///
310/// A link-local address names a machine only together with the interface that
311/// reaches it. The text holds that number after a `%`, and the standard
312/// library reads neither the `%` nor the number, so both parts are taken
313/// apart here.
314pub(crate) fn v6_endpoint(text: &str, port: u16) -> std::io::Result<SocketAddr> {
315    let (host, scope) = match text.split_once('%') {
316        Some((h, s)) => (h, s.parse::<u32>().unwrap_or(0)),
317        None => (text, 0),
318    };
319    let addr: std::net::Ipv6Addr = host
320        .parse()
321        .map_err(|_| std::io::Error::other(format!("cannot read the address {text}")))?;
322    Ok(SocketAddr::V6(std::net::SocketAddrV6::new(
323        addr, port, 0, scope,
324    )))
325}
326
327/// Build the query that liblsl builds for a property.
328///
329/// `src/resolver_impl.cpp:66-73`.
330pub fn build_property_query(session_id: &str, prop: &str, value: &str) -> String {
331    format!("session_id='{session_id}' and {prop}='{value}'")
332}
333
334/// A connected inlet.
335///
336/// A background thread reads the socket and decodes samples into a bounded
337/// queue. The application pulls from that queue.
338///
339/// The split matters. A reader that decoded inside `pull` would leave the
340/// socket unread while the application worked, so a loss would land in the
341/// outlet's queue instead of this one. liblsl runs the same background thread
342/// (`src/data_receiver.h`).
343pub struct Inlet {
344    queue: Arc<SampleQueue>,
345    info: StreamInfo,
346    clock: Arc<ClockState>,
347    source: LiveSource,
348    post: PostProcessor,
349    /// Set once the reader thread stops.
350    reader_done: Arc<AtomicBool>,
351    conn: Arc<ConnState>,
352}
353
354/// What the reader thread and the application share about the connection.
355struct ConnState {
356    /// True when the inlet finds the stream again after its source restarts.
357    recover: bool,
358    /// How many times the connection has been rebuilt.
359    recoveries: AtomicU64,
360    /// False while the reader is between connections.
361    connected: AtomicBool,
362    /// The description of the stream that the reader is attached to. A
363    /// recovery replaces it, and the instance identifier changes.
364    info: Mutex<StreamInfo>,
365}
366
367/// How long without data before the reader treats the source as gone.
368///
369/// liblsl checks on the same period and uses the same threshold
370/// (`src/api_config.cpp:302-303`).
371fn watchdog_threshold() -> Duration {
372    Duration::from_secs_f64(config::get().watchdog_time_threshold)
373}
374
375impl Inlet {
376    /// Open a feed to a resolved stream. SPEC.md 4 and 6.
377    ///
378    /// The call runs the whole handshake, including the two test pattern
379    /// samples that open every feed.
380    pub fn open(info: &StreamInfo, timeout: Duration) -> std::io::Result<Self> {
381        Inlet::open_with_buffer(info, timeout, 3600)
382    }
383
384    /// Open a feed and choose the size of the queue, in samples.
385    ///
386    /// The value also goes out in `Max-Buffer-Length`, which carries a count of
387    /// samples. A caller that thinks in seconds converts first. SPEC.md 8.6.
388    pub fn open_with_buffer(
389        info: &StreamInfo,
390        timeout: Duration,
391        buffer_samples: i32,
392    ) -> std::io::Result<Self> {
393        Inlet::open_full(info, timeout, buffer_samples, false)
394    }
395
396    /// Open a feed and choose whether the inlet finds the stream again after a
397    /// restart of its source. SPEC.md 10.1.
398    ///
399    /// liblsl enables recovery by default (`include/lsl_cpp.h:915`).
400    pub fn open_recovering(
401        info: &StreamInfo,
402        timeout: Duration,
403        buffer_samples: i32,
404    ) -> std::io::Result<Self> {
405        Inlet::open_full(info, timeout, buffer_samples, true)
406    }
407
408    fn open_full(
409        info: &StreamInfo,
410        timeout: Duration,
411        buffer_samples: i32,
412        recover: bool,
413    ) -> std::io::Result<Self> {
414        let (stream, client, buf) = handshake(info, timeout, buffer_samples)?;
415        debug_assert_eq!(client.state(), State::Streaming);
416
417        // The queue holds what the application has not pulled yet. Its size is
418        // the value that went out in `Max-Buffer-Length`, which is a count of
419        // samples. SPEC.md 8.6.
420        let queue = Arc::new(SampleQueue::new(buffer_samples.max(1) as usize));
421        let reader_done = Arc::new(AtomicBool::new(false));
422
423        // The offset thread runs for the life of the inlet. It answers on the
424        // service port, which is separate from the data port. SPEC.md 3.
425        let clock = Arc::new(ClockState::default());
426        let seed = Arc::new(Mutex::new(
427            std::process::id() as u64 ^ 0x9E37_79B9_7F4A_7C15,
428        ));
429        if let Some(target) = service_endpoint(info) {
430            crate::clock::start(target, Arc::clone(&clock), seed);
431        }
432
433        let conn = Arc::new(ConnState {
434            recover,
435            recoveries: AtomicU64::new(0),
436            connected: AtomicBool::new(true),
437            info: Mutex::new(info.clone()),
438        });
439
440        // One thread owns the connection for its whole life: it reads, and when
441        // the source goes away it finds the stream again and starts over.
442        {
443            let q = Arc::clone(&queue);
444            let done = Arc::clone(&reader_done);
445            let clk = Arc::clone(&clock);
446            let state = Arc::clone(&conn);
447            let codec = *client.codec().expect("the handshake set the codec");
448            std::thread::spawn(move || {
449                read_and_recover(stream, buf, codec, q, done, clk, state, buffer_samples);
450            });
451        }
452
453        Ok(Inlet {
454            queue,
455            reader_done,
456            conn,
457            info: info.clone(),
458            source: LiveSource::new(Arc::clone(&clock), info.nominal_srate),
459            clock,
460            // No stage runs until a caller asks for one. liblsl uses the same
461            // default (`include/lsl/common.h:103`).
462            post: PostProcessor::new(),
463        })
464    }
465
466    /// Choose the post-processing stages. SPEC.md 8.5.
467    ///
468    /// The default applies none, so a timestamp arrives as the sender wrote it.
469    pub fn set_postprocessing(&mut self, options: u32) {
470        self.post.set_options(options);
471    }
472
473    /// Apply every stage: clock sync, then jitter removal, then the clamp.
474    pub fn set_postprocessing_all(&mut self) {
475        self.post
476            .set_options(flags::CLOCKSYNC | flags::DEJITTER | flags::MONOTONIZE);
477    }
478
479    /// The measured offset between the two clocks, or `None` before the first
480    /// burst finishes.
481    ///
482    /// Add this value to a timestamp to move it onto the local clock. The
483    /// `CLOCKSYNC` stage does that on its own.
484    pub fn time_correction(&self) -> Option<f64> {
485        self.clock.offset()
486    }
487
488    /// Wait for a first offset measurement.
489    pub fn wait_for_time_correction(&self, timeout: Duration) -> Option<f64> {
490        self.clock.wait(timeout)
491    }
492
493    /// The round-trip time of the estimate that the offset came from.
494    pub fn time_uncertainty(&self) -> Option<f64> {
495        self.clock.uncertainty()
496    }
497
498    /// The description of the connected stream.
499    ///
500    /// This is the short description that discovery returned. It carries an
501    /// empty description tree. Call [`Inlet::fullinfo`] for the tree.
502    pub fn info(&self) -> &StreamInfo {
503        &self.info
504    }
505
506    /// Read the whole description, with the description tree.
507    ///
508    /// The short description that a discovery answer carries has no tree
509    /// (`src/stream_info_impl.cpp:160`). The tree travels on the data port.
510    /// This opens its own connection, the way `info_receiver` does
511    /// (`src/info_receiver.cpp:60`), and leaves the feed connection alone.
512    pub fn fullinfo(&self, timeout: Duration) -> std::io::Result<StreamInfo> {
513        read_fullinfo(&self.info, timeout)
514    }
515
516    /// Read one sample.
517    ///
518    /// Returns `Ok(None)` when the timeout passes with no whole sample.
519    ///
520    /// The timestamp passes through the post-processing stages that
521    /// [`Inlet::set_postprocessing`] selected. With none selected the value is
522    /// the one that the sender wrote.
523    pub fn pull(&mut self, timeout: Duration) -> std::io::Result<Option<Sample>> {
524        match self.queue.pop(timeout) {
525            Some(mut s) => {
526                // Every stage runs here, in the fixed order. SPEC.md 8.5.
527                s.timestamp = self.post.process(s.timestamp, &mut self.source);
528                Ok(Some(s))
529            }
530            None => Ok(None),
531        }
532    }
533
534    /// Read every sample that waits, up to `max`, with one lock.
535    ///
536    /// The samples go to the end of `out`. The call gives how many it added.
537    /// Every timestamp passes through the stages that
538    /// [`Inlet::set_postprocessing`] selected, in the order of one
539    /// [`Inlet::pull`] for each sample.
540    ///
541    /// The timeout applies to the first sample only. The call never waits for
542    /// `max` samples, because a program that shows live signals must show what
543    /// arrived.
544    ///
545    /// This is the call for a fast stream. [`Inlet::pull`] takes the queue lock
546    /// and reads the clock for each sample. A stream of 8 channels at 1000 Hz
547    /// therefore costs 1000 locks each second with `pull`, and one lock for each
548    /// block here.
549    pub fn pull_chunk(
550        &mut self,
551        out: &mut Vec<Sample>,
552        max: usize,
553        timeout: Duration,
554    ) -> std::io::Result<usize> {
555        let first = out.len();
556        let got = self.queue.pop_many(out, max, timeout);
557        // Every stage runs here, in the fixed order, one sample after another.
558        // SPEC.md 8.5. The state of the filter carries across the block, so a
559        // block gives the timestamps that the same samples get one at a time.
560        for s in &mut out[first..] {
561            s.timestamp = self.post.process(s.timestamp, &mut self.source);
562        }
563        Ok(got)
564    }
565
566    /// How many samples wait for the application.
567    pub fn samples_available(&self) -> usize {
568        self.queue.len()
569    }
570
571    /// How many samples the queue has dropped.
572    ///
573    /// Nothing on the wire carries this number, so a peer cannot learn it.
574    /// SPEC.md 8.7. This exists for a local report only.
575    pub fn samples_dropped(&self) -> u64 {
576        self.queue.dropped()
577    }
578
579    /// The size of the queue, in samples.
580    pub fn buffer_capacity(&self) -> usize {
581        self.queue.capacity()
582    }
583
584    /// True once the connection ended and every sample has been pulled.
585    pub fn is_finished(&self) -> bool {
586        self.reader_done.load(Ordering::SeqCst) && self.queue.is_empty()
587    }
588}
589
590impl Drop for Inlet {
591    fn drop(&mut self) {
592        self.clock.stop();
593        self.queue.close();
594    }
595}
596
597/// Read samples, and rebuild the connection when the source goes away.
598///
599/// SPEC.md 10.1 records what liblsl does: the inlet finds the stream again by
600/// name, type, source identifier, channel count, and channel format. The
601/// instance identifier changes across a restart, and the clock state clears
602/// because the old fit describes a process that no longer exists.
603#[allow(clippy::too_many_arguments)]
604fn read_and_recover(
605    mut sock: TcpStream,
606    mut carry: Vec<u8>,
607    mut codec: labstream_wire::Codec,
608    queue: Arc<SampleQueue>,
609    done: Arc<AtomicBool>,
610    clock: Arc<ClockState>,
611    conn: Arc<ConnState>,
612    buffer_samples: i32,
613) {
614    let mut tmp = [0u8; 65536];
615    let _ = sock.set_read_timeout(Some(Duration::from_millis(200)));
616    let mut last_data = Instant::now();
617
618    // Most samples of a chunk carry no timestamp. The reader rebuilds each one
619    // from the position in the stream, and the accumulator runs for the life of
620    // the connection. SPEC.md 8.1.
621    let srate = conn.info.lock().unwrap().nominal_srate;
622    let mut deducer = labstream_wire::TimestampDeducer::new(srate);
623
624    loop {
625        if queue.is_closed() {
626            break;
627        }
628
629        // Decode everything already buffered before reading more.
630        let mut decoded_any = false;
631        loop {
632            match codec.decode(&carry) {
633                Ok((mut sample, used)) => {
634                    carry.drain(..used);
635                    sample.timestamp = deducer.apply(sample.timestamp);
636                    queue.push(sample);
637                    decoded_any = true;
638                }
639                Err(labstream_wire::Error::Truncated) => break,
640                Err(_) => {
641                    // A stream that cannot be decoded is not worth recovering.
642                    // The bytes are wrong, not missing.
643                    done.store(true, Ordering::SeqCst);
644                    queue.close();
645                    return;
646                }
647            }
648        }
649        if decoded_any {
650            last_data = Instant::now();
651        }
652
653        let ended = match sock.read(&mut tmp) {
654            Ok(0) => true,
655            Ok(n) => {
656                carry.extend_from_slice(&tmp[..n]);
657                last_data = Instant::now();
658                false
659            }
660            Err(ref e)
661                if e.kind() == std::io::ErrorKind::WouldBlock
662                    || e.kind() == std::io::ErrorKind::TimedOut =>
663            {
664                // A source that stopped without closing looks exactly like a
665                // quiet one. The watchdog is what tells them apart.
666                last_data.elapsed() > watchdog_threshold()
667            }
668            Err(_) => true,
669        };
670
671        if !ended {
672            continue;
673        }
674        let trace = std::env::var_os("LSL_TRACE_RECOVER").is_some();
675        if trace {
676            eprintln!(
677                "TRACE recover: the connection ended, recover={}",
678                conn.recover
679            );
680        }
681        if !conn.recover {
682            break;
683        }
684
685        conn.connected.store(false, Ordering::SeqCst);
686        let known = conn.info.lock().unwrap().clone();
687        if trace {
688            eprintln!(
689                "TRACE recover: query {:?} recoverable={}",
690                known.recovery_query(),
691                known.is_recoverable()
692            );
693        }
694        if !known.is_recoverable() {
695            // Without a source identifier the query can match another stream,
696            // so liblsl refuses to recover. SPEC.md 10.1.
697            break;
698        }
699
700        let attempt = find_again(&known);
701        if trace {
702            eprintln!(
703                "TRACE recover: found {:?}",
704                attempt.as_ref().map(|f| &f.uid)
705            );
706        }
707        match attempt {
708            Some(fresh) => {
709                match handshake(&fresh, Duration::from_secs(5), buffer_samples) {
710                    Ok((s, c, rest)) => {
711                        let _ = &c;
712                        let _ = s.set_read_timeout(Some(Duration::from_millis(200)));
713                        sock = s;
714                        carry = rest;
715                        codec = *c.codec().expect("the handshake set the codec");
716                        // The old fit and the old offset describe a process
717                        // that has gone. SPEC.md 8.5.
718                        if fresh.uid != known.uid {
719                            // The old fit, the old offset, and the timestamp
720                            // accumulator all describe a process that has gone.
721                            clock.mark_reset();
722                            deducer = labstream_wire::TimestampDeducer::new(fresh.nominal_srate);
723                        }
724                        *conn.info.lock().unwrap() = fresh;
725                        conn.recoveries.fetch_add(1, Ordering::SeqCst);
726                        conn.connected.store(true, Ordering::SeqCst);
727                        last_data = Instant::now();
728                    }
729                    Err(_) => std::thread::sleep(Duration::from_millis(500)),
730                }
731            }
732            None => std::thread::sleep(Duration::from_millis(500)),
733        }
734    }
735
736    conn.connected.store(false, Ordering::SeqCst);
737    done.store(true, Ordering::SeqCst);
738    queue.close();
739}
740
741/// Find the stream again after its source restarted.
742///
743/// The query comes from [`StreamInfo::recovery_query`]. liblsl accepts the
744/// result only when exactly one stream matches, because a source identifier
745/// that is not unique would otherwise attach the inlet to the wrong stream
746/// (`src/inlet_connection.cpp:188-192`).
747fn find_again(known: &StreamInfo) -> Option<StreamInfo> {
748    let found = resolve(&known.recovery_query(), 1, Duration::from_secs(2)).ok()?;
749    if found.is_empty() {
750        return None;
751    }
752    // A result that still carries the old identifier means the source never
753    // went away, so there is nothing to recover.
754    if found.iter().any(|f| f.uid == known.uid) {
755        return None;
756    }
757    if found.len() != 1 {
758        return None;
759    }
760    Some(found.into_iter().next().unwrap())
761}
762
763/// Ask a data port for the whole description.
764///
765/// The exchange is one line out and a document back. The sender closes the
766/// connection when the document is complete, so the reader reads to the end of
767/// the stream (`src/info_receiver.cpp:60-67`).
768///
769/// A description that arrives with a created time of zero is not usable, and
770/// liblsl retries. This returns an error instead, and the caller decides.
771pub fn read_fullinfo(known: &StreamInfo, timeout: Duration) -> std::io::Result<StreamInfo> {
772    let addr = data_endpoint(known)?;
773    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
774    stream.set_nodelay(true)?;
775    stream.set_read_timeout(Some(timeout))?;
776    stream.write_all(b"LSL:fullinfo\r\n")?;
777    stream.flush()?;
778
779    let mut text = String::new();
780    stream.read_to_string(&mut text)?;
781    StreamInfo::from_fullinfo_xml(&text).map_err(std::io::Error::other)
782}
783
784/// Connect and run the whole handshake. SPEC.md 4 and 6.
785///
786/// The reader thread calls this again after a recovery, so it lives outside
787/// [`Inlet`] and holds no state of its own.
788fn handshake(
789    info: &StreamInfo,
790    timeout: Duration,
791    buffer_samples: i32,
792) -> std::io::Result<(TcpStream, FeedClient, Vec<u8>)> {
793    let addr = data_endpoint(info)?;
794    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
795    stream.set_nodelay(true)?;
796    stream.set_read_timeout(Some(timeout))?;
797
798    let mut params = FeedParams::new(&info.uid, info.format);
799    params.hostname = crate::info::hostname();
800    params.source_id = info.source_id.clone();
801    params.session_id = info.session_id.clone();
802    params.max_buffer_length = buffer_samples.max(1);
803
804    let (mut client, request) = FeedClient::start(params, info.format, info.channel_count as usize);
805    stream.write_all(&request)?;
806    stream.flush()?;
807
808    let mut buf = Vec::new();
809    let mut tmp = [0u8; 8192];
810
811    // Read the answer headers.
812    loop {
813        match client.on_headers(&buf) {
814            Ok(used) => {
815                buf.drain(..used);
816                break;
817            }
818            Err(labstream_proto::header::Error::Incomplete) => {}
819            Err(e) => return Err(std::io::Error::other(e.to_string())),
820        }
821        let n = stream.read(&mut tmp)?;
822        if n == 0 {
823            return Err(std::io::Error::other(
824                "the outlet closed during the handshake",
825            ));
826        }
827        buf.extend_from_slice(&tmp[..n]);
828    }
829
830    // Read the two test pattern samples and compare them.
831    loop {
832        match client.on_test_pattern(&buf) {
833            Ok(used) => {
834                buf.drain(..used);
835                break;
836            }
837            Err(TestPatternError::Incomplete) => {}
838            Err(e) => {
839                return Err(std::io::Error::other(format!(
840                    "the test pattern did not match: {e:?}"
841                )))
842            }
843        }
844        let n = stream.read(&mut tmp)?;
845        if n == 0 {
846            return Err(std::io::Error::other(
847                "the outlet closed before the test pattern",
848            ));
849        }
850        buf.extend_from_slice(&tmp[..n]);
851    }
852
853    debug_assert_eq!(client.state(), State::Streaming);
854    Ok((stream, client, buf))
855}
856
857impl Inlet {
858    /// True while the reader is attached to a source.
859    ///
860    /// A recovery sets this to false until the stream is found again.
861    pub fn is_connected(&self) -> bool {
862        self.conn.connected.load(Ordering::SeqCst)
863    }
864
865    /// How many times the connection has been rebuilt. SPEC.md 10.1.
866    pub fn recoveries(&self) -> u64 {
867        self.conn.recoveries.load(Ordering::SeqCst)
868    }
869
870    /// The stream that the reader is attached to now.
871    ///
872    /// A recovery replaces this, and the instance identifier changes while the
873    /// name and the source identifier stay.
874    pub fn current_info(&self) -> StreamInfo {
875        self.conn.info.lock().unwrap().clone()
876    }
877}