mx-remote 5.1.0

Client library for Pulse-Eight MatrixOS devices over UDP multicast/broadcast
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
// Author: Lars Op den Kamp (lars@opdenkamp-it.nl)
// Copyright (c) 2026 Op den Kamp IT Solutions

//! A discovered device and the bays it owns.

use std::collections::BTreeMap;
use std::net::Ipv4Addr;
use std::time::{Duration, Instant};

use crate::event::Event;
use crate::types::{
    AmpDolbySettings, AudioChangeSource, AudioEndpoints, AudioLink, DeviceStatus,
    DeviceV2ipDetails, DeviceV2ipSink, FirmwareVersion, MultiviewerStatus, NetworkPortStatus,
    RcSettings, TopologyEntry, V2ipDeviceSettings, V2ipDeviceStats, V2ipScalingSettings,
    V2ipStreamSources, V2ipTilingConfig, VolumeMuteStatus,
};
use crate::wire::{BayConfig, BayUid, DeviceFeature, DeviceUid, FirmwareType, V2ipFpgaFeature};

use super::bay::Bay;

/// How long a device below [`MODERN_PROTOCOL`] may stay silent before it
/// counts as offline.
const SILENCE_LIMIT: Duration = Duration::from_secs(120);

/// How long a device at [`MODERN_PROTOCOL`] or above may stay silent.
///
/// That version announces every few seconds, so silence becomes meaningful
/// long before two minutes of it have passed.
const SILENCE_LIMIT_MODERN: Duration = Duration::from_secs(15);

/// The version from which the shorter limit applies.
const MODERN_PROTOCOL: u16 = 0x20;

/// How long a device is given to finish describing itself.
///
/// Past this its link configuration stops being waited for, and it keeps being
/// asked for the rest. It never stands in for the bay configuration - see
/// [`Device::has_bays`].
pub(crate) const CONFIG_GRACE: Duration = Duration::from_secs(15);

/// What a device advertises about itself in its hello frame.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct HelloInfo {
    pub(crate) supported_protocol: u16,
    pub(crate) name: String,
    pub(crate) serial: String,
    pub(crate) version: String,
    pub(crate) features: DeviceFeature,
    pub(crate) address: Option<Ipv4Addr>,
}

impl HelloInfo {
    /// Compares what the device said about itself, ignoring where it said it
    /// from: an address change is a route change, not a configuration change.
    fn same_advertisement(&self, other: &Self) -> bool {
        self.supported_protocol == other.supported_protocol
            && self.name == other.name
            && self.serial == other.serial
            && self.version == other.version
            && self.features == other.features
    }
}

/// A device on the MX Remote network: a matrix, a OneIP unit or an amplifier.
#[derive(Clone, Debug)]
pub(crate) struct Device {
    pub(crate) uid: DeviceUid,
    pub(crate) hello: HelloInfo,
    pub(crate) bays: BTreeMap<u16, Bay>,
    pub(crate) temperatures: Vec<u8>,
    pub(crate) online: bool,
    pub(crate) have_config: bool,
    pub(crate) rebooting: bool,
    pub(crate) last_ping: Instant,
    /// When this device was first heard from.
    ///
    /// What [`CONFIG_GRACE`] is measured against, so it is the moment the
    /// device entered the registry and not the last hello: a device announces
    /// every few seconds, and a window restarted by each announcement is one
    /// that never closes.
    pub(crate) first_seen: Instant,
    /// Whether the device has reported its link configuration.
    pub(crate) link_config_received: bool,
    /// Whether the device has sent its primary bay configuration.
    ///
    /// Every unit sends that list whatever else it sends, so it is the one
    /// thing whose arrival can be required of any device.
    pub(crate) bay_config_received: bool,

