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
// Author: Lars Op den Kamp (lars@opdenkamp-it.nl)
// Copyright (c) 2026 Op den Kamp IT Solutions

//! Handlers for the frames that report device and bay state.

use std::net::Ipv4Addr;

use crate::event::Event;
use crate::state::{Device, HelloInfo, State};
use crate::types::{
    BayMirrorStatus, ConnectStatus, DeviceV2ipDetails, DeviceV2ipSink, FirmwareVersion,
    HiddenStatus, MuteStatus, PowerStatus, StreamKind, TopologyEntry, V2ipDeviceSettings,
    V2ipDscpConfig, V2ipScalingSettings, V2ipStreamSource, V2ipStreamSources, V2ipTilingConfig,
    VolumeMuteStatus, SCALING_FLAGS_DEFINED, SCALING_FLAG_MATCH_SOURCE,
    SCALING_FLAG_OPTIONS2_VALID, SCALING_FLAG_SKIP_420, VOLUME_UNCHANGED,
};
use crate::wire::{
    op, parse_bay_config, BayStatus, BayUid, DeviceFeature, DeviceUid, FirmwareType, Frame,
    MxrSignalType, RcAction, RcKey, V2ipDeviceSetting, V2ipFpgaFeature, BAY_CONFIG_SIZE,
    FW_VERSION_LEN,
};

use super::Rx;

/// Payload length of a remote-control key or action frame with a one-byte bay
/// id, and of the one from protocol 6 that widened it to two.
///
/// The length is what tells the two apart, not the frame's stamp. These
/// opcodes' table entries were seeded after the widening had already happened
/// and were never raised for it, so both forms go out stamped 0x01 and the
/// stamp says nothing about which one arrived. A table entry is what a frame
/// is stamped with; it is not a record of when a layout changed.
const RC_NARROW_SIZE: usize = 3;
const RC_WIDE_SIZE: usize = 4;

/// Payload length of the superseded `AUDIO_SET_VOLUME` layout, which addresses
/// its target by serial and carries a one-byte bay. Anything longer is the
/// current layout, which addresses its target by uid and carries two bay bytes;
/// that one is 24 with its tail padding and readable from 21 without it.
const SET_VOLUME_LEGACY_SIZE: usize = 20;

/// The bay and the value a remote-control key or action frame carries.
fn rc_bay_and_value(f: &Frame) -> Option<(u16, u16)> {
    match f.payload().len() {
        RC_NARROW_SIZE => Some((u16::from(f.u8(0)?), f.u16(1)?)),
        n if n >= RC_WIDE_SIZE => Some((f.u16(0)?, f.u16(2)?)),
        _ => None,
    }
}

pub(super) fn hello(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let f = &rx.frame;
    let hello = HelloInfo {
        supported_protocol: f.u16(0).unwrap_or(0),
        name: f.str(2, 16).unwrap_or_default(),
        serial: f.str(18, 16).unwrap_or_default(),
        version: f.str(34, 16).unwrap_or_default(),
        features: DeviceFeature::from_bits(f.u32(50).unwrap_or(0)),
        address: rx.address,
    };
    state.apply_hello(rx.sender(), hello, rx.timestamp, ev);
}

/// Merges one page of bay descriptors into the device's bay list.
///
/// A device pages its bays across several frames, sizing each page against the
/// payload it can send and shrinking it further under memory pressure, so the
/// record count varies from frame to frame and no single frame holds the whole
/// list. Merge records rather than replacing the list, and never read the
/// record count as the device's bay count.
pub(super) fn bay_config(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let Some(device) = state.device_mut(rx.sender()) else {
        return;
    };
    let payload = rx.frame.payload();
    for record in payload.chunks_exact(BAY_CONFIG_SIZE) {
        if let Some(cfg) = parse_bay_config(record) {
            device.apply_bay_config(&cfg, rx.timestamp, ev);
        }
    }
    // The primary list, specifically. Every unit sends that one whatever else
    // it sends, so requiring it strands nothing, and the secondary list does
    // not stand in for it: a device that has sent only the secondary one has
    // not yet described itself.
    if rx.frame.opcode() == op::SYS_BAY_CONFIG {
        device.note_bay_config(rx.timestamp, ev);
    }
}

