1use 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
20pub 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 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 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 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
110pub(crate) struct QueryWave {
123 legs: Vec<Leg>,
124 query_id: String,
127 buf: Vec<u8>,
128}
129
130struct Leg {
131 v6: bool,
133 rx: UdpSocket,
137 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
357fn 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 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 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 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 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 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 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
467pub(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 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
543pub(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
560pub(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 format!("127.0.0.1:{v4port}")
584 .parse()
585 .map_err(|_| std::io::Error::other("cannot read the loopback address"))
586}
587
588pub(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
607pub fn build_property_query(session_id: &str, prop: &str, value: &str) -> String {
611 format!("session_id='{session_id}' and {prop}='{value}'")
612}
613
614pub struct Inlet {
624 queue: Arc<SampleQueue>,
625 info: StreamInfo,
626 clock: Arc<ClockState>,
627 source: LiveSource,
628 post: PostProcessor,
629 post_options: u32,
631 device_delay_explicit: bool,
633 skip_scratch: Vec<(usize, u64)>,
635 packed_scratch: Vec<PackedSample>,
637 shm_meta_scratch: Vec<crate::shm::ShmSampleMeta>,
639 shm: Option<Arc<crate::shm::ShmReader>>,
641 shm_gen: u64,
643 shm_expected_seq: Option<u64>,
645 shm_last_ts: Option<f64>,
647 shm_latency_ticks: u64,
649 reader_done: Arc<AtomicBool>,
651 conn: Arc<ConnState>,
652}
653
654const 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 recover: bool,
677 recoveries: AtomicU64,
679 connected: AtomicBool,
681 info: Mutex<StreamInfo>,
684 selection: Mutex<Option<features::SelectParam>>,
686 shm: Mutex<Option<Arc<crate::shm::ShmReader>>>,
688 shm_gen: AtomicU64,
690 on_shm: AtomicBool,
692 compressed: AtomicBool,
694 encrypted: AtomicBool,
696 meta_enabled: AtomicBool,
698 metadata: Mutex<MetadataInbox>,
700 wire_bytes: Arc<AtomicU64>,
702 raw_bytes: Arc<AtomicU64>,
704 shm_next_expected: AtomicU64,
706 shm_dropped_prev: AtomicU64,
708 shm_drop_gaps: Mutex<VecDeque<Gap>>,
710 shm_last_ts_bits: AtomicU64,
712 tcp_shutdown: Mutex<Option<TcpStream>>,
714 numbered: AtomicBool,
716 lost: Arc<AtomicU64>,
719 on_udp: AtomicBool,
721 resumed: AtomicBool,
724 resent: AtomicU64,
726 gaps: Arc<Mutex<GapTracker>>,
728 latency: Arc<LatencyProbe>,
730}
731
732fn watchdog_threshold() -> Duration {
737 Duration::from_secs_f64(config::get().watchdog_time_threshold)
738}
739
740impl Inlet {
741 pub fn open(info: &StreamInfo, timeout: Duration) -> std::io::Result<Self> {
746 Inlet::open_with_buffer(info, timeout, 3600)
747 }
748
749 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 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 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 let queue = Arc::new(SampleQueue::new(buffer_samples.max(1) as usize));
836 let reader_done = Arc::new(AtomicBool::new(false));
837
838 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 {
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 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 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 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 pub fn device_delay(&self) -> f64 {
960 self.post.device_delay()
961 }
962
963 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 pub fn time_correction(&self) -> Option<f64> {
976 self.clock.offset()
977 }
978
979 pub fn wait_for_time_correction(&self, timeout: Duration) -> Option<f64> {
981 self.clock.wait(timeout)
982 }
983
984 pub fn time_uncertainty(&self) -> Option<f64> {
986 self.clock.uncertainty()
987 }
988
989 pub fn clock_drift(&self) -> Option<f64> {
993 self.clock.drift()
994 }
995
996 pub fn smooth_time_correction(&self, remote_ts: f64) -> Option<f64> {
999 self.clock.smooth_offset_at(remote_ts)
1000 }
1001
1002 pub fn info(&self) -> &StreamInfo {
1007 &self.info
1008 }
1009
1010 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 pub fn selection(&self) -> Option<features::SelectParam> {
1032 self.conn.selection.lock().unwrap().clone()
1033 }
1034
1035 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 #[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 #[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 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 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 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 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 s.timestamp = self.post.process(s.timestamp, &mut self.source);
1236 Ok(Some(s))
1237 }
1238 None => Ok(None),
1239 }
1240 }
1241
1242 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn on_udp(&self) -> bool {
1543 self.conn.on_udp.load(Ordering::SeqCst)
1544 }
1545
1546 pub fn on_shm(&self) -> bool {
1549 self.conn.on_shm.load(Ordering::SeqCst)
1550 }
1551
1552 pub fn is_compressed(&self) -> bool {
1554 self.conn.compressed.load(Ordering::SeqCst)
1555 }
1556
1557 pub fn is_encrypted(&self) -> bool {
1560 self.conn.encrypted.load(Ordering::SeqCst)
1561 }
1562
1563 pub fn has_live_metadata(&self) -> bool {
1566 self.conn.meta_enabled.load(Ordering::SeqCst)
1567 }
1568
1569 pub fn pending_metadata_count(&self) -> usize {
1571 self.conn.metadata.lock().unwrap().pending.len()
1572 }
1573
1574 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 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 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 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 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 pub fn buffer_capacity(&self) -> usize {
1646 self.queue.capacity()
1647 }
1648
1649 pub fn is_finished(&self) -> bool {
1651 self.reader_done.load(Ordering::SeqCst) && self.samples_available() == 0
1652 }
1653
1654 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 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 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#[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 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 let mut counter = labstream_proto::seq::Counter::new();
1814
1815 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 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 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 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 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 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 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 break;
2013 }
2014 if ending == Ending::Closed {
2015 conn.connected.store(false, Ordering::SeqCst);
2016 }
2017
2018 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 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 if ending == Ending::Closed {
2045 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 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 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 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 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 last_data = Instant::now();
2230 break;
2231 }
2232 Found::Same | Found::Nothing => {
2233 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 clock.stop();
2250 queue.close();
2251}
2252
2253#[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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2402enum Ending {
2403 Closed,
2405 Quiet,
2407}
2408
2409#[derive(Debug)]
2411enum Found {
2412 Same,
2414 Moved(Box<StreamInfo>),
2416 Nothing,
2418}
2419
2420fn 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 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
2442fn 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
2457pub 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
2478fn uses_seq(client: &FeedClient) -> bool {
2480 features::has(client.features(), features::SEQ, 1)
2481}
2482
2483struct 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 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 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 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 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 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 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 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 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 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 pub fn is_connected(&self) -> bool {
2707 self.conn.connected.load(Ordering::SeqCst)
2708 }
2709
2710 pub fn recoveries(&self) -> u64 {
2712 self.conn.recoveries.load(Ordering::SeqCst)
2713 }
2714
2715 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 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 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 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 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 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 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 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}