    pub(crate) v2ip_sources: Option<Vec<V2ipStreamSources>>,
    /// Source records by their position in the sender's list.
    ///
    /// A paged list arrives as windows that can be reordered or lost, so the
    /// records are held by position and `v2ip_sources` is the run of them that
    /// has arrived from the start.
    pub(crate) v2ip_source_pages: BTreeMap<u16, V2ipStreamSources>,
    /// The source device behind each of this device's V2IP bays, by bay mode
    /// and number.
    ///
    /// Held here as well as on the bays because a device may send them before
    /// the bay configuration that creates those bays, and a bay that arrives
    /// later picks its mapping up from here.
    pub(crate) v2ip_bay_mappings: BTreeMap<(&'static str, u8), DeviceUid>,
    pub(crate) v2ip_details: Option<DeviceV2ipDetails>,
    pub(crate) v2ip_sink: Option<DeviceV2ipSink>,
    /// What the device's video processor supports, once it has reported it.
    ///
    /// `None` until a frame the device sent about itself carries a non-empty
    /// mask: a device leaves the field zero when configuring someone else, and
    /// reports zero of its own while its processor has yet to answer.
    pub(crate) v2ip_features: Option<V2ipFpgaFeature>,
    /// The device settings, once any has been reported.
    pub(crate) v2ip_settings: Option<V2ipDeviceSettings>,
    pub(crate) v2ip_stats: Option<V2ipDeviceStats>,
    pub(crate) setup_done: Option<bool>,
    pub(crate) installer_id: Option<u16>,
    pub(crate) tiling: Option<V2ipTilingConfig>,
    pub(crate) rc_settings: Option<RcSettings>,
    pub(crate) audio_select: Option<AudioChangeSource>,
    pub(crate) firmware: BTreeMap<FirmwareType, FirmwareVersion>,
    pub(crate) mesh_master: DeviceUid,
    pub(crate) network: BTreeMap<u16, NetworkPortStatus>,
    pub(crate) sys_status: Option<(u16, String)>,
    pub(crate) topology: Vec<TopologyEntry>,
    pub(crate) audio: Option<AudioEndpoints>,
    pub(crate) multiviewer: Option<MultiviewerStatus>,
    pub(crate) dolby_settings: Option<AmpDolbySettings>,
    /// The EDID the device presents on its input, as it last reported it.
    pub(crate) edid_input: Option<Vec<u8>>,
    /// The EDID of the display on the device's output, as it last reported it.
    pub(crate) edid_output: Option<Vec<u8>>,
}

impl Device {
    pub(crate) fn new(uid: DeviceUid, hello: HelloInfo, now: Instant) -> Self {
        Self {
            uid,
            hello,
            bays: BTreeMap::new(),
            temperatures: Vec::new(),
            online: true,
            have_config: false,
            rebooting: false,
            last_ping: now,
            first_seen: now,
            link_config_received: false,
            bay_config_received: false,
            v2ip_sources: None,
            v2ip_source_pages: BTreeMap::new(),
            v2ip_bay_mappings: BTreeMap::new(),
            v2ip_details: None,
            v2ip_sink: None,
            v2ip_features: None,
            v2ip_settings: None,
            v2ip_stats: None,
            setup_done: None,
            installer_id: None,
            tiling: None,
            rc_settings: None,
            audio_select: None,
            firmware: BTreeMap::new(),
            mesh_master: DeviceUid::ZERO,
            network: BTreeMap::new(),
            sys_status: None,
            topology: Vec::new(),
            audio: None,
            multiviewer: None,
            dolby_settings: None,
            edid_input: None,
            edid_output: None,
        }
    }

    /// The EDID the device last reported, for its output or for its input.
    pub(crate) fn edid(&self, output: bool) -> Option<&[u8]> {
        let stored = if output {
            &self.edid_output
        } else {
            &self.edid_input
        };
        stored.as_deref()
    }

    /// Stores an EDID the device reported.
    pub(crate) fn set_edid(&mut self, output: bool, data: Vec<u8>) {
        if output {
            self.edid_output = Some(data);
        } else {
            self.edid_input = Some(data);
        }
    }

    // ---- identity ----

    pub(crate) fn serial(&self) -> &str {
        if self.hello.serial.is_empty() {
            "Unknown"
        } else {
            &self.hello.serial
        }
    }

    pub(crate) fn name(&self) -> &str {
        if self.hello.name.is_empty() {
            "Unknown"
        } else if self.hello.name.trim().is_empty() {
            "<unnamed>"
        } else {
            &self.hello.name
        }
    }

    // ---- type checks ----

    pub(crate) fn is_v2ip(&self) -> bool {
        self.hello.features.has(DeviceFeature::V2IP_SINK)
            || self.hello.features.has(DeviceFeature::V2IP_SOURCE)
    }

    /// Whether a receiver would let this device write another device's
    /// configuration.
    ///
    /// Two bits, because the two kinds of writer announce themselves
    /// differently and neither implies the other.
    /// [`DeviceFeature::MANAGER`] belongs to external management applications -
    /// anything driving these devices that is not one of them, this library
    /// included - and no device firmware ever sets it on itself, so testing it
    /// alone would refuse every write a controller makes. A device that is
    /// controlling its mesh announces [`DeviceFeature::MESH_MASTER`] instead.
    ///
    /// The bit has a hole a caller has to close elsewhere: a device sets it
    /// only while it is both the controller and has bays mapped, so one
    /// promoted before it has any carries neither bit while still being its
    /// mesh's controller. What covers that window is the controller uid the
    /// devices in that mesh report, which is the subject's question rather
    /// than this device's.
    pub(crate) fn is_management(&self) -> bool {
        self.hello.features.has(DeviceFeature::MANAGER)
            || self.hello.features.has(DeviceFeature::MESH_MASTER)
    }