pub(super) fn connect_status(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let Some(port) = rx.frame.u8(0) else {
        return;
    };
    let status = if rx.frame.boolean(1) {
        ConnectStatus::Connected
    } else {
        ConnectStatus::Disconnected
    };
    if let Some(bay) = state.bay_mut(BayUid::new(rx.sender(), u16::from(port))) {
        bay.apply_connect_status(status, ev);
    }
}

pub(super) fn power_change(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let Some(port) = rx.frame.u8(0) else {
        return;
    };
    let power = if rx.frame.boolean(1) {
        PowerStatus::On
    } else {
        PowerStatus::Off
    };
    if let Some(bay) = state.bay_mut(BayUid::new(rx.sender(), u16::from(port))) {
        bay.set_power_status(power, ev);
    }
}

/// Applies a routing change: which source a sink is now showing and hearing.
///
/// `mxr_routing_change` is packed and every bay in it is an `mbay_port_id`, so
/// each is two bytes: sink at 0, selected at 2, video at 4, scrambled at 6 and
/// audio at 7. Reading them a byte wide puts "selected" in video and "video" in
/// audio, which agrees with the wire only while the selected input is the one
/// actually being shown.
pub(super) fn routing_change(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let f = &rx.frame;
    let Some(sink_port) = f.u16(0) else {
        return;
    };
    let sender = rx.sender();
    let Some(device) = state.device(sender) else {
        return;
    };
    if device.bay(sink_port).is_none() {
        return;
    }
    let resolve = |port: Option<u16>| {
        port.filter(|p| device.bay(*p).is_some())
            .map(|p| BayUid::new(sender, p))
    };
    let video = resolve(f.u16(4));
    let audio = resolve(f.u16(7));

    if let Some(bay) = state.bay_mut(BayUid::new(sender, sink_port)) {
        if let Some(video) = video {
            bay.set_video_source(Some(video), ev);
        }
        if let Some(audio) = audio {
            bay.set_audio_source(Some(audio), ev);
        }
    }
}

pub(super) fn rc_action(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let Some(device) = state.device(rx.sender()) else {
        return;
    };
    let Some((port, action)) = rc_bay_and_value(&rx.frame) else {
        return;
    };
    if device.bay(port).is_some() {
        ev.push(Event::ActionReceived {
            bay: BayUid::new(rx.sender(), port),
            action: RcAction::from_wire(action),
        });
    }
}

/// Reports a remote-control key press.
pub(super) fn rc_key(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let Some(device) = state.device(rx.sender()) else {
        return;
    };
    let Some((port, key)) = rc_bay_and_value(&rx.frame) else {
        return;
    };
    if device.bay(port).is_some() {
        ev.push(Event::KeyPressed {
            bay: BayUid::new(rx.sender(), port),
            key: RcKey::from_wire(key),
        });
    }
}

/// Applies an `AUDIO_SET_VOLUME` request: a volume per channel and a mute
/// bitmask, for the bay its payload names.
///
/// **The bay belongs to the device in the payload, not to the sender.** The two
/// differ for every such frame that does anything: a controller asking for a
/// volume owns no bay the request could be about, so reading the sender loses
/// the setting rather than misplacing it visibly. This matches the other
/// uid-addressed requests, `BAY_HIDE` and `V2IP_MANUAL_SRC_SWITCH`; the status
/// frames that do file under the sender are reports a device makes about
/// itself.
///
/// Two layouts, told apart by length alone. The superseded form names its
/// target by serial and carries a one-byte bay; anything longer is the current
/// form, which names it by uid and carries two. Both stamp the same version, so
/// there is no stamp to select on - unlike `NET_LINK_STATUS`, where a widened
/// field did raise one. The two cannot be confused for each other anyway: the
/// first sixteen bytes are a printable serial in one and a binary identifier in
/// the other.
pub(super) fn volume_set(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let f = &rx.frame;
    let (target, port, at) = match f.payload().len() {
        n if n > SET_VOLUME_LEGACY_SIZE => (rx.uid_or_zero(0), f.u16(16), 18),
        SET_VOLUME_LEGACY_SIZE => {
            let serial = f.str(0, 16).unwrap_or_default();
            let Some(device) = state.device_by_serial(&serial) else {
                return;
            };
            (device.uid, f.u8(16).map(u16::from), 17)
        }
        _ => return,
    };
    let Some(port) = port else {
        return;
    };
    // A volume above 100 is not a percentage, which drops the "leave this
    // alone" value along with anything else out of range. The mute byte has
    // no such range to fall outside of, so it is checked for that value
    // directly: read as a bitmask it would say both channels are muted, which
    // is the opposite of the "do not change" it means.
    let muted = f.u8(at + 2).filter(|m| *m != VOLUME_UNCHANGED);
    let volume = VolumeMuteStatus {
        volume_left: f.u8(at).filter(|v| *v <= 100),
        volume_right: f.u8(at + 1).filter(|v| *v <= 100),
        muted_left: muted.map(|m| MuteStatus::from_wire(m).left()),
        muted_right: muted.map(|m| MuteStatus::from_wire(m).right()),
    };
    if let Some(device) = state.device_mut(target) {
        device.apply_bay_volume(port, volume, ev);
    }
}

