telegenic 2.0.3

Pure-Rust GenICam camera library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
//! The GigE Vision backend: the [`GigECamera`] transport handle and its
//! configuration, network [`discovery`], the GVCP/GVSP wire formats
//! ([`proto`]), and the GVSP [`stream`] receiver.
//!
//! `GigECamera` is a plain owned value whose connection is an `Option`:
//! construction is free and infallible, `connect()` is where I/O happens
//! (and doubles as the reconnect path), and `disconnect()` takes the
//! connection down by value, so a dead link is unreachable by construction.
//! All per-connection state — device identity, capabilities, the GenICam
//! XML and node graph — lives exactly as long as the connection.

pub mod discovery;
pub mod proto;
mod runner;
pub mod stream;

use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use fast_talker::options::{SocketOption, ThreadOption};
use parking_lot::Mutex;

use crate::error::{CameraError, Result};
use crate::gige::proto::bootstrap;
use crate::gige::proto::gvcp;
use crate::gige::proto::gvsp;
use crate::gige::runner::ToWorker;
use crate::gige::stream::{StreamChannel, StreamConfig, StreamShared};
use crate::handle::{ResponseHandle, unwrap_arc};
use crate::link::{LinkCounters, LinkStats as HealthStats};
use crate::thread_util::ThreadHandle;
use crate::tuning::{self, SocketRole, TuningReport};
use crate::wire::{
    ControlRx, ControlTelemetry, ControlTx, GvcpCmd, GvspPacket, StreamTelemetry, TelemetrySink,
};

pub use proto::bootstrap::DeviceInfo;
pub use proto::gvcp::GvcpStatus;
pub use proto::gvsp::PixelFormat;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GigeConfig {
    /// Device GVCP endpoint, normally `<device ip>:3956`.
    pub addr: SocketAddr,
    /// Local address to bind the control socket on; `0.0.0.0:0` by default.
    /// Set the IP to pick an interface on a multi-homed host.
    pub local_addr: Option<SocketAddr>,
    /// Per-try acknowledge timeout.
    pub gvcp_timeout: Duration,
    /// Retries after the first try before a transaction fails.
    pub retries: u8,
    /// Written to the device's heartbeat timeout register at connect; the
    /// worker reads CCP at a third of this period to keep control alive.
    pub heartbeat_timeout_ms: u32,
    /// Take exclusive control (no other application may even read).
    pub exclusive: bool,
    /// Buffered events per subscribed [`EventChannel`].
    pub event_capacity: usize,
    /// Options the GVCP worker applies to itself before `connect` returns;
    /// one it fails to apply fails `connect`. Accepted: `CpuAffinity`,
    /// `PrefaultStack`, `LinuxNice`, `UnixScheduler(Other | Batch | Idle)`,
    /// `WinPriority` below `TimeCritical`, `WinDisablePowerThrottling`,
    /// `MacOsQos`. Real-time classes (`RtPriority`, `UnixScheduler(Fifo |
    /// RoundRobin)`, `WinPriority(TimeCritical)`, `WinMmcss`,
    /// `MacOsTimeConstraint`) are refused: this thread blocks on slow
    /// round-trips and would only starve the rest of the system. Options for
    /// another platform are skipped with a warning. Process-wide settings
    /// are the application's to make, with
    /// [`ProcessOption::apply_all`](fast_talker::options::ProcessOption::apply_all).
    pub thread: Vec<ThreadOption>,
    /// Options for the GVCP socket, applied before bind. Accepted:
    /// `RecvBuffer`, `BindDevice`, `Dscp`, `LinuxPriority`. Refused: the
    /// busy-poll options (they burn a core on a slow loop), `SendBuffer`,
    /// `DontFragment` and `WinCpuAffinity`.
    pub control_socket: Vec<SocketOption>,
}

impl GigeConfig {
    pub fn new(ip: impl Into<IpAddr>) -> Self {
        Self {
            addr: SocketAddr::new(ip.into(), gvcp::GVCP_PORT),
            local_addr: None,
            gvcp_timeout: Duration::from_millis(500),
            retries: 4,
            heartbeat_timeout_ms: 3000,
            exclusive: false,
            event_capacity: 64,
            thread: Vec::new(),
            control_socket: Vec::new(),
        }
    }

    /// Worst-case duration of one transaction, used as the blocking budget
    /// for the convenience waits in `connect`.
    pub(crate) fn transaction_budget(&self) -> Duration {
        self.gvcp_timeout * (u32::from(self.retries) + 1) + Duration::from_millis(500)
    }
}

/// Control-channel counters.
#[cfg_attr(feature = "valuable", derive(valuable::Valuable))]
#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "py", pyo3::pyclass(get_all, skip_from_py_object))]
pub struct LinkStats {
    pub commands: u64,
    pub acks: u64,
    pub retries: u64,
    pub timeouts: u64,
    pub naks: u64,
    pub pending_acks: u64,
    pub heartbeats: u64,
    pub events: u64,
    pub unsolicited: u64,
}