    /// Whether the device reports a V2IP sink, which is what carries the
    /// scaling settings.
    pub(crate) fn is_v2ip_sink(&self) -> bool {
        self.hello.features.has(DeviceFeature::V2IP_SINK)
    }

    pub(crate) fn is_video_matrix(&self) -> bool {
        self.hello.features.has(DeviceFeature::VIDEO_ROUTING)
    }

    pub(crate) fn is_audio_matrix(&self) -> bool {
        self.hello.features.has(DeviceFeature::AUDIO_ROUTING)
            && !self.hello.features.has(DeviceFeature::VIDEO_ROUTING)
    }

    pub(crate) fn is_amp(&self) -> bool {
        self.hello.features.has(DeviceFeature::VOLUME_CONTROL) && self.is_audio_matrix()
    }

    pub(crate) fn is_multiviewer(&self) -> bool {
        self.is_v2ip() && self.hello.features.has(DeviceFeature::MULTIVIEWER)
    }

    /// Whether this device's firmware initialises the configuration it
    /// broadcasts.
    ///
    /// Firmware without it builds some frames over uninitialised stack, so
    /// those fields carry noise rather than values: the scaling flags and,
    /// behind a spuriously set valid bit, the scaling mode and refresh; bay 0's
    /// addresses in the V2IP sources frame; and the padding beside the
    /// remote-control target.
    pub(crate) fn config_initialised(&self) -> bool {
        self.hello.features.has(DeviceFeature::CONFIG_INITIALISED)
    }

    pub(crate) fn has_local_source(&self) -> bool {
        self.first_input().is_some_and(Bay::is_local)
    }

    pub(crate) fn has_local_sink(&self) -> bool {
        self.first_output().is_some_and(Bay::is_local)
    }

    // ---- status ----

    pub(crate) fn is_online(&self, now: Instant) -> bool {
        let limit = if self.hello.supported_protocol >= MODERN_PROTOCOL {
            SILENCE_LIMIT_MODERN
        } else {
            SILENCE_LIMIT
        };
        now.saturating_duration_since(self.last_ping) < limit
    }

    pub(crate) fn is_rebooting(&self, now: Instant) -> bool {
        self.rebooting
            || (self.is_online(now) && self.hello.features.has(DeviceFeature::STATUS_REBOOT))
    }

    pub(crate) fn status(&self, now: Instant) -> DeviceStatus {
        if !self.is_online(now) {
            return DeviceStatus::Offline;
        }
        if self.is_rebooting(now) {
            return DeviceStatus::Rebooting;
        }
        if self.hello.features.has(DeviceFeature::BOOTING) {
            return DeviceStatus::Booting;
        }
        DeviceStatus::Online
    }

    // ---- bays ----

    pub(crate) fn bay(&self, port: u16) -> Option<&Bay> {
        self.bays.get(&port)
    }

    pub(crate) fn bay_mut(&mut self, port: u16) -> Option<&mut Bay> {
        self.bays.get_mut(&port)
    }

    pub(crate) fn bay_by_name(&self, name: &str) -> Option<&Bay> {
        self.bays.values().find(|b| b.port_name == name)
    }

    /// The input bay carrying the given user-assigned name.
    ///
    /// Inputs only, and hidden ones are skipped: this resolves the name a
    /// picker shows, and a picker does not offer what it does not list.
    pub(crate) fn bay_by_user_name(&self, name: &str) -> Option<&Bay> {
        self.inputs().find(|b| b.user_name() == name)
    }

    /// The bay the device's own API would call `mode` number `bay`.
    pub(crate) fn bay_by_mode_num(&self, mode: &str, bay: u8) -> Option<&Bay> {
        self.bays
            .values()
            .find(|b| b.mode_str() == mode && b.bay_num() == bay)
    }

    pub(crate) fn first_input(&self) -> Option<&Bay> {
        self.bays.values().find(|b| b.is_input())
    }

    pub(crate) fn first_output(&self) -> Option<&Bay> {
        self.bays.values().find(|b| b.is_output())
    }

    pub(crate) fn first_output_port(&self) -> Option<u16> {
        self.first_output().map(|b| b.port)
    }

    pub(crate) fn inputs(&self) -> impl Iterator<Item = &Bay> {
        self.bays
            .values()
            .filter(|b| b.is_input() && b.hidden != Some(true))
    }

    /// The streams the given source bay advertises.
    ///
    /// The V2IP sources frame lists one record per source bay in bay order. A
    /// receiver with no local source still sends a record for the bay it does
    /// not have, so its list is offset by one.
    pub(crate) fn v2ip_source_for(&self, bay: &Bay) -> Option<&V2ipStreamSources> {
        if !bay.is_input() || !self.is_v2ip() {
            return None;
        }
        let offset = u8::from(!self.has_local_source());
        let index = bay.bay_num().checked_sub(offset)?;
        self.v2ip_sources.as_ref()?.get(usize::from(index))
    }