pub(super) fn temperature(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let f = &rx.frame;
    let Some(count) = f.u8(0) else {
        return;
    };
    let temperatures = (1..=usize::from(count)).filter_map(|i| f.u8(i)).collect();
    if let Some(device) = state.device_mut(rx.sender()) {
        device.set_temperatures(temperatures, ev);
    }
}

/// Width of one record in the V2IP sources frame.
const V2IP_SOURCE_RECORD: usize = 40;

/// The header a paged source list puts in front of its records: where in the
/// sender's list this page starts, how many records the whole list held when
/// the page was built, and four reserved bytes.
const V2IP_SOURCE_PAGE_HEADER: usize = 8;

pub(super) fn v2ip_sources(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let payload = rx.frame.payload();
    // A list that fits one frame is sent as bare records from the first byte. A
    // longer one is split into pages, each carrying a header that says where in
    // the sender's list its records begin. That header is not a whole record,
    // so the remainder is what tells the two forms apart - and a payload that
    // is neither is refused rather than read from byte zero, which would shift
    // every record by the header's width and report a full set of plausible
    // addresses belonging to no bay.
    let (first, total, body) = match payload.len() % V2IP_SOURCE_RECORD {
        0 => (0, payload.len() / V2IP_SOURCE_RECORD, payload),
        V2IP_SOURCE_PAGE_HEADER => {
            let Some(body) = payload.get(V2IP_SOURCE_PAGE_HEADER..) else {
                return;
            };
            (
                usize::from(u16_at(payload, 0)),
                usize::from(u16_at(payload, 2)),
                body,
            )
        }
        _ => return,
    };
    let sources: Vec<V2ipStreamSources> = body
        .chunks_exact(V2IP_SOURCE_RECORD)
        .map(|record| V2ipStreamSources {
            uid: uid_at(record, 0),
            video: stream_source(StreamKind::Video, record, 16),
            audio: stream_source(StreamKind::Audio, record, 24),
            anc: stream_source(StreamKind::Anc, record, 32),
            arc: None,
        })
        .collect();
    if let Some(device) = state.device_mut(rx.sender()) {
        device.merge_v2ip_sources(first, total, &sources, ev);
    }
}

/// Applies the source switch a mesh master broadcasts, which names the sink by
/// uid and the streams it is now subscribed to by group address.
pub(super) fn v2ip_source_switch(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let target = rx.uid_or_zero(0);
    let payload = rx.frame.payload();
    let Some(body) = payload.get(16..24) else {
        return;
    };
    let video = ipv4_at(body, 0);
    let audio = ipv4_at(body, 4);
    let Some(sink) = state
        .device(target)
        .and_then(|d| d.first_output_port())
        .map(|port| BayUid::new(target, port))
    else {
        return;
    };
    apply_stream_route(state, sink, video, audio, ev);
}

/// Applies a manual source switch, which carries the full stream triple and
/// optionally the audio format the sink should expect.
///
/// The frame is a route request addressed to the sink, and is applied to the
/// sink here rather than only announced as a request: every device on the mesh
/// writes an observed switch into its own record of the addressee, so leaving
/// the registry alone would make this client the only participant that does not
/// know where a sink was pointed. What the sink did about it is not
/// acknowledged - see `DeviceV2ipSink`.
pub(super) fn v2ip_manual_source_switch(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let target = rx.uid_or_zero(0);
    let payload = rx.frame.payload();
    if payload.len() < 38 {
        return;
    }
    let video = stream_source(StreamKind::Video, payload, 16);
    let audio = stream_source(StreamKind::Audio, payload, 24);
    let anc = stream_source(StreamKind::Anc, payload, 32);

    if let Some(sink) = state
        .device(target)
        .and_then(|d| d.first_output_port())
        .map(|port| BayUid::new(target, port))
    {
        apply_stream_route(state, sink, video.ip, audio.ip, ev);
    }

    let sink = DeviceV2ipSink {
        addresses: V2ipStreamSources {
            uid: DeviceUid::ZERO,
            video,
            audio,
            anc,
            arc: None,
        },
        audio_fmt: payload.get(40..48).and_then(audio_format),
    };
    if let Some(device) = state.device_mut(target) {
        device.set_v2ip_sink(sink, ev);
    }
}