/// A device-initiated message-channel event.
#[cfg_attr(feature = "valuable", derive(valuable::Valuable))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GvcpEvent {
    /// `EVENT_CMD` or `EVENTDATA_CMD`.
    pub command: u16,
    pub event_id: u16,
    pub stream_channel: u16,
    pub block_id: u16,
    pub timestamp: u64,
    /// Trailing data of an EVENTDATA event; empty for plain events.
    pub data: Vec<u8>,
    /// The unparsed command payload, kept as an escape hatch.
    pub raw: Vec<u8>,
}

impl GvcpEvent {
    pub(crate) fn parse(command: u16, payload: &[u8]) -> Self {
        let u16_at = |i: usize| {
            payload
                .get(i..i + 2)
                .map_or(0, |b| u16::from_be_bytes([b[0], b[1]]))
        };
        let timestamp = payload.get(8..16).map_or(0, |b| {
            u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])
        });
        Self {
            command,
            event_id: u16_at(2),
            stream_channel: u16_at(4),
            block_id: u16_at(6),
            timestamp,
            data: payload.get(16..).unwrap_or_default().to_vec(),
            raw: payload.to_vec(),
        }
    }
}

/// A clone-able receiver for device events. Each subscription has its own
/// bounded buffer; events are dropped (and logged) when it is full.
#[derive(Debug, Clone)]
pub struct EventChannel {
    rx: flume::Receiver<GvcpEvent>,
}

impl EventChannel {
    /// Block until an event is buffered or `timeout` elapses.
    pub fn wait_for(&self, timeout: Duration) -> Option<GvcpEvent> {
        self.rx.recv_timeout(timeout).ok()
    }

    pub fn try_recv(&self) -> Option<GvcpEvent> {
        self.rx.try_recv().ok()
    }

    pub fn is_disconnected(&self) -> bool {
        self.rx.is_disconnected()
    }

    pub async fn recv_async(&self) -> Option<GvcpEvent> {
        self.rx.recv_async().await.ok()
    }
}

/// The state the control worker genuinely shares with the camera side:
/// counters it writes continuously and the control-loss flag it raises on
/// its way down. Everything else lives in [`Connection`] as plain fields.
pub(crate) struct Shared {
    pub(crate) stats: Mutex<LinkStats>,
    pub(crate) link: Arc<LinkCounters>,
    control_lost: AtomicBool,
    /// The device accepts several registers in one READREG/WRITEREG
    /// (`CAP_CONCATENATION`). Off until the capability register is read.
    concatenation: AtomicBool,
}

impl Shared {
    fn new(link: Arc<LinkCounters>) -> Self {
        Self {
            stats: Mutex::new(LinkStats::default()),
            link,
            control_lost: AtomicBool::new(false),
            concatenation: AtomicBool::new(false),
        }
    }

    pub(crate) fn set_control_lost(&self) {
        self.control_lost.store(true, Ordering::Relaxed);
    }

    fn control_lost(&self) -> bool {
        self.control_lost.load(Ordering::Relaxed)
    }

    pub(crate) fn concatenation(&self) -> bool {
        self.concatenation.load(Ordering::Relaxed)
    }
}

/// A lightweight submission path to the control worker: enough to issue
/// transactions without owning the connection. [`StreamChannel`] holds one
/// to close its channel registers on drop, and the GenICam layer uses it as
/// the device port.
pub(crate) struct ControlPort {
    to_worker: flume::Sender<ToWorker>,
    /// Non-owning twin; only liveness and wake, never join.
    thread: ThreadHandle,
    budget: Duration,
}

impl Clone for ControlPort {
    fn clone(&self) -> Self {
        Self {
            to_worker: self.to_worker.clone(),
            thread: self.thread.to_pass_in(),
            budget: self.budget,
        }
    }
}

impl ControlPort {
    pub(crate) fn budget(&self) -> Duration {
        self.budget
    }

    fn send(&self, msg: ToWorker) -> Result<()> {
        if !self.thread.is_alive() {
            return Err(CameraError::Disconnected);
        }
        self.to_worker
            .send(msg)
            .map_err(|_| CameraError::Disconnected)?;
        self.thread.wake().ok();
        // The worker may have died between the send and now, with its
        // shutdown drain already past. Its handle fulfilment is idempotent,
        // so failing here too is safe — and guarantees no handle is left
        // pending forever.
        if !self.thread.is_alive() {
            return Err(CameraError::Disconnected);
        }
        Ok(())
    }

    fn submit<T: Clone>(
        &self,
        build: impl FnOnce(ResponseHandle<T>) -> ToWorker,
    ) -> ResponseHandle<T> {
        let handle = ResponseHandle::new();
        if let Err(e) = self.send(build(handle.clone())) {
            handle.fail(e);
        }
        handle
    }

    pub(crate) fn read_register(&self, addr: u32) -> ResponseHandle<u32> {
        self.submit(|h| ToWorker::ReadReg(addr, h))
    }

    pub(crate) fn read_registers(&self, addrs: Vec<u32>) -> ResponseHandle<Vec<u32>> {
        self.submit(|h| ToWorker::ReadRegs(addrs, h))
    }