    /// The cross-device identity a bay is linked by.
    ///
    /// A V2IP source is the same physical input wherever it appears, so it is
    /// keyed by the device producing the stream rather than by the port it
    /// happens to be mapped to. Everything else is keyed by its own port.
    pub(crate) fn link_key(&self, bay: &Bay) -> BayUid {
        if bay.is_v2ip_source() {
            let from_stream = self
                .v2ip_source_for(bay)
                .map(|s| s.uid)
                .filter(|uid| !uid.is_zero());
            let source = from_stream.or_else(|| Some(bay.v2ip_uid).filter(|u| !u.is_zero()));
            if let Some(source) = source {
                return BayUid::new(source, 0);
            }
        }
        bay.uid()
    }

    // ---- configuration completeness ----

    /// Whether the device's bay configuration has arrived.
    ///
    /// That it was sent at all is the whole of what can be established. A
    /// device pages its bays and nothing on the wire marks the last page -
    /// no count, no index, no terminating frame - and nothing it says about
    /// itself gives the number to expect, so counting what arrived can only be
    /// compared against a guess.
    ///
    /// For a V2IP device this is half the answer by itself: its bays include
    /// ones that live on other devices, and those arrive on a frame of their
    /// own that [`Self::configuration_complete`] requires separately.
    ///
    /// Unlike the link configuration, waiting for this never times out. A bay
    /// is what a caller names things after, and a name it assigns before this
    /// frame arrives is one it assigned to a placeholder - persisted, reused
    /// from then on, and undone only by editing whatever holds it. So a device
    /// that has not sent its bays is reported as undescribed for as long as
    /// that lasts.
    fn has_bays(&self) -> bool {
        self.bay_config_received
    }

    /// Whether the device has yet to report its link configuration.
    ///
    /// That it reported at all is the whole of what can be established, and no
    /// count of bays stands in for it. Two reasons, either enough on its own:
    ///
    /// A link record describes one of the sender's own ports. Most of a V2IP
    /// device's bays are proxies for streams that live on other devices, and
    /// those own no record - a 14-bay transceiver reports two, for its local
    /// input and its local output.
    ///
    /// A list longer than one payload is cut to what fits rather than
    /// continued. An 18-bay amplifier reports 17 records in one page and sends
    /// no second one, so even a device whose bays are all its own never
    /// accounts for the last of them.
    ///
    /// Waiting ends after [`CONFIG_GRACE`], and the device keeps being asked
    /// for the rest. Nothing a caller has already built needs revising when the
    /// records do arrive: a link is reported per bay and read on access, so an
    /// unreported one reads as no link, which is what a link coming up later
    /// looks like anyway. A withheld frame therefore costs a consumer that
    /// window rather than leaving the device permanently undescribed, a state
    /// nothing on the wire distinguishes from a device with no links to offer.
    fn needs_link_config(&self, now: Instant) -> bool {
        (self.is_amp() || self.is_video_matrix() || self.is_audio_matrix() || self.is_v2ip())
            && !self.link_config_received
            && now.saturating_duration_since(self.first_seen) <= CONFIG_GRACE
    }

    pub(crate) fn configuration_complete(&self, now: Instant) -> bool {
        self.has_bays()
            && !(self.is_v2ip() && self.v2ip_sources.is_none())
            && !self.needs_link_config(now)
    }

    /// Announces completion the first time every part has arrived.
    ///
    /// Also called on every pass of the probe loop, which is what gives the
    /// window in [`Self::needs_link_config`] a moment to expire in: no frame
    /// need arrive for a device to stop waiting for its links, so that pass is
    /// the only thing that can notice.
    pub(crate) fn check_config_complete(&mut self, now: Instant, ev: &mut Vec<Event>) {
        if self.have_config || !self.configuration_complete(now) {
            return;
        }
        self.have_config = true;
        ev.push(Event::DeviceConfigComplete { device: self.uid });
    }

    /// How many HDBaseT outputs this model has, by name.
    pub(crate) fn hdbt_outputs(&self) -> u8 {
        let name = self.hello.name.as_str();
        if name.starts_with("FF88") {
            8
        } else if name.starts_with("FF66") {
            6
        } else if name.starts_with("FF64")
            || name.starts_with("SP14")
            || matches!(name, "FFMB44" | "FFMS44" | "FFMG44")
        {
            4
        } else {
            0
        }
    }