/// Points a sink at the source bays advertising the given groups, leaving a
/// stream that maps to no known bay alone.
fn apply_stream_route(
    state: &mut State,
    sink: BayUid,
    video_ip: Ipv4Addr,
    audio_ip: Ipv4Addr,
    ev: &mut Vec<Event>,
) {
    let video = state.bay_by_stream_ip(video_ip, false);
    let audio = state.bay_by_stream_ip(audio_ip, true);
    if let Some(bay) = state.bay_mut(sink) {
        if let Some(video) = video {
            bay.set_video_source(Some(video), ev);
        }
        if let Some(audio) = audio {
            bay.set_audio_source(Some(audio), ev);
        }
    }
}

/// The device a V2IP configuration frame is about, or `None` when nothing on
/// the network would act on it.
///
/// The payload names its subject in the first sixteen bytes, and that is what
/// decides whose configuration this is - not who sent it. Equal to the sender
/// it is a device describing itself, which is what almost every one of these
/// frames is. Different, it is a write for the device it names, and a receiver
/// takes one only from a sender it treats as management. Anything else is
/// dropped rather than filed against the sender, because a frame the network
/// ignores must not move a record here.
fn v2ip_config_subject(state: &State, rx: &Rx<'_>, p: &[u8]) -> Option<DeviceUid> {
    let subject = uid_at(p, 0);
    if subject == rx.sender() {
        return Some(subject);
    }
    // An unknown subject is dropped, as it is on a device: there is no record
    // to move, and inventing one from a third party's description would create
    // a device nothing has been heard from.
    state.device(subject)?;
    manages(state, rx.sender(), subject).then_some(subject)
}

/// Whether a device takes a write about `subject` from `sender`.
///
/// Management standing, or the subject naming this sender as its mesh
/// controller. The second is asked of the subject rather than the sender
/// because it closes the window where a controller has been promoted but has
/// no bays mapped yet, and so announces neither bit while still being the
/// controller its mesh obeys.
///
/// A subject that has named no controller contributes nothing here rather than
/// refusing: not knowing who a device follows is not knowing that it follows
/// nobody, and a client that has just started knows nothing about anyone for as
/// long as a broadcast period.
pub(super) fn manages(state: &State, sender: DeviceUid, subject: DeviceUid) -> bool {
    state.device(sender).is_some_and(Device::is_management)
        || state
            .device(subject)
            .is_some_and(|d| !d.mesh_master.is_zero() && d.mesh_master == sender)
}

/// Which scaling flag bits may be believed from this sender.
///
/// A sender that does not initialise this block builds it over an
/// uninitialised stack local, so every bit in the byte is suspect. Only the
/// second options group is dropped for it: those bits cannot be real on such a
/// sender, whereas the older ones can, and the caller is told which case it has
/// through the same announcement.
fn scaling_flag_mask(state: &State, rx: &Rx<'_>) -> u8 {
    if state
        .device(rx.sender())
        .is_some_and(Device::config_initialised)
    {
        return SCALING_FLAGS_DEFINED;
    }
    SCALING_FLAGS_DEFINED
        & !(SCALING_FLAG_OPTIONS2_VALID | SCALING_FLAG_MATCH_SOURCE | SCALING_FLAG_SKIP_420)
}

/// The configuration block as it was before the tiling window was appended to
/// it, which is the shortest whole one any sender emits.
///
/// Every field ahead of the window sits at the same offset in both forms, so a
/// sender of this one is decoded in full rather than refused: it is a complete
/// configuration, just an older one.
const V2IP_CONFIG_SIZE_BASE: usize = 64;

/// The configuration block with the tiling window on the end.
const V2IP_CONFIG_SIZE: usize = 88;

/// The sink block the options extension opens with.
const V2IP_SINK_SIZE: usize = 32;

/// Where the processor's feature word sits, behind the sink block at the end of
/// the options extension.
const V2IP_CODEC_AT: usize = V2IP_CONFIG_SIZE + V2IP_SINK_SIZE;
const V2IP_CODEC_SIZE: usize = 8;