    pub(crate) fn write_register(&self, addr: u32, value: u32) -> ResponseHandle<()> {
        tracing::trace!("write register {addr:#06x} := {value:#010x}");
        self.submit(|h| ToWorker::WriteRegs(vec![(addr, value)], h))
    }

    pub(crate) fn write_registers(&self, pairs: Vec<(u32, u32)>) -> ResponseHandle<()> {
        tracing::trace!(?pairs, "write registers");
        self.submit(|h| ToWorker::WriteRegs(pairs, h))
    }

    pub(crate) fn read_memory(&self, addr: u32, len: u32) -> ResponseHandle<Vec<u8>> {
        let handle = ResponseHandle::new();
        if !addr.is_multiple_of(4) {
            handle.fail(CameraError::Protocol(
                "read address must be 4-byte aligned".into(),
            ));
            return handle;
        }
        if let Err(e) = self.send(ToWorker::ReadMem {
            addr,
            len,
            handle: handle.clone(),
        }) {
            handle.fail(e);
        }
        handle
    }

    pub(crate) fn write_memory(&self, addr: u32, data: Vec<u8>) -> ResponseHandle<()> {
        tracing::trace!("write memory {addr:#06x} ({} bytes)", data.len());
        let handle = ResponseHandle::new();
        if !addr.is_multiple_of(4) || !data.len().is_multiple_of(4) {
            handle.fail(CameraError::Protocol(
                "write address and length must be 4-byte aligned".into(),
            ));
            return handle;
        }
        if let Err(e) = self.send(ToWorker::WriteMem {
            addr,
            data,
            handle: handle.clone(),
        }) {
            handle.fail(e);
        }
        handle
    }
}

/// One established control link and everything scoped to it.
struct Connection {
    port: ControlPort,
    /// Owner handle; joins the worker on drop.
    thread: ThreadHandle,
    shared: Arc<Shared>,
    /// The device endpoint this connection was established to (the config
    /// may have been retargeted since).
    device_addr: SocketAddr,
    local_addr: SocketAddr,
    info: DeviceInfo,
    capabilities: u32,
    genicam_xml: Option<Arc<[u8]>>,
    genicam: Option<crate::genicam::Genicam>,
    tuning: TuningReport,
}

/// A GigE Vision device over its GVCP control channel.
///
/// Plain owned value: `new`/`with_config` store configuration without IO,
/// [`connect`](Self::connect) establishes the link (taking device control,
/// starting heartbeat), and [`disconnect`](Self::disconnect) — or drop —
/// releases it. Worker-facing methods return
/// [`CameraError::Disconnected`] while no link is up. Share explicitly
/// (e.g. `Arc<Mutex<GigECamera>>`) if you need to.
pub struct GigECamera {
    cfg: GigeConfig,
    connection: Option<Connection>,
    telemetry: Option<ControlTelemetry>,
    link: Arc<LinkCounters>,
}

impl std::fmt::Debug for GigECamera {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GigECamera")
            .field("addr", &self.cfg.addr)
            .field("connected", &self.is_connected())
            .field(
                "model",
                &self
                    .connection
                    .as_ref()
                    .map(|c| c.info.model.as_str())
                    .unwrap_or(""),
            )
            .finish()
    }
}

impl GigECamera {
    /// A disconnected camera targeting `ip:3956`. No I/O, infallible.
    pub fn new(ip: impl Into<IpAddr>) -> Self {
        Self::with_config(GigeConfig::new(ip))
    }

    /// A disconnected camera with full configuration. No I/O, infallible.
    pub fn with_config(cfg: GigeConfig) -> Self {
        Self {
            cfg,
            connection: None,
            telemetry: None,
            link: Arc::new(LinkCounters::default()),
        }
    }

    /// Install a telemetry sink observing every GVCP datagram on the control
    /// channel. Takes effect on the next [`connect`](Self::connect); the live
    /// connection keeps the sink it was established with. Stream channels
    /// carry their own sink — see
    /// [`open_stream_with_telemetry`](Self::open_stream_with_telemetry).
    pub fn set_telemetry<S: TelemetrySink<ControlTx, ControlRx>>(&mut self, telemetry: S) {
        self.telemetry = Some(Arc::new(telemetry));
    }

    pub fn config(&self) -> &GigeConfig {
        &self.cfg
    }

    /// Retarget or retune; takes effect on the next [`connect`](Self::connect).
    pub fn config_mut(&mut self) -> &mut GigeConfig {
        &mut self.cfg
    }

    /// Establish the control link: bind, take device control (CCP), write
    /// the heartbeat timeout, and read capabilities and identity. Blocking;
    /// a no-op when already connected. A previous dead connection is torn
    /// down first, so this is also the reconnect path.
    pub fn connect(&mut self) -> Result<()> {
        if let Some(conn) = &self.connection {
            if conn.thread.is_alive() {
                return Ok(());
            }
            // Dropping joins the dead worker and frees per-connection state.
            self.connection = None;
        }
        let conn = establish(self.cfg.clone(), self.telemetry.clone(), self.link.clone())?;
        tracing::debug!(
            addr = %conn.device_addr,
            model = %conn.info.model,
            serial = %conn.info.serial,
            "connected"
        );
        self.connection = Some(conn);
        Ok(())
    }