    /// A friendly model name, from the hello name for matrices and from the
    /// bays it actually has for a OneIP unit.
    pub(crate) fn model_name(&self) -> &str {
        if self.is_v2ip() {
            return match (
                self.is_multiviewer(),
                self.has_local_source(),
                self.has_local_sink(),
            ) {
                (true, _, _) => "OneIP Multiviewer",
                (_, true, true) => "OneIP Transceiver",
                (_, true, false) => "OneIP Transmitter",
                _ => "OneIP Receiver",
            };
        }
        match self.hello.name.as_str() {
            "PROAMP8" => "ProAmp8",
            "PROAMPv2" => "ProAmp8 v2",
            "FFMB44" => "neo:4 Bronze",
            "FFMS44" => "neo:4 Silver",
            "FFMG44" => "neo:4 Gold",
            "FF88SA" | "FF88S" | "FF88T" => "neo:X",
            "FF88" => "neo:8",
            "FF88A" | "FF88A1" => "neo:8 Audio",
            "FF66SA" => "neo:6 X",
            "FF66A" | "FF66A1" => "neo:6 Audio",
            "FF64S" => "neo:6",
            "SP14" | "SP142" => "neo:4 Splitter",
            other => other,
        }
    }

    // ---- mutators ----

    pub(crate) fn apply_hello(&mut self, hello: HelloInfo, now: Instant, ev: &mut Vec<Event>) {
        self.last_ping = now;
        let changed = !self.hello.same_advertisement(&hello);
        self.hello = hello;
        self.rebooting = false;
        if changed {
            ev.push(Event::DeviceConfigChanged { device: self.uid });
        }
    }

    /// Merges one bay descriptor, resolving its routed source ports against
    /// the bays this device already has.
    pub(crate) fn apply_bay_config(&mut self, cfg: &BayConfig, now: Instant, ev: &mut Vec<Event>) {
        self.last_ping = now;
        let is_v2ip = self.is_v2ip();
        let video = self.routed_source(cfg.video_source);
        let audio = self.routed_source(cfg.audio_source);
        let is_new = !self.bays.contains_key(&u16::from(cfg.port));

        let bay = self
            .bays
            .entry(u16::from(cfg.port))
            .or_insert_with(|| Bay::new(self.uid, cfg));

        bay.features = cfg.features;
        bay.status_mask = cfg.status;
        bay.set_user_name(cfg.user_name.clone(), ev);
        if bay.mbay_id.is_none() {
            bay.mbay_id = Some(cfg.bay);
        }
        if let Some(uid) = self.v2ip_bay_mappings.get(&(bay.mode_str(), bay.bay_num())) {
            bay.v2ip_uid = *uid;
        }
        bay.apply_bay_status(cfg.status, ev);
        bay.signal_mode = cfg.signal_mode;
        // A V2IP source reporting a signal describes it in its own detailed
        // report, which carries the frame rate this field has no room for.
        if !cfg.status.has(crate::wire::BayStatus::SIGNAL_DETECTED) || !is_v2ip {
            bay.set_signal_type(cfg.signal_type.clone(), ev);
        }
        if bay.is_output() {
            bay.set_video_source(video, ev);
            bay.set_audio_source(audio, ev);
        } else {
            bay.set_rc_type(cfg.rc_type, ev);
            bay.set_edid_profile(cfg.edid_profile, ev);
        }

        if is_new {
            ev.push(Event::BayRegistered {
                bay: BayUid::new(self.uid, u16::from(cfg.port)),
            });
            // The audio tree names the bays it runs through, and may have
            // arrived before this one did.
            self.attach_audio_endpoints(ev);
            self.check_config_complete(now, ev);
        }
    }

    /// The identity of a local bay named by port number in a routing report.
    fn routed_source(&self, port: u8) -> Option<BayUid> {
        self.bays.get(&u16::from(port)).map(Bay::uid)
    }

    /// Notes that the device has sent its primary bay configuration.
    pub(crate) fn note_bay_config(&mut self, now: Instant, ev: &mut Vec<Event>) {
        if self.bay_config_received {
            return;
        }
        self.bay_config_received = true;
        self.check_config_complete(now, ev);
    }

    /// Notes that the device has reported its link configuration.
    pub(crate) fn note_link_config(&mut self, now: Instant, ev: &mut Vec<Event>) {
        if self.link_config_received {
            return;
        }
        self.link_config_received = true;
        self.check_config_complete(now, ev);
    }

    pub(crate) fn set_temperatures(&mut self, temperatures: Vec<u8>, ev: &mut Vec<Event>) {
        if self.temperatures == temperatures {
            return;
        }
        self.temperatures.clone_from(&temperatures);
        ev.push(Event::DeviceTemperatureChanged {
            device: self.uid,
            temperatures,
        });
    }

    /// Records that the device was heard from at `stamped`, and re-evaluates
    /// its liveness as of `now`.
    ///
    /// The two clocks differ whenever a datagram is handled later than it
    /// arrived. The frame's own time says when the device was last heard; only
    /// the current time says how long ago that was, so measuring the gap from
    /// the frame's time would make every device look freshly seen.
    pub(crate) fn touch(&mut self, stamped: Instant, now: Instant, ev: &mut Vec<Event>) {
        self.last_ping = stamped;
        self.check_online(now, ev);
    }