/// Where the device settings sit, behind the processor's feature word.
const V2IP_SETTINGS_AT: usize = V2IP_CODEC_AT + V2IP_CODEC_SIZE;
const V2IP_SETTINGS_SIZE: usize = 16;

/// Applies a device's V2IP encoder configuration, and the tiling and sink
/// blocks a longer frame appends to it.
///
/// Every block lands on the device the payload names, which is the sender only
/// when the sender is describing itself.
pub(super) fn v2ip_device_configuration(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let p = rx.frame.payload();
    // A whole configuration or nothing. Shorter than the oldest complete form is
    // a frame no device anywhere acts on, and the fields it does carry are not
    // worth holding a configuration nothing else believes in.
    if p.len() < V2IP_CONFIG_SIZE_BASE {
        return;
    }
    let Some(subject) = v2ip_config_subject(state, rx, p) else {
        return;
    };
    let tx_rate = p.get(40).copied().filter(|rate| {
        (crate::wire::V2IP_SOURCE_RATE_MIN..=crate::wire::V2IP_SOURCE_RATE_MAX).contains(rate)
    });
    let details = DeviceV2ipDetails {
        video: stream_source(StreamKind::Video, p, 16),
        audio: stream_source(StreamKind::Audio, p, 24),
        anc: stream_source(StreamKind::Anc, p, 32),
        arc: stream_source(StreamKind::Arc, p, 48),
        tx_rate,
        dscp: V2ipDscpConfig {
            video: crate::types::parse_dscp(byte(p, 41)),
            audio: crate::types::parse_dscp(byte(p, 42)),
            anc: crate::types::parse_dscp(byte(p, 43)),
        },
        scaling: V2ipScalingSettings {
            mode: MxrSignalType::from_wire(u16_at(p, 56)),
            refresh: u16_at(p, 58),
            // Undefined bits never reach the cache, even on a first frame:
            // firmware that does not initialise this frame builds it from an
            // uninitialised stack local and ORs its flags onto whatever was
            // there.
            //
            // The second options group is dropped from such a sender
            // entirely. No firmware carries those options without also
            // announcing that it initialises this block, so a sender that does
            // not announce it has no such settings - masking them can discard
            // nothing real, while reading them would invent a capability out
            // of whatever the stack held.
            //
            // The older bits are not that case and are kept. A sender without
            // the announcement can still have a genuine mode configured, and
            // the captured frame in the tests is one: its refresh agrees with
            // the rate its mode names, which junk does not do. Dropping those
            // would discard the only reading of that device anyone has.
            flags: byte(p, 60) & scaling_flag_mask(state, rx),
        },
    };
    if let Some(device) = state.device_mut(subject) {
        device.set_v2ip_details(details, ev);
    }

    // The tiling window was appended to the configuration, so a sender that
    // predates it stops in front of it and the length is what says it is there.
    // It carries no validity flag of its own; its uid is the marker. Every path
    // that produces a real window stamps it, and a controller writing any other
    // field sends the block zeroed - so a zero uid means "not carried" while a
    // set uid with zero geometry is a real clear.
    //
    // As with the processor word below, the length test cannot be observed to
    // fail: a window that is not there reads as a zero uid through a
    // bounds-checked accessor, which is already the marker for absent. It stays
    // because whether the block is present is a question about the frame's
    // shape, and leaving it to the marker would make that depend on the
    // accessor's out-of-range value rather than on the length.
    let target = uid_at(p, 64);
    if p.len() >= V2IP_CONFIG_SIZE && !target.is_zero() {
        let tiling = V2ipTilingConfig {
            target,
            pos_x: u16_at(p, 80),
            pos_y: u16_at(p, 82),
            width: u16_at(p, 84),
            height: u16_at(p, 86),
        };
        if let Some(device) = state.device_mut(subject) {
            device.set_tiling(tiling, ev);
        }
    }

    // Everything past the configuration is the options extension, found by
    // length alone: each block that was appended to it left every offset ahead
    // of it where it was, so no stamp distinguishes the forms and a sender that
    // predates a block simply stops short of it.
    //
    // The sink block is a device's own report. A controller writing another
    // device's configuration sends it zeroed, because it has nothing to say
    // about that sink's subscription, and caching those zeros would clear
    // every reader's record of the route on each unrelated write.
    if p.len() >= V2IP_CONFIG_SIZE + V2IP_SINK_SIZE && subject == rx.sender() {
        let sink = DeviceV2ipSink {
            addresses: V2ipStreamSources {
                uid: DeviceUid::ZERO,
                video: stream_source(StreamKind::Video, p, 88),
                audio: stream_source(StreamKind::Audio, p, 96),
                anc: stream_source(StreamKind::Anc, p, 104),
                arc: None,
            },
            audio_fmt: p.get(112..120).and_then(audio_format),
        };
        if let Some(device) = state.device_mut(subject) {
            device.set_v2ip_sink(sink, ev);
        }
    }

    // A device's processor features are its own. It fills the word in only on
    // the frame describing itself and leaves it zero on one it sends to
    // configure another device, so a write about a third party says nothing
    // about that party's processor - and caching its zero would report a device
    // as supporting nothing on the strength of a frame that never asked it.
    //
    // Zero from the device itself is no better: the mask is empty until the
    // processor answers after boot, and an older processor answers with none of
    // the optional commands. The two are identical on the wire, so an empty
    // mask stays unknown rather than becoming an empty capability set.
    //
    // The length test cannot be observed to fail while that is true - a word
    // that is not there reads as zero through a bounds-checked accessor, and an
    // absent mask and an empty one mean the same thing to a caller. It stays
    // because it is the rule that decides whether the field is present, which
    // is a different question from what it holds: read the two as one and the
    // presence of a field silently depends on zero meaning "not reported".
    if p.len() >= V2IP_CODEC_AT + V2IP_CODEC_SIZE && subject == rx.sender() {
        let features = V2ipFpgaFeature::from_bits(u64_at(p, V2IP_CODEC_AT));
        if !features.is_empty() {
            if let Some(device) = state.device_mut(subject) {
                device.set_v2ip_features(features, ev);
            }
        }
    }

    // The device reports every setting it has. A controller sends only the
    // ones it changes, and the device applies only those it has, so a write
    // is cached as far as the device will take it and no further.
    if let Some(s) = p.get(V2IP_SETTINGS_AT..V2IP_SETTINGS_AT + V2IP_SETTINGS_SIZE) {
        let frame = V2ipDeviceSettings {
            valid: V2ipDeviceSetting::from_bits(u32_at(s, 0)),
            flags: V2ipDeviceSetting::from_bits(u32_at(s, 4)),
            ir_profiles: u32_at(s, 8),
            ir_profile: s[12] as i8,
            ir_profile_sink: s[13] as i8,
        };
        if let Some(device) = state.device_mut(subject) {
            let frame = if subject == rx.sender() {
                frame
            } else {
                let reported = device.v2ip_settings.unwrap_or_default().valid;
                frame.as_applied_to(reported)
            };
            device.merge_v2ip_settings(frame, ev);
        }
    }
}