    /// Stop the worker, releasing device control, and drop all
    /// per-connection state. Blocks up to `deadline` for the release write
    /// to go out; [`connect`](Self::connect) redials afterwards.
    pub fn disconnect(&mut self, deadline: Duration) {
        let Some(conn) = self.connection.take() else {
            return;
        };
        tracing::debug!(addr = %conn.device_addr, "disconnecting");
        if conn.port.send(ToWorker::Shutdown).is_ok() {
            conn.thread.wait_exited(deadline);
        }
        conn.thread.request_stop();
        // Dropping `conn` joins the worker.
    }

    pub fn is_connected(&self) -> bool {
        self.connection
            .as_ref()
            .is_some_and(|c| c.thread.is_alive())
    }

    fn conn(&self) -> Result<&Connection> {
        match &self.connection {
            None => Err(CameraError::Disconnected),
            Some(c) if !c.thread.is_alive() => Err(if c.shared.control_lost() {
                CameraError::ControlLost
            } else {
                CameraError::Disconnected
            }),
            Some(c) => Ok(c),
        }
    }

    fn conn_mut(&mut self) -> Result<&mut Connection> {
        self.conn()?;
        match &mut self.connection {
            Some(c) => Ok(c),
            None => Err(CameraError::Disconnected),
        }
    }

    pub fn read_register(&self, addr: u32) -> Result<ResponseHandle<u32>> {
        Ok(self.conn()?.port.read_register(addr))
    }

    /// Read several registers in one transaction.
    pub fn read_registers(&self, addrs: Vec<u32>) -> Result<ResponseHandle<Vec<u32>>> {
        Ok(self.conn()?.port.read_registers(addrs))
    }

    pub fn write_register(&self, addr: u32, value: u32) -> Result<ResponseHandle<()>> {
        Ok(self.conn()?.port.write_register(addr, value))
    }

    /// Write several registers in one transaction.
    pub fn write_registers(&self, pairs: Vec<(u32, u32)>) -> Result<ResponseHandle<()>> {
        Ok(self.conn()?.port.write_registers(pairs))
    }

    /// Read `len` bytes of device memory, transparently split into GVCP-sized
    /// chunks. `addr` must be 4-byte aligned.
    pub fn read_memory(&self, addr: u32, len: u32) -> Result<ResponseHandle<Vec<u8>>> {
        Ok(self.conn()?.port.read_memory(addr, len))
    }

    /// Write device memory, transparently split into GVCP-sized chunks.
    /// `addr` and `data.len()` must be 4-byte aligned.
    pub fn write_memory(&self, addr: u32, data: Vec<u8>) -> Result<ResponseHandle<()>> {
        Ok(self.conn()?.port.write_memory(addr, data))
    }

    /// Identity and addressing read from the device at connect.
    pub fn device_info(&self) -> Result<&DeviceInfo> {
        Ok(&self.conn()?.info)
    }

    /// The GVCP capability register (0x0934) read at connect; see the
    /// `bootstrap::CAP_*` bits.
    pub fn capabilities(&self) -> Result<u32> {
        Ok(self.conn()?.capabilities)
    }

    /// Subscribe to device-initiated events. Each call returns an independent
    /// buffered channel. Call [`enable_events`](Self::enable_events) to point
    /// the device's message channel at this host.
    pub fn events(&self) -> Result<EventChannel> {
        let conn = self.conn()?;
        let (tx, rx) = flume::bounded(self.cfg.event_capacity);
        conn.port.send(ToWorker::SubscribeEvents(tx))?;
        Ok(EventChannel { rx })
    }

    /// Open the device's message channel towards the control socket, so
    /// EVENT/EVENTDATA commands arrive on [`events`](Self::events) channels.
    pub fn enable_events(&self) -> Result<()> {
        let conn = self.conn()?;
        if conn.capabilities & bootstrap::CAP_EVENT == 0 {
            return Err(CameraError::Unsupported("message channel events"));
        }
        let IpAddr::V4(host_v4) = advertised_host_ip(conn)? else {
            return Err(CameraError::Unsupported(
                "IPv6 message channel destinations",
            ));
        };
        for (addr, value) in [
            (bootstrap::MESSAGE_CHANNEL_DEST_ADDRESS, u32::from(host_v4)),
            (bootstrap::MESSAGE_CHANNEL_TRANSMISSION_TIMEOUT, 1000),
            (bootstrap::MESSAGE_CHANNEL_RETRY_COUNT, 3),
            (
                bootstrap::MESSAGE_CHANNEL_PORT,
                u32::from(conn.local_addr.port()),
            ),
        ] {
            conn.port
                .write_register(addr, value)
                .wait_timeout(conn.port.budget())
                .map_err(unwrap_arc)?;
        }
        Ok(())
    }