    pub(crate) fn check_online(&mut self, now: Instant, ev: &mut Vec<Event>) {
        let online = self.is_online(now);
        if online == self.online {
            return;
        }
        self.online = online;
        if !online {
            self.have_config = false;
        }
        ev.push(Event::DeviceOnlineChanged {
            device: self.uid,
            online,
        });
    }

    pub(crate) fn set_firmware_version(&mut self, version: FirmwareVersion, ev: &mut Vec<Event>) {
        if self.firmware.get(&version.firmware_type) == Some(&version) {
            return;
        }
        self.firmware.insert(version.firmware_type, version.clone());
        ev.push(Event::FirmwareVersionChanged {
            device: self.uid,
            version,
        });
    }

    pub(crate) fn set_system_status(&mut self, status: u16, message: String, ev: &mut Vec<Event>) {
        let current = (status, message);
        if self.sys_status.as_ref() == Some(&current) {
            return;
        }
        self.sys_status = Some(current.clone());
        ev.push(Event::SystemStatusChanged {
            device: self.uid,
            status: current.0,
            message: current.1,
        });
    }

    pub(crate) fn update_network_status(&mut self, status: NetworkPortStatus, ev: &mut Vec<Event>) {
        if self.network.get(&status.port) == Some(&status) {
            return;
        }
        self.network.insert(status.port, status.clone());
        ev.push(Event::NetworkStatusChanged {
            device: self.uid,
            status,
        });
    }

    pub(crate) fn set_v2ip_stats(&mut self, stats: V2ipDeviceStats, ev: &mut Vec<Event>) {
        self.v2ip_stats = Some(stats);
        ev.push(Event::V2ipStatsChanged {
            device: self.uid,
            stats,
        });
    }

    /// How many amplifier outputs the reported Dolby mode groups together.
    ///
    /// Zero unless the amplifier is in a Dolby mode, and the group is always
    /// the outputs numbered below the count: `mxr_amp_dolby_settings`
    /// spells its `dolby_config` as 0 standard, 1 three-zone, 2 four-zone.
    /// The bay feature bit does not describe the group - an output outside it
    /// can carry the bit and name the same Dolby input.
    fn dolby_zones(&self) -> u8 {
        match self.dolby_settings.map(|d| d.mode) {
            Some(1) => 3,
            Some(2) => 4,
            _ => 0,
        }
    }

    /// Applies a volume to a bay, and to the rest of its Dolby group.
    ///
    /// An amplifier reports one volume for a Dolby group, against its first
    /// output, because the group is driven as one. Every output in it holds
    /// that volume, so a caller reading any of them sees what the zone is set
    /// to rather than nothing at all.
    pub(crate) fn apply_bay_volume(
        &mut self,
        port: u16,
        volume: VolumeMuteStatus,
        ev: &mut Vec<Event>,
    ) {
        let Some(bay) = self.bay_mut(port) else {
            return;
        };
        bay.set_volume_status(volume, ev);

        let zones = self.dolby_zones();
        let leads_group = self
            .bay(port)
            .is_some_and(|b| b.is_output() && b.has_dolby() && b.bay_num() == 0);
        if zones == 0 || !self.is_amp() || !leads_group {
            return;
        }
        let group: Vec<u16> = self
            .bays
            .values()
            .filter(|b| b.is_output() && b.has_dolby() && (1..zones).contains(&b.bay_num()))
            .map(|b| b.port)
            .collect();
        for port in group {
            if let Some(bay) = self.bay_mut(port) {
                bay.set_volume_status(volume, ev);
            }
        }
    }

    pub(crate) fn set_dolby_settings(&mut self, settings: AmpDolbySettings, ev: &mut Vec<Event>) {
        if self.dolby_settings == Some(settings) {
            return;
        }
        self.dolby_settings = Some(settings);
        ev.push(Event::AmpDolbySettingsChanged {
            device: self.uid,
            settings,
        });
    }

    pub(crate) fn set_setup_completed(&mut self, completed: bool, ev: &mut Vec<Event>) {
        if self.setup_done == Some(completed) {
            return;
        }
        self.setup_done = Some(completed);
        ev.push(Event::SetupStatusChanged {
            device: self.uid,
            completed,
        });
    }

    pub(crate) fn set_installer_id(&mut self, installer_id: u16, ev: &mut Vec<Event>) {
        if self.installer_id == Some(installer_id) {
            return;
        }
        self.installer_id = Some(installer_id);
        ev.push(Event::InstallerIdChanged {
            device: self.uid,
            installer_id,
        });
    }

    pub(crate) fn set_tiling(&mut self, tiling: V2ipTilingConfig, ev: &mut Vec<Event>) {
        if self.tiling == Some(tiling) {
            return;
        }
        self.tiling = Some(tiling);
        ev.push(Event::TilingChanged {
            device: self.uid,
            tiling,
        });
    }