pub(super) fn bay_hide(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let target = rx.uid_or_zero(0);
    let Some(port) = rx.frame.u16(16) else {
        return;
    };
    let hidden = if rx.frame.boolean(18) {
        HiddenStatus::Hidden
    } else {
        HiddenStatus::Visible
    };
    if let Some(bay) = state.bay_mut(BayUid::new(target, port)) {
        bay.apply_hidden(hidden, ev);
    }
}

/// Applies a bay status report.
///
/// `mxr_bay_status.local_bay` is an `mbay_port_id`, so it is a `u16` at 0.
/// Reading its high byte at 1 yields zero for every real port and finds no bay
/// at all.
pub(super) fn bay_status(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let f = &rx.frame;
    let Some(port) = f.u16(0) else {
        return;
    };
    let sender = rx.sender();
    let Some(device) = state.device(sender) else {
        return;
    };
    if device.bay(port).is_none() {
        return;
    }
    let is_v2ip = device.is_v2ip();
    let features = f.u32(24);
    let Some(status) = f.u32(20).map(BayStatus::from_bits) else {
        return;
    };
    // `mxr_cfg_signal` is a 14-byte description followed by a 2-byte signal
    // type, so the description stops at 14 rather than running into the type.
    let description = f.str(2, 14);

    if let Some(bay) = state.bay_mut(BayUid::new(sender, port)) {
        if let Some(features) = features {
            bay.features = crate::wire::BayFeatures::from_bits(features);
        }
        bay.apply_bay_status(status, ev);
        // 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 !status.has(BayStatus::SIGNAL_DETECTED) || !is_v2ip {
            bay.apply_signal_status(status.has(BayStatus::SIGNAL_DETECTED), description, ev);
        }
    }
}