    /// Close the message channel (MCP := 0).
    pub fn disable_events(&self) -> Result<()> {
        let conn = self.conn()?;
        conn.port
            .write_register(bootstrap::MESSAGE_CHANNEL_PORT, 0)
            .wait_timeout(conn.port.budget())
            .map_err(unwrap_arc)?;
        Ok(())
    }

    /// Control-channel counters of the current connection, if any.
    pub fn stats(&self) -> Option<LinkStats> {
        self.connection.as_ref().map(|c| *c.shared.stats.lock())
    }

    /// Link-health counters of this camera, cumulative across connections
    /// and stream channels.
    pub fn link_stats(&self) -> HealthStats {
        self.link.snapshot()
    }

    /// What [`GigeConfig::thread`] and [`GigeConfig::control_socket`] came
    /// to on the current connection, if any.
    pub fn tuning_report(&self) -> Option<&TuningReport> {
        self.connection.as_ref().map(|c| &c.tuning)
    }

    /// Open a GVSP stream channel: bind a receive socket, point the device's
    /// SCDA/SCP at it, settle the packet size (negotiating it when
    /// configured `Auto`), and start the reassembly worker.
    ///
    /// The device only transmits once acquisition is started (the
    /// `AcquisitionStart` feature, or
    /// [`GenICamera::start_acquisition`](crate::GenICamera)).
    pub fn open_stream(&self, cfg: StreamConfig) -> Result<StreamChannel> {
        self.open_stream_inner(cfg, None)
    }

    /// Like [`open_stream`](Self::open_stream), with a telemetry sink
    /// observing every GVSP datagram the channel receives and every resend
    /// request it sends.
    ///
    /// The sink is called once per datagram on the receive thread — tens of
    /// thousands of times a second on a fast link — and each call materializes
    /// an owned copy of the packet body. Keep the implementation to a queue
    /// push, and do the real work elsewhere.
    pub fn open_stream_with_telemetry<S: TelemetrySink<GvcpCmd, GvspPacket>>(
        &self,
        cfg: StreamConfig,
        telemetry: S,
    ) -> Result<StreamChannel> {
        self.open_stream_inner(cfg, Some(Arc::new(telemetry)))
    }

    fn open_stream_inner(
        &self,
        cfg: StreamConfig,
        telemetry: Option<StreamTelemetry>,
    ) -> Result<StreamChannel> {
        let payload_size = cfg
            .payload_size
            .filter(|&n| n > 0)
            .ok_or_else(|| CameraError::Protocol("payload_size must be set".into()))?;
        tuning::check_thread(tuning::ThreadRole::Stream, &cfg.thread)?;
        tuning::check_socket(SocketRole::UdpStreamRx, &cfg.stream_socket)?;
        let conn = self.conn()?;
        let port = &conn.port;
        let budget = port.budget();
        let base = cfg.channel_base();

        let local = match cfg.local_addr {
            Some(a) => a,
            None => SocketAddr::new(advertised_host_ip(conn)?, 0),
        };
        let (socket, socket_report) =
            tuning::bind_udp(SocketRole::UdpStreamRx, local, &cfg.stream_socket_options())
                .map_err(std::io::Error::from)?;
        let bound = socket.local_addr()?;
        let IpAddr::V4(host_v4) = bound.ip() else {
            return Err(CameraError::Unsupported("IPv6 stream destinations"));
        };
        if host_v4.is_unspecified() {
            tracing::debug!(
                local = %bound,
                "stream host IP unresolved; advertising SCDA=0 (device streams to the GVCP requester)"
            );
        }

        port.write_register(
            bootstrap::STREAM_CHANNEL_DEST_ADDRESS + base,
            u32::from(host_v4),
        )
        .wait_timeout(budget)
        .map_err(unwrap_arc)?;
        port.write_register(
            bootstrap::STREAM_CHANNEL_PORT + base,
            u32::from(bound.port()),
        )
        .wait_timeout(budget)
        .map_err(unwrap_arc)?;

        let open = move || -> Result<StreamChannel> {
            let scps_addr = bootstrap::STREAM_CHANNEL_PACKET_SIZE + base;
            let packet_size = match cfg.packet_size {
                crate::gige::stream::PacketSize::Fixed(n) => {
                    port.write_register(scps_addr, u32::from(n))
                        .wait_timeout(budget)
                        .map_err(unwrap_arc)?;
                    n
                }
                crate::gige::stream::PacketSize::Auto => {
                    negotiate_packet_size(port, conn.device_addr.ip(), &socket, scps_addr)?
                }
            };
            if let Some(delay) = cfg.packet_delay {
                port.write_register(bootstrap::STREAM_CHANNEL_PACKET_DELAY + base, delay)
                    .wait_timeout(budget)
                    .map_err(unwrap_arc)?;
            }

            let tick_frequency = port
                .read_registers(vec![
                    bootstrap::TIMESTAMP_TICK_FREQUENCY_HIGH,
                    bootstrap::TIMESTAMP_TICK_FREQUENCY_LOW,
                ])
                .wait_timeout(budget)
                .map(|v| (u64::from(v[0]) << 32) | u64::from(v[1]))
                .unwrap_or(0);

            let resend_enabled = cfg.resend == crate::gige::stream::ResendPolicy::Always
                && conn.capabilities & bootstrap::CAP_PACKET_RESEND != 0;

            let shared = Arc::new(StreamShared {
                stats: Mutex::new(Default::default()),
                link: self.link.clone(),
            });
            let (to_worker, rx) = flume::unbounded();
            let channel = cfg.channel;
            let (thread, thread_report) = crate::gige::stream::runner::spawn(
                socket,
                crate::gige::stream::runner::LinkParams {
                    device_gvcp_addr: conn.device_addr,
                    scps_packet_size: packet_size,
                    payload_size,
                    resend_enabled,
                    tick_frequency,
                },
                rx,
                shared.clone(),
                cfg,
                telemetry,
            )?;

            tracing::debug!(channel, local = %bound, packet_size, "stream channel opened");
            Ok(StreamChannel {
                to_worker,
                thread,
                shared,
                control: port.clone(),
                channel_base: base,
                packet_size,
                local_addr: bound,
                tuning: TuningReport {
                    thread: thread_report,
                    socket: socket_report.summary(),
                },
            })
        };
        open().inspect_err(|_| {
            let _ = port
                .write_register(bootstrap::STREAM_CHANNEL_PORT + base, 0)
                .wait_timeout(budget);
        })
    }