    pub(crate) fn set_rc_settings(&mut self, settings: RcSettings, ev: &mut Vec<Event>) {
        if self.rc_settings.as_ref() == Some(&settings) {
            return;
        }
        self.rc_settings = Some(settings.clone());
        ev.push(Event::RcSettingsChanged {
            device: self.uid,
            settings,
        });
    }

    pub(crate) fn set_audio_select_input(
        &mut self,
        change: AudioChangeSource,
        ev: &mut Vec<Event>,
    ) {
        if self.audio_select == Some(change) {
            return;
        }
        self.audio_select = Some(change);
        ev.push(Event::AudioSelectInput {
            device: self.uid,
            change,
        });
    }

    pub(crate) fn set_mesh_master(&mut self, master: DeviceUid, ev: &mut Vec<Event>) {
        if self.mesh_master == master {
            return;
        }
        self.mesh_master = master;
        ev.push(Event::MeshMasterChanged {
            device: self.uid,
            master,
        });
    }

    pub(crate) fn set_topology(&mut self, topology: Vec<TopologyEntry>, ev: &mut Vec<Event>) {
        if self.topology == topology {
            return;
        }
        self.topology.clone_from(&topology);
        ev.push(Event::TopologyChanged {
            device: self.uid,
            topology,
        });
    }

    /// Merges one frame of a device's source list into the list it belongs to.
    ///
    /// A list that fits one frame is the whole list and replaces what was held.
    /// A longer one arrives as pages, and a page is a window rather than the
    /// list: its records belong at `first + index` whatever order the pages
    /// arrive in, and it says nothing about the records it leaves out. Only a
    /// frame covering the whole list may shorten it.
    ///
    /// `total` is the sender's count at the moment that page was built rather
    /// than a promise about the set, so it decides only whether this frame is
    /// the whole list - it never sizes the result.
    pub(crate) fn merge_v2ip_sources(
        &mut self,
        first: usize,
        total: usize,
        page: &[V2ipStreamSources],
        ev: &mut Vec<Event>,
    ) {
        let whole = first == 0 && page.len() == total;
        if whole {
            self.v2ip_source_pages.clear();
        }
        for (index, source) in page.iter().enumerate() {
            let Ok(at) = u16::try_from(first + index) else {
                return;
            };
            self.v2ip_source_pages.insert(at, *source);
        }
        if whole {
            self.set_v2ip_sources(page.to_vec(), ev);
            return;
        }
        // A record's position is what maps it to a bay, so the list reported is
        // the run that has arrived from the start. A gap is where it stops,
        // never something to fill: a default in the middle would report a bay
        // as advertising no streams, which is a reading rather than an absence.
        let mut list = Vec::with_capacity(self.v2ip_source_pages.len());
        for (at, source) in &self.v2ip_source_pages {
            if usize::from(*at) != list.len() {
                break;
            }
            list.push(*source);
        }
        if list.is_empty() {
            return;
        }
        self.set_v2ip_sources(list, ev);
    }

    pub(crate) fn set_v2ip_sources(
        &mut self,
        sources: Vec<V2ipStreamSources>,
        ev: &mut Vec<Event>,
    ) {
        if self.v2ip_sources.as_ref() == Some(&sources) {
            return;
        }
        self.v2ip_sources = Some(sources.clone());
        ev.push(Event::V2ipSourcesChanged {
            device: self.uid,
            sources,
        });
    }

    /// Merges an encoder configuration report, which carries only the fields
    /// the sender had values for.
    pub(crate) fn set_v2ip_details(&mut self, details: DeviceV2ipDetails, ev: &mut Vec<Event>) {
        let merged = details.merge(self.v2ip_details);
        if self.v2ip_details == Some(merged) {
            return;
        }
        self.v2ip_details = Some(merged);
        ev.push(Event::V2ipDetailsChanged {
            device: self.uid,
            details: merged,
        });
    }

    /// The scaling block as last reported or written, all-zero before either.
    pub(crate) fn v2ip_scaling(&self) -> V2ipScalingSettings {
        self.v2ip_details.unwrap_or_default().scaling
    }

    /// Replaces the cached scaling block with the state a write will have left
    /// on the device.
    ///
    /// Separate from [`Device::set_v2ip_details`] because that folds a received
    /// frame on, and folding cannot express a cleared mode: a write clears one
    /// by sending the valid bit over a zero mode, while a device with no mode
    /// configured reports the valid bit clear. Only the second is a state a
    /// device broadcasts, so it is the one to cache.
    pub(crate) fn set_v2ip_scaling(&mut self, scaling: V2ipScalingSettings, ev: &mut Vec<Event>) {
        let mut details = self.v2ip_details.unwrap_or_default();
        if details.scaling == scaling {
            return;
        }
        details.scaling = scaling;
        self.v2ip_details = Some(details);
        ev.push(Event::V2ipDetailsChanged {
            device: self.uid,
            details,
        });
    }