/// Width of one record in the link configuration frame.
const LINK_RECORD: usize = 38;

/// Merges one page of link descriptors into the link registry, paged the same
/// way as the bay configuration.
pub(super) fn links(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let sender = rx.sender();
    let records: Vec<(u16, String, String, u32)> = rx
        .frame
        .payload()
        .chunks_exact(LINK_RECORD)
        .map(|record| {
            (
                u16::from(byte(record, 0)),
                crate::wire::cstr(&record[2..18]),
                crate::wire::cstr(&record[18..34]),
                u32_at(record, 34),
            )
        })
        .collect();
    for (port, linked_serial, linked_bay, features) in records {
        let origin = BayUid::new(sender, port);
        // A record naming a bay this client has not seen is dropped rather
        // than held, matching what a device does with the same frame, and the
        // device re-sends.
        if state.bay(origin).is_none() {
            continue;
        }
        state.update_link(origin, linked_serial, linked_bay, features, ev);
    }
    // The page counts as the list having been reported whatever landed, which
    // is the whole of what the link configuration establishes. Most of a V2IP
    // device's bays own no record, so a record per bay is a total no device
    // reaches.
    if let Some(device) = state.device_mut(sender) {
        device.note_link_config(rx.timestamp, ev);
    }
}

/// Applies a mirror report: which device's output this one is repeating.
pub(super) fn mirror_status(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let sender = rx.sender();
    let target = rx.uid_or_zero(0);
    if sender != target {
        return;
    }
    let Some(port) = state.device(sender).and_then(|d| d.first_output_port()) else {
        return;
    };
    let master = rx.uid_or_zero(16);
    let mirror = BayMirrorStatus {
        target: (!master.is_zero() && master != target).then(|| BayUid::new(master, 0)),
    };
    if let Some(bay) = state.bay_mut(BayUid::new(sender, port)) {
        bay.set_mirroring(mirror, ev);
    }
}

/// The mesh sub-opcode that reports which device is the mesh master.
const MESH_REPORT_MEMBERSHIP: u8 = 0xFF;

/// Size of `mxr_mesh_operation`, which is 8-aligned: the operation byte is
/// followed by three bytes of padding before the two uids.
const MESH_OPERATION_SIZE: usize = 40;

/// The protocol version from which a mesh operation is acted on at all.
///
/// Below this the opcode's own receiver ignores the frame, so a client that
/// read one anyway would take a mesh master from a frame no device acted on.
/// It is not this opcode's table entry: that is 0x1D, the version its
/// report-controller operation grew a second parameter at.
///
/// This is the one version test on a receive path here that a length cannot
/// replace. The operation struct is fixed size, and what changed at this
/// version is what its bytes mean rather than how many there are, so every form
/// of it measures the same and nothing about the payload distinguishes them.
/// Senders below this are still on the network, and their operations are
/// ignored deliberately rather than missed.
const MESH_OPERATION_PROTOCOL: u16 = 0x1A;

pub(super) fn mesh_operation(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    if rx.frame.payload().len() < MESH_OPERATION_SIZE
        || rx.frame.protocol() < MESH_OPERATION_PROTOCOL
    {
        return;
    }
    if rx.frame.u8(0) != Some(MESH_REPORT_MEMBERSHIP) {
        return;
    }
    let master = rx.uid_or_zero(4);
    if let Some(device) = state.device_mut(rx.sender()) {
        device.set_mesh_master(master, ev);
    }
}

/// Records which source device each V2IP bay stands in for.
///
/// The first `u16` packs the record count above a direction bit, and the
/// second is the bay number the run starts at.
pub(super) fn v2ip_bay_mapping(state: &mut State, rx: &Rx<'_>, _ev: &mut [Event]) {
    let f = &rx.frame;
    let (Some(header), Some(first)) = (f.u16(0), f.u16(2)) else {
        return;
    };
    let count = header >> 1;
    let mode = if header & 1 == 1 { "Input" } else { "Output" };
    let sender = rx.sender();

    let Some(device) = state.device_mut(sender) else {
        return;
    };
    for i in 0..count {
        let Some(uid) = f.uid(8 + 16 * usize::from(i)) else {
            break;
        };
        let Some(number) = first.checked_add(i).and_then(|n| u8::try_from(n).ok()) else {
            break;
        };
        // Kept for a bay not configured yet as well: a device may send its
        // mappings ahead of the bay configuration that creates the bays.
        device.v2ip_bay_mappings.insert((mode, number), uid);
        let port = device.bay_by_mode_num(mode, number).map(|bay| bay.port);
        if let Some(bay) = port.and_then(|port| device.bays.get_mut(&port)) {
            bay.v2ip_uid = uid;
        }
    }
}