    /// The device description XML, fetched (and unzipped) on first call,
    /// then cached for the lifetime of the connection. Tries URL register 0,
    /// falls back to URL register 1.
    pub fn genicam_xml(&mut self) -> Result<Arc<[u8]>> {
        let conn = self.conn_mut()?;
        if let Some(xml) = &conn.genicam_xml {
            return Ok(xml.clone());
        }
        let mut last_err = CameraError::Protocol("no GenICam URL".into());
        for url_addr in [bootstrap::XML_URL_0, bootstrap::XML_URL_1] {
            match fetch_genicam_xml(&conn.port, url_addr) {
                Ok(xml) => {
                    conn.genicam_xml = Some(xml.clone());
                    return Ok(xml);
                }
                Err(e) => {
                    tracing::debug!("GenICam URL at {url_addr:#x} failed: {e}");
                    last_err = e;
                }
            }
        }
        Err(last_err)
    }

    /// Parse and cache the GenICam node graph for this connection.
    pub(crate) fn ensure_genicam(&mut self) -> crate::error::GenicamResult<()> {
        if self.conn()?.genicam.is_some() {
            return Ok(());
        }
        let xml = self.genicam_xml()?;
        let text = String::from_utf8_lossy(&xml);
        let graph = crate::genicam::parse_xml(&text)?;
        tracing::debug!("GenICam feature model loaded");
        self.conn_mut()?.genicam = Some(graph);
        Ok(())
    }

    /// The node graph and the device port to evaluate it against. The
    /// disjoint borrows are what let feature access take a true `&mut`
    /// graph while register IO goes through the port.
    pub(crate) fn genicam_parts(
        &mut self,
    ) -> crate::error::GenicamResult<(&mut crate::genicam::Genicam, &ControlPort)> {
        let conn = self.conn_mut()?;
        let Connection { genicam, port, .. } = conn;
        match genicam {
            Some(graph) => Ok((graph, port)),
            None => Err(crate::error::GenicamError::Xml(
                "feature model not loaded".into(),
            )),
        }
    }

    pub(crate) fn genicam_graph(&self) -> crate::error::GenicamResult<&crate::genicam::Genicam> {
        self.conn()?
            .genicam
            .as_ref()
            .ok_or_else(|| crate::error::GenicamError::Xml("feature model not loaded".into()))
    }

    pub(crate) fn genicam_ref(&self) -> Option<&crate::genicam::Genicam> {
        self.connection.as_ref()?.genicam.as_ref()
    }
}

/// The host IP to advertise to the device for a return channel (GVSP stream
/// or message channel). Prefers the control socket's bound IP — it provably
/// reaches the device — then fast-talker's `nic::source_for`: the address a
/// real kernel picks for the outbound route, or where connecting leaves it
/// unspecified, the host's address on the device's subnet. On a host with
/// neither (only wildcard binds, e.g. a virtual network shim) the caller
/// advertises an address of 0 and relies on the device streaming back to
/// the GVCP requester (see `GigeDevice::stream_dest`).
fn advertised_host_ip(conn: &Connection) -> Result<IpAddr> {
    if !conn.local_addr.ip().is_unspecified() {
        return Ok(conn.local_addr.ip());
    }
    match fast_talker::nic::source_for(conn.device_addr.ip()) {
        Err(e) if e.kind() == std::io::ErrorKind::AddrNotAvailable => {
            Ok(Ipv4Addr::UNSPECIFIED.into())
        }
        found => Ok(found?),
    }
}