    /// Records the processor's feature mask, which only ever gains bits.
    ///
    /// The caller passes a non-empty mask from a frame the device sent about
    /// itself; every other frame says nothing about the subject's processor and
    /// must leave what is cached alone.
    pub(crate) fn set_v2ip_features(&mut self, features: V2ipFpgaFeature, ev: &mut Vec<Event>) {
        if self.v2ip_features == Some(features) {
            return;
        }
        self.v2ip_features = Some(features);
        ev.push(Event::V2ipFeaturesChanged {
            device: self.uid,
            features,
        });
    }

    /// Folds a settings block onto the cached one.
    ///
    /// The caller has already limited a write about this device to what the
    /// device takes from one; a block that carries no setting leaves the cache
    /// as it was.
    pub(crate) fn merge_v2ip_settings(&mut self, frame: V2ipDeviceSettings, ev: &mut Vec<Event>) {
        if frame.valid.is_empty() {
            return;
        }
        let merged = frame.merge(self.v2ip_settings.unwrap_or_default());
        if self.v2ip_settings == Some(merged) {
            return;
        }
        self.v2ip_settings = Some(merged);
        ev.push(Event::V2ipDeviceSettingsChanged {
            device: self.uid,
            settings: merged,
        });
    }

    pub(crate) fn set_v2ip_sink(&mut self, sink: DeviceV2ipSink, ev: &mut Vec<Event>) {
        if self.v2ip_sink == Some(sink) {
            return;
        }
        self.v2ip_sink = Some(sink);
        ev.push(Event::V2ipSinkChanged {
            device: self.uid,
            sink,
        });
    }

    pub(crate) fn set_multiviewer_status(
        &mut self,
        status: MultiviewerStatus,
        ev: &mut Vec<Event>,
    ) {
        if self.multiviewer.as_ref() == Some(&status) {
            return;
        }
        self.multiviewer = Some(status.clone());
        ev.push(Event::MultiviewerStatusChanged {
            device: self.uid,
            status,
        });
    }

    /// Replaces the audio endpoint tree and reattaches the bays that carry it.
    ///
    /// A device re-sends the tree whenever any routing within it changes, so
    /// only a change to the tree's own shape is announced. The attachments are
    /// redone either way, because a bay discovered after the tree first
    /// arrived has nothing to attach it to until the tree comes round again.
    pub(crate) fn set_audio_endpoints(&mut self, endpoints: AudioEndpoints, ev: &mut Vec<Event>) {
        let same = self
            .audio
            .as_ref()
            .is_some_and(|current| current.same_tree(&endpoints));
        self.audio = Some(endpoints);
        self.attach_audio_endpoints(ev);
        if same {
            return;
        }
        if let Some(endpoints) = self.audio.clone() {
            ev.push(Event::AudioEndpointsChanged {
                device: self.uid,
                endpoints,
            });
        }
    }

    /// Attaches each audio endpoint to the bay that carries it.
    ///
    /// A OneIP unit has one input and one output, and its tree crosses them:
    /// the local input feeds the endpoint that leaves the box, so the input
    /// bay carries the tree's first output and the output bay its first input.
    /// An amplifier instead numbers its endpoints, inputs below ten and
    /// outputs from ten.
    fn attach_audio_endpoints(&mut self, ev: &mut Vec<Event>) {
        let Some(endpoints) = self.audio.clone() else {
            return;
        };
        let mut pairs: Vec<(u16, u8)> = Vec::new();
        if self.is_v2ip() && self.has_local_source() {
            let mut pair = |bay: Option<&Bay>, endpoint: Option<&crate::types::AudioEndpoint>| {
                if let (Some(bay), Some(endpoint)) = (bay, endpoint) {
                    pairs.push((bay.port, endpoint.id));
                }
            };
            pair(self.first_input(), endpoints.first_root_output());
            pair(self.first_output(), endpoints.first_root_input());
        } else if self.is_amp() {
            for ep in endpoints.list() {
                let (mode, number) = if ep.id < 10 {
                    ("Input", ep.id)
                } else {
                    ("Output", ep.id - 10)
                };
                if let Some(bay) = self.bay_by_mode_num(mode, number) {
                    pairs.push((bay.port, ep.id));
                }
            }
        }
        for (port, endpoint) in pairs {
            if let Some(bay) = self.bays.get_mut(&port) {
                bay.set_audio_endpoint(endpoint, ev);
            }
        }
    }

    pub(crate) fn apply_audio_links(&mut self, links: &[AudioLink]) {
        let Some(audio) = self.audio.as_mut() else {
            return;
        };
        for link in links {
            audio.apply_link(link);
        }
    }
}