/// Width of one entry in a topology report.
const TOPOLOGY_ENTRY: usize = 20;

pub(super) fn topology(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let topology: Vec<TopologyEntry> = rx
        .frame
        .payload()
        .chunks_exact(TOPOLOGY_ENTRY)
        .map(|entry| TopologyEntry {
            uid: uid_at(entry, 0),
            mask: u32_at(entry, 16),
        })
        .collect();
    if let Some(device) = state.device_mut(rx.sender()) {
        device.set_topology(topology, ev);
    }
}

/// Applies a firmware version report for one component.
pub(super) fn firmware_version(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let f = &rx.frame;
    let Some(firmware_type) = f.u8(0) else {
        return;
    };
    // Read at most the field's own width, but settle for what a peer sending a
    // short frame did give us rather than losing the whole report over a name.
    let available = f.payload().len().saturating_sub(12);
    let name_len = available.min(FW_VERSION_LEN);
    if name_len == 0 {
        return;
    }
    let (Some(version), Some(timestamp)) = (f.str(12, name_len), f.u32(8)) else {
        return;
    };
    let version = FirmwareVersion {
        firmware_type: FirmwareType::from_wire(firmware_type),
        timestamp,
        version,
        hash: f.u32(4).unwrap_or(0),
    };
    if let Some(device) = state.device_mut(rx.sender()) {
        device.set_firmware_version(version, ev);
    }
}

pub(super) fn system_status(state: &mut State, rx: &Rx<'_>, ev: &mut Vec<Event>) {
    let Some(status) = rx.frame.u16(16) else {
        return;
    };
    let message = rx.frame.str_to_end(18).unwrap_or_default();
    if let Some(device) = state.device_mut(rx.sender()) {
        device.set_system_status(status, message, ev);
    }
}

// ---- shared readers ----

pub(super) fn byte(p: &[u8], idx: usize) -> u8 {
    p.get(idx).copied().unwrap_or(0)
}

pub(super) fn u16_at(p: &[u8], idx: usize) -> u16 {
    p.get(idx..idx + 2)
        .and_then(|b| <[u8; 2]>::try_from(b).ok())
        .map_or(0, u16::from_le_bytes)
}

pub(super) fn u32_at(p: &[u8], idx: usize) -> u32 {
    p.get(idx..idx + 4)
        .and_then(|b| <[u8; 4]>::try_from(b).ok())
        .map_or(0, u32::from_le_bytes)
}

pub(super) fn u64_at(p: &[u8], idx: usize) -> u64 {
    p.get(idx..idx + 8)
        .and_then(|b| <[u8; 8]>::try_from(b).ok())
        .map_or(0, u64::from_le_bytes)
}

pub(super) fn uid_at(p: &[u8], idx: usize) -> DeviceUid {
    p.get(idx..idx + 16)
        .and_then(|b| <[u8; 16]>::try_from(b).ok())
        .map_or(DeviceUid::ZERO, DeviceUid::from_array)
}

/// Reads a network-order IPv4 address.
pub(super) fn ipv4_at(p: &[u8], idx: usize) -> Ipv4Addr {
    Ipv4Addr::new(
        byte(p, idx),
        byte(p, idx + 1),
        byte(p, idx + 2),
        byte(p, idx + 3),
    )
}

/// Reads a `v2ip_stream_addr`: an address and a port.
pub(super) fn stream_source(kind: StreamKind, p: &[u8], idx: usize) -> V2ipStreamSource {
    V2ipStreamSource {
        kind,
        ip: ipv4_at(p, idx),
        port: u16_at(p, idx + 4),
    }
}

/// Reads an audio format block, which is absent when it reports no channels.
fn audio_format(p: &[u8]) -> Option<crate::types::V2ipAudioFormat> {
    let channels = byte(p, 4);
    (channels != 0).then(|| crate::types::V2ipAudioFormat {
        sample_rate: u32_at(p, 0),
        channels,
    })
}