/// Dial and bootstrap one connection. On any failure the worker is torn
/// down (joined, control released) by `ThreadHandle`'s drop before the
/// error propagates — nothing leaks out of a half-built connection.
fn establish(
    cfg: GigeConfig,
    telemetry: Option<ControlTelemetry>,
    link: Arc<LinkCounters>,
) -> Result<Connection> {
    let shared = Arc::new(Shared::new(link));
    let (to_worker, rx) = flume::unbounded();
    let (thread, local_addr, tuning) = runner::spawn(rx, shared.clone(), cfg.clone(), telemetry)?;
    let port = ControlPort {
        to_worker,
        thread: thread.to_pass_in(),
        budget: cfg.transaction_budget(),
    };
    let budget = port.budget();

    let ccp = bootstrap::CCP_CONTROL
        | if cfg.exclusive {
            bootstrap::CCP_EXCLUSIVE
        } else {
            0
        };
    port.write_register(bootstrap::CONTROL_CHANNEL_PRIVILEGE, ccp)
        .wait_timeout(budget)
        .map_err(|e| match &*e {
            CameraError::Nak { status, .. }
                if *status == GvcpStatus::ACCESS_DENIED || *status == GvcpStatus::WRITE_PROTECT =>
            {
                CameraError::ControlDenied
            }
            CameraError::Timeout => CameraError::ConnectTimeout,
            _ => unwrap_arc(e),
        })?;

    port.write_register(bootstrap::HEARTBEAT_TIMEOUT, cfg.heartbeat_timeout_ms)
        .wait_timeout(budget)
        .map_err(unwrap_arc)?;

    let capabilities = port
        .read_register(bootstrap::GVCP_CAPABILITY)
        .wait_timeout(budget)
        .map_err(unwrap_arc)?;
    shared.concatenation.store(
        capabilities & bootstrap::CAP_CONCATENATION != 0,
        Ordering::Relaxed,
    );

    let info = fetch_device_info(&port)?;

    Ok(Connection {
        port,
        thread,
        shared,
        device_addr: cfg.addr,
        local_addr,
        info,
        capabilities,
        genicam_xml: None,
        genicam: None,
        tuning,
    })
}

/// Assemble the device identity from individual register and string reads.
/// A single bulk read of the description block would be one transaction, but
/// real devices commonly reject READMEM spanning the reserved gaps in it.
fn fetch_device_info(port: &ControlPort) -> Result<DeviceInfo> {
    let budget = port.budget();
    let regs = port
        .read_registers(vec![
            bootstrap::VERSION,
            bootstrap::DEVICE_MODE,
            bootstrap::DEVICE_MAC_HIGH,
            bootstrap::DEVICE_MAC_LOW,
            bootstrap::SUPPORTED_IP_CONFIG,
            bootstrap::CURRENT_IP_CONFIG,
            bootstrap::CURRENT_IP_ADDRESS,
            bootstrap::CURRENT_SUBNET_MASK,
            bootstrap::CURRENT_GATEWAY,
        ])
        .wait_timeout(budget)
        .map_err(unwrap_arc)?;
    let [
        version,
        device_mode,
        mac_high,
        mac_low,
        supported_ip_config,
        current_ip_config,
        ip,
        mask,
        gateway,
    ] = regs[..]
    else {
        return Err(CameraError::Protocol(
            "short bootstrap register read".into(),
        ));
    };

    let string_field = |addr: u32, size: usize| -> Result<String> {
        match port.read_memory(addr, size as u32).wait_timeout(budget) {
            Ok(raw) => {
                let end = raw.iter().position(|&b| b == 0).unwrap_or(raw.len());
                Ok(String::from_utf8_lossy(&raw[..end]).into_owned())
            }
            // Optional fields on some devices; identity is still usable.
            Err(e) if matches!(&*e, CameraError::Nak { .. }) => {
                tracing::trace!("string register {addr:#06x} unreadable: {e}");
                Ok(String::new())
            }
            Err(e) => Err(unwrap_arc(e)),
        }
    };

    let mut mac = [0u8; 6];
    mac[..2].copy_from_slice(&mac_high.to_be_bytes()[2..]);
    mac[2..].copy_from_slice(&mac_low.to_be_bytes());

    Ok(DeviceInfo {
        spec_version: ((version >> 16) as u16, version as u16),
        device_mode,
        mac,
        supported_ip_config,
        current_ip_config,
        ip: ip.into(),
        subnet_mask: mask.into(),
        gateway: gateway.into(),
        manufacturer: string_field(
            bootstrap::MANUFACTURER_NAME,
            bootstrap::MANUFACTURER_NAME_SIZE,
        )?,
        model: string_field(bootstrap::MODEL_NAME, bootstrap::MODEL_NAME_SIZE)?,
        device_version: string_field(bootstrap::DEVICE_VERSION, bootstrap::DEVICE_VERSION_SIZE)?,
        manufacturer_info: string_field(
            bootstrap::MANUFACTURER_INFO,
            bootstrap::MANUFACTURER_INFO_SIZE,
        )?,
        serial: string_field(bootstrap::SERIAL_NUMBER, bootstrap::SERIAL_NUMBER_SIZE)?,
        user_defined_name: string_field(
            bootstrap::USER_DEFINED_NAME,
            bootstrap::USER_DEFINED_NAME_SIZE,
        )?,
    })
}

/// Largest device-hosted GenICam XML (or zip of one) fetched; real ones are
/// a few hundred KiB.
const MAX_XML_SIZE: usize = 64 << 20;

fn fetch_genicam_xml(port: &ControlPort, url_addr: u32) -> Result<Arc<[u8]>> {
    let budget = port.budget();
    let raw = port
        .read_memory(url_addr, bootstrap::XML_URL_SIZE as u32)
        .wait_timeout(budget * 2)
        .map_err(unwrap_arc)?;
    let end = raw.iter().position(|&b| b == 0).unwrap_or(raw.len());
    let url_str = String::from_utf8_lossy(&raw[..end]);
    let url = crate::genicam::XmlUrl::parse(&url_str).map_err(CameraError::Protocol)?;

    let data = match &url {
        crate::genicam::XmlUrl::Local { address, size, .. } => {
            let address = u32::try_from(*address)
                .map_err(|_| CameraError::Protocol("XML address beyond 32 bit".into()))?;
            let size = u32::try_from(*size)
                .ok()
                .filter(|&s| s as usize <= MAX_XML_SIZE)
                .ok_or_else(|| CameraError::Protocol(format!("XML size {size} out of range")))?;
            let budget = budget * (size / 512 + 2);
            port.read_memory(address, size)
                .wait_timeout(budget)
                .map_err(unwrap_arc)?
        }
        crate::genicam::XmlUrl::File(path) => std::fs::read(path)?,
        crate::genicam::XmlUrl::Http(_) => {
            return Err(CameraError::Unsupported("http-hosted GenICam XML"));
        }
    };
    let data = if url.is_zip() {
        crate::genicam::zip::extract_first_file(&data).map_err(CameraError::Protocol)?
    } else {
        data
    };
    Ok(Arc::from(data.into_boxed_slice()))
}

/// Fire-test bisection of the SCPS packet size: write a candidate size with the
/// fire-test and do-not-fragment bits and watch for the device's test
/// packet on the stream socket. Devices may align or cap the size they
/// actually use (e.g. 16-byte alignment), so whatever size the test packet
/// *arrives* at is taken as the verified value — the probe only decides the
/// search direction.
fn negotiate_packet_size(
    port: &ControlPort,
    device_ip: IpAddr,
    socket: &std::net::UdpSocket,
    scps_addr: u32,
) -> Result<u16> {
    // Probes are 16-aligned: devices round requests down to their own
    // increment (commonly 4, sometimes 16) and some only answer the fire
    // test for sizes they support exactly. 16 is a multiple of every
    // increment seen in the wild.
    const INC: u16 = 16;
    const MIN: u16 = 560;
    const MAX: u16 = 9152;

    let budget = port.budget();
    socket
        .set_read_timeout(Some(Duration::from_millis(25)))
        .ok();
    let mut buf = vec![0u8; 0x10000];
    // Returns the SCPS-equivalent size of the test packet the device
    // managed to deliver, if any.
    let mut probe = |size: u16| -> Option<u16> {
        let value =
            u32::from(size) | bootstrap::SCPS_FIRE_TEST_PACKET | bootstrap::SCPS_DO_NOT_FRAGMENT;
        port.write_register(scps_addr, value)
            .wait_timeout(budget)
            .ok()?;
        let mut achieved = None;
        for _ in 0..3 {
            match socket.recv_from(&mut buf) {
                Ok((n, src)) if src.ip() == device_ip => {
                    let delivered = (n + gvsp::PACKET_UDP_OVERHEAD) as u16;
                    if delivered <= size {
                        achieved = achieved.max(Some(delivered));
                        if delivered == size {
                            break;
                        }
                    }
                    // Oversized replies are stale probes; keep draining.
                }
                Ok(_) => {}
                Err(_) => {}
            }
        }
        achieved
    };

    let mut best = 0u16;
    let size = if let Some(a) = probe(MAX) {
        a
    } else if let Some(mut good) = [1488u16, 1008, MIN].into_iter().find(|&c| match probe(c) {
        Some(a) => {
            best = best.max(a);
            true
        }
        None => false,
    }) {
        let mut bad = MAX;
        while bad - good > INC {
            let mid = good + (bad - good) / 2 / INC * INC;
            match probe(mid) {
                Some(a) => {
                    best = best.max(a);
                    good = mid;
                }
                None => bad = mid,
            }
        }
        best
    } else {
        // Device never produced a test packet — it likely doesn't implement
        // the mechanism. Fall back without probing further.
        tracing::warn!("packet size fire-test unsupported, falling back to 1500");
        1500
    };
    let size = size.max(MIN);

    port.write_register(scps_addr, u32::from(size))
        .wait_timeout(budget)
        .map_err(unwrap_arc)?;
    // A test packet can land after its probe stopped listening; drain such
    // residue so the stream worker doesn't mistake it for frame data.
    socket.set_read_timeout(Some(Duration::from_millis(5))).ok();
    while socket.recv_from(&mut buf).is_ok() {}
    tracing::debug!("negotiated stream packet size {size}");
    Ok(size)
}