mx_remote/types/v2ip.rs
1// Author: Lars Op den Kamp (lars@opdenkamp-it.nl)
2// Copyright (c) 2026 Op den Kamp IT Solutions
3
4//! V2IP stream configuration, statistics and the sink-side route.
5
6use core::fmt;
7use std::net::Ipv4Addr;
8
9use crate::wire::{
10 DeviceUid, MxrSignalType, V2ipColourSpace, V2ipDeviceSetting, V2IP_AUDIO_DEFAULT_CHANNELS,
11 V2IP_AUDIO_DEFAULT_SAMPLE_RATE, V2IP_DSCP_MAX, V2IP_DSCP_SET, V2IP_IR_PROFILE_MAX,
12 V2IP_IR_PROFILE_NOT_SET,
13};
14
15/// Which of a V2IP device's streams an address describes.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub enum StreamKind {
18 /// The video stream.
19 #[default]
20 Video,
21 /// The audio stream.
22 Audio,
23 /// The ancillary-data stream.
24 Anc,
25 /// The audio-return stream.
26 Arc,
27}
28
29impl fmt::Display for StreamKind {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 f.write_str(match self {
32 Self::Video => "video",
33 Self::Audio => "audio",
34 Self::Anc => "anc",
35 Self::Arc => "arc",
36 })
37 }
38}
39
40/// A single multicast stream address.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct V2ipStreamSource {
43 /// Which stream this address is for.
44 pub kind: StreamKind,
45 /// The multicast group.
46 pub ip: Ipv4Addr,
47 /// The destination UDP port.
48 pub port: u16,
49}
50
51impl Default for V2ipStreamSource {
52 fn default() -> Self {
53 Self {
54 kind: StreamKind::default(),
55 ip: Ipv4Addr::UNSPECIFIED,
56 port: 0,
57 }
58 }
59}
60
61impl V2ipStreamSource {
62 /// Reports whether this carries a usable address: a multicast group and a
63 /// non-zero port, both, matching firmware `mxr_v2ip_stream_valid`.
64 pub const fn is_valid(&self) -> bool {
65 self.ip.is_multicast() && self.port != 0
66 }
67}
68
69impl fmt::Display for V2ipStreamSource {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 write!(f, "{}={}:{}", self.kind, self.ip, self.port)
72 }
73}
74
75/// The streams advertised by a single V2IP source.
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
77pub struct V2ipStreamSources {
78 /// The originating device, or the zero UID when it is not known.
79 pub uid: DeviceUid,
80 /// The video stream.
81 pub video: V2ipStreamSource,
82 /// The audio stream.
83 pub audio: V2ipStreamSource,
84 /// The ancillary-data stream.
85 pub anc: V2ipStreamSource,
86 /// The audio-return stream, when one is advertised.
87 pub arc: Option<V2ipStreamSource>,
88}
89
90impl fmt::Display for V2ipStreamSources {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 write!(
93 f,
94 "video:{} audio:{} anc:{}",
95 self.video, self.audio, self.anc
96 )
97 }
98}
99
100/// One multicast destination in a route the caller assembles.
101///
102/// The unspecified address sends the slot zeroed, naming no group for that
103/// stream. It is not a way to leave one stream alone: the firmware decides
104/// whether a sink has a manual route at all by reading the video and
105/// ancillary slots, so an empty one of those disqualifies the whole route
106/// rather than preserving anything - see
107/// [`crate::Remote::select_source_addr`].
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct V2ipRouteTarget {
110 /// The multicast group.
111 pub ip: Ipv4Addr,
112 /// The destination UDP port. Zero means the standard port for the stream
113 /// this target is given as.
114 pub port: u16,
115}
116
117impl Default for V2ipRouteTarget {
118 fn default() -> Self {
119 Self {
120 ip: Ipv4Addr::UNSPECIFIED,
121 port: 0,
122 }
123 }
124}
125
126impl V2ipRouteTarget {
127 /// A target at the standard port for its stream.
128 pub const fn new(ip: Ipv4Addr) -> Self {
129 Self { ip, port: 0 }
130 }
131
132 /// The port to send, substituting `standard` for an unset one.
133 pub(crate) const fn port_or(self, standard: u16) -> u16 {
134 if self.port == 0 {
135 standard
136 } else {
137 self.port
138 }
139 }
140}
141
142impl fmt::Display for V2ipRouteTarget {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 write!(f, "{}:{}", self.ip, self.port)
145 }
146}
147
148/// The three streams a manual route points a V2IP sink at.
149///
150/// Fill in all three. The firmware decides whether a sink has a manual route
151/// at all by looking at the video and ancillary groups, so a route carrying
152/// only audio does not register as one and the sink falls back to the audio
153/// source its mesh picks.
154#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
155pub struct V2ipRoute {
156 /// The video stream, at [`crate::V2IP_PORT_VIDEO`] unless the port says otherwise.
157 pub video: V2ipRouteTarget,
158 /// The audio stream, at [`crate::V2IP_PORT_AUDIO`] unless the port says otherwise.
159 pub audio: V2ipRouteTarget,
160 /// The ancillary-data stream, at [`crate::V2IP_PORT_ANC`] unless the port says
161 /// otherwise.
162 pub anc: V2ipRouteTarget,
163}
164
165impl V2ipRoute {
166 /// The three streams of one source, at the ports it advertises them on.
167 pub fn of(sources: &V2ipStreamSources) -> Self {
168 let target = |s: &V2ipStreamSource| V2ipRouteTarget {
169 ip: s.ip,
170 port: s.port,
171 };
172 Self {
173 video: target(&sources.video),
174 audio: target(&sources.audio),
175 anc: target(&sources.anc),
176 }
177 }
178}
179
180impl fmt::Display for V2ipRoute {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 write!(
183 f,
184 "video:{} audio:{} anc:{}",
185 self.video, self.audio, self.anc
186 )
187 }
188}
189
190/// The sample rate and channel count a V2IP audio stream is decoded at.
191///
192/// Fill both in. The firmware header calls zero "use the default", but the
193/// path that applies a manual route substitutes nothing: it hands the pair to
194/// the FPGA as it arrived, and the FPGA rejects a zero rate and takes the
195/// whole switch down with it. [`V2ipAudioFormat::STANDARD`] is the pair the
196/// header documents as the default.
197#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
198pub struct V2ipAudioFormat {
199 /// Sample rate in Hz.
200 pub sample_rate: u32,
201 /// Channel count.
202 pub channels: u8,
203}
204
205impl V2ipAudioFormat {
206 /// 48kHz stereo: the rate and channel count the firmware header names as
207 /// its default, which a caller has to send because firmware does not
208 /// substitute it.
209 pub const STANDARD: Self = Self {
210 sample_rate: V2IP_AUDIO_DEFAULT_SAMPLE_RATE,
211 channels: V2IP_AUDIO_DEFAULT_CHANNELS,
212 };
213
214 /// Encodes `v2ip_audio_format`: a `u32` rate, a channel byte and three
215 /// reserved bytes, padded to the struct's 8-byte alignment.
216 pub(crate) fn wire(&self) -> [u8; 8] {
217 let r = self.sample_rate.to_le_bytes();
218 [r[0], r[1], r[2], r[3], self.channels, 0, 0, 0]
219 }
220}
221
222impl fmt::Display for V2ipAudioFormat {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 write!(f, "{}Hz/{}ch", self.sample_rate, self.channels)
225 }
226}
227
228/// A V2IP output's scaling mode, refresh rate and flags.
229#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
230pub struct V2ipScalingSettings {
231 /// The signal type the output scales to.
232 pub mode: MxrSignalType,
233 /// Refresh rate in Hz.
234 pub refresh: u16,
235 /// The flag bits below.
236 pub flags: u8,
237}
238
239/// Set when the frame carries a scaling mode and refresh rate.
240pub const SCALING_FLAG_MODE_VALID: u8 = 1 << 0;
241
242/// Set when the frame carries the scaling options.
243pub const SCALING_FLAG_OPTIONS_VALID: u8 = 1 << 1;
244
245/// Set when the frame carries the second group of scaling options.
246///
247/// Firmware that has those options sets this on every configuration it sends
248/// about itself, so it doubles as the report that the device has them at all.
249pub const SCALING_FLAG_OPTIONS2_VALID: u8 = 1 << 4;
250
251/// Set when the output follows its source's format instead of a fixed one.
252pub const SCALING_FLAG_MATCH_SOURCE: u8 = 1 << 5;
253
254/// Set when the output declines 4:2:0 rather than scaling it.
255pub const SCALING_FLAG_SKIP_420: u8 = 1 << 6;
256
257/// Set when the output scales automatically.
258pub const SCALING_FLAG_AUTO_SCALING: u8 = 1 << 7;
259
260/// The flag bits that carry meaning.
261///
262/// Bits 2 and 3 have no meaning and are excluded: they are not reliably zero
263/// on the wire, because firmware that does not initialise the configuration it
264/// broadcasts builds this frame from an uninitialised stack local and ORs its
265/// flags onto whatever was there. The same is true of every bit here on such a
266/// sender, which is why each reading below says what it rests on.
267pub const SCALING_FLAGS_DEFINED: u8 = SCALING_FLAG_MODE_VALID
268 | SCALING_FLAG_OPTIONS_VALID
269 | SCALING_FLAG_OPTIONS2_VALID
270 | SCALING_FLAG_MATCH_SOURCE
271 | SCALING_FLAG_SKIP_420
272 | SCALING_FLAG_AUTO_SCALING;
273
274/// Lowest refresh rate a V2IP output stage accepts, in Hz.
275///
276/// A receiver replaces anything outside
277/// [`V2IP_SCALING_REFRESH_MIN`]..=[`V2IP_SCALING_REFRESH_MAX`] with 50 rather
278/// than refusing the write, so 0 asks for 50Hz here instead of asking for
279/// nothing.
280pub const V2IP_SCALING_REFRESH_MIN: u16 = 24;
281
282/// Highest refresh rate a V2IP output stage accepts, in Hz. See
283/// [`V2IP_SCALING_REFRESH_MIN`].
284pub const V2IP_SCALING_REFRESH_MAX: u16 = 120;
285
286/// The output format to scale a V2IP sink to.
287///
288/// Built from a depth and a colour space rather than from a packed signal-type
289/// word, so the word a caller sends cannot carry the unset bpp index a sink
290/// reports while it has no mode configured.
291#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
292pub struct V2ipOutputMode {
293 /// The CTA-861 short video descriptor to output.
294 pub svd: u8,
295 /// Bit depth: 8, 10 or 12.
296 pub depth: u8,
297 /// The colour space to output.
298 pub colour: V2ipColourSpace,
299 /// Refresh rate in Hz, [`V2IP_SCALING_REFRESH_MIN`] to
300 /// [`V2IP_SCALING_REFRESH_MAX`].
301 pub refresh: u16,
302}
303
304impl V2ipOutputMode {
305 /// Reports whether a sink will take this mode, or why it will not.
306 ///
307 /// Checked here because a sink checks it and then says nothing: every value
308 /// this rejects is one the receiver decodes cleanly and drops, leaving a
309 /// caller with a send that succeeded and a setting that did not move.
310 ///
311 /// Passing is not a guarantee. A sink also weighs the format against the
312 /// EDID of the display attached to it and against what its own clock and
313 /// output stage can produce, and none of that is knowable from here.
314 pub fn validate(&self) -> Result<(), &'static str> {
315 if self.svd == 0 {
316 return Err("svd 0 is how a mode is cleared, not a mode to set");
317 }
318 if crate::lookup_svd(u16::from(self.svd)).is_none() {
319 return Err("the svd names no known video descriptor");
320 }
321 if MxrSignalType::bpp_index_for_depth(self.depth).is_none() {
322 return Err("a V2IP output stage takes 8, 10 or 12 bits per pixel");
323 }
324 if self.colour > V2ipColourSpace::YCBCR420 {
325 return Err("the colour space names none of RGB, 4:4:4, 4:2:2 or 4:2:0");
326 }
327 if !(V2IP_SCALING_REFRESH_MIN..=V2IP_SCALING_REFRESH_MAX).contains(&self.refresh) {
328 return Err("the refresh rate is outside 24..=120Hz");
329 }
330 Ok(())
331 }
332
333 /// The packed signal type a scaling write carries for this mode.
334 ///
335 /// Call [`V2ipOutputMode::validate`] first: an unvalidated depth packs as
336 /// the index for "no depth", which a receiver drops.
337 pub(crate) fn to_signal_type(self) -> MxrSignalType {
338 MxrSignalType::from_parts(
339 self.svd,
340 self.colour.to_wire(),
341 MxrSignalType::bpp_index_for_depth(self.depth).unwrap_or(0),
342 )
343 }
344}
345
346impl fmt::Display for V2ipOutputMode {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 write!(
349 f,
350 "svd {}, colour {}, {}bpp, {}Hz",
351 self.svd,
352 self.colour.to_wire(),
353 self.depth,
354 self.refresh
355 )
356 }
357}
358
359impl V2ipScalingSettings {
360 /// The mode this sink is configured to scale to, `None` when it has none.
361 ///
362 /// The two are distinct on the wire: a sink with no mode configured leaves
363 /// [`SCALING_FLAG_MODE_VALID`] clear, and never sets it over a zero mode.
364 ///
365 /// Trust it only where the sender reports
366 /// [`crate::DeviceInfo::config_initialised`]. Firmware without that builds
367 /// this block over uninitialised stack, where the valid bit itself is
368 /// noise.
369 pub const fn configured_mode(&self) -> Option<(MxrSignalType, u16)> {
370 if self.flags & SCALING_FLAG_MODE_VALID == 0 {
371 return None;
372 }
373 Some((self.mode, self.refresh))
374 }
375
376 /// Whether the output scales automatically, `None` when the sender did not
377 /// say.
378 pub const fn auto_scaling(&self) -> Option<bool> {
379 if self.flags & SCALING_FLAG_OPTIONS_VALID == 0 {
380 return None;
381 }
382 Some(self.flags & SCALING_FLAG_AUTO_SCALING != 0)
383 }
384
385 /// Whether the output follows its source's format, `None` when the device
386 /// has never said.
387 ///
388 /// Firmware with this option announces it on every configuration it sends
389 /// about itself, so a device that has reported it once is known to have
390 /// it. The cached block accumulates its validity bits, so a later write
391 /// carrying only the first options group does not take that back.
392 ///
393 /// Reported only from a sender announcing
394 /// [`crate::DeviceInfo::config_initialised`], so this needs no caveat of
395 /// its own: no firmware has these options without that announcement, and
396 /// one that lacks it would be reporting uninitialised stack. That is the
397 /// difference from [`Self::configured_mode`], which is reported from any
398 /// sender because a mode can be genuine on one of those.
399 pub const fn match_source(&self) -> Option<bool> {
400 if self.flags & SCALING_FLAG_OPTIONS2_VALID == 0 {
401 return None;
402 }
403 Some(self.flags & SCALING_FLAG_MATCH_SOURCE != 0)
404 }
405
406 /// Whether the output declines 4:2:0 rather than scaling it, `None` when
407 /// the device has never said. Reported on the same terms as
408 /// [`Self::match_source`], which shares its validity bit.
409 pub const fn skip_420(&self) -> Option<bool> {
410 if self.flags & SCALING_FLAG_OPTIONS2_VALID == 0 {
411 return None;
412 }
413 Some(self.flags & SCALING_FLAG_SKIP_420 != 0)
414 }
415
416 /// Folds a received scaling config onto the cached one, field by field.
417 ///
418 /// A write carries the mode or the options alone, so taking the block
419 /// wholesale would drop whichever half was not being written. The options
420 /// branch replaces the option bit rather than adding to it, which is what
421 /// lets an options-only write clear [`SCALING_FLAG_AUTO_SCALING`].
422 #[must_use]
423 pub fn merge(self, previous: Self) -> Self {
424 let mut out = previous;
425 if self.flags & SCALING_FLAG_MODE_VALID != 0 {
426 out.mode = self.mode;
427 out.refresh = self.refresh;
428 out.flags |= SCALING_FLAG_MODE_VALID;
429 }
430 if self.flags & SCALING_FLAG_OPTIONS_VALID != 0 {
431 out.flags &= !SCALING_FLAG_AUTO_SCALING;
432 out.flags |= SCALING_FLAG_OPTIONS_VALID;
433 out.flags |= self.flags & SCALING_FLAG_AUTO_SCALING;
434 }
435 // One validity bit covers both options in this group, so a frame
436 // carrying it replaces both and a frame without it leaves both alone -
437 // which is also what keeps the bit itself, and so the knowledge that
438 // the device has these options, from being taken back by a later write
439 // that carries only the first group.
440 if self.flags & SCALING_FLAG_OPTIONS2_VALID != 0 {
441 out.flags &= !(SCALING_FLAG_MATCH_SOURCE | SCALING_FLAG_SKIP_420);
442 out.flags |= SCALING_FLAG_OPTIONS2_VALID;
443 out.flags |= self.flags & (SCALING_FLAG_MATCH_SOURCE | SCALING_FLAG_SKIP_420);
444 }
445 out
446 }
447}
448
449/// The per-stream DSCP marking in a V2IP device configuration.
450///
451/// A stream whose wire byte carries no [`V2IP_DSCP_SET`] bit reads back as
452/// `None`. Firmware treats the marking as all-or-nothing: it applies one only
453/// when all three streams carry a value and otherwise falls back to the
454/// default, so [`V2ipDscpConfig::is_complete`] reports which case a frame is in.
455#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
456pub struct V2ipDscpConfig {
457 /// Marking for the video stream.
458 pub video: Option<u8>,
459 /// Marking for the audio stream.
460 pub audio: Option<u8>,
461 /// Marking for the ancillary-data stream.
462 pub anc: Option<u8>,
463}
464
465impl V2ipDscpConfig {
466 /// Reports whether all three streams carry a marking, which is what
467 /// firmware requires before it applies one.
468 pub const fn is_complete(&self) -> bool {
469 self.video.is_some() && self.audio.is_some() && self.anc.is_some()
470 }
471}
472
473impl fmt::Display for V2ipDscpConfig {
474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 match (self.video, self.audio, self.anc) {
476 (Some(v), Some(a), Some(n)) => write!(f, "video:{v} audio:{a} anc:{n}"),
477 _ => f.write_str("no marking"),
478 }
479 }
480}
481
482/// Decodes one `dscp` byte, or `None` when the byte carries no marking.
483pub(crate) fn parse_dscp(raw: u8) -> Option<u8> {
484 (raw & V2IP_DSCP_SET != 0).then_some(raw & V2IP_DSCP_MAX)
485}
486
487/// The local encoder/decoder configuration of a V2IP device.
488#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
489pub struct DeviceV2ipDetails {
490 /// The video stream this device sources.
491 pub video: V2ipStreamSource,
492 /// The audio stream this device sources.
493 pub audio: V2ipStreamSource,
494 /// The ancillary-data stream this device sources.
495 pub anc: V2ipStreamSource,
496 /// The audio-return stream this device sources.
497 pub arc: V2ipStreamSource,
498
499 /// Encoder rate in units of 10Mb/s, or `None` when the sender offered no
500 /// rate.
501 ///
502 /// A rate-only write carries the rate on its own; every other controller
503 /// write puts a value outside the valid range here, which firmware drops as
504 /// invalid so that address-only and scaling writes leave the peer's rate
505 /// alone.
506 pub tx_rate: Option<u8>,
507
508 /// Per-stream DSCP marking.
509 pub dscp: V2ipDscpConfig,
510 /// Scaling mode, refresh rate and flags.
511 pub scaling: V2ipScalingSettings,
512}
513
514impl DeviceV2ipDetails {
515 /// Reports whether the source block carries usable addresses.
516 ///
517 /// Firmware requires video and anc; audio is optional and is carried with
518 /// them.
519 pub const fn source_is_valid(&self) -> bool {
520 self.video.is_valid() && self.anc.is_valid()
521 }
522
523 /// Folds a received device configuration onto the cached one.
524 ///
525 /// Every field is optional behind its own validity marker: the payload is
526 /// zeroed before a sender fills in the one field it is writing, so a
527 /// controller writing a TX rate sends zeroed addresses and a controller
528 /// writing addresses sends an out-of-range rate. Firmware applies each
529 /// field only behind its own test, so replacing the whole cached config on
530 /// every frame would make the peer read back with its addresses, rate or
531 /// marking gone.
532 #[must_use]
533 pub fn merge(mut self, previous: Option<Self>) -> Self {
534 let Some(previous) = previous else {
535 return self;
536 };
537 if !self.source_is_valid() {
538 self.video = previous.video;
539 self.audio = previous.audio;
540 self.anc = previous.anc;
541 }
542 if !self.arc.is_valid() {
543 self.arc = previous.arc;
544 }
545 if self.tx_rate.is_none() {
546 self.tx_rate = previous.tx_rate;
547 }
548 // Firmware gates all three dscp bytes on the video byte's set bit
549 // alone, and stores whatever the other two carry.
550 if self.dscp.video.is_none() {
551 self.dscp = previous.dscp;
552 }
553 self.scaling = self.scaling.merge(previous.scaling);
554 self
555 }
556}
557
558/// The sink-side route a V2IP device is subscribed to, as the mesh believes it.
559///
560/// A route request addressed to the device sets this the moment it is seen,
561/// which is what every device on the mesh does with one. So a request the
562/// device refused, or that reached it while it was offline, reads back here as
563/// though it had taken effect. Only the device's own configuration report
564/// confirms a route, and it sends that on its own schedule rather than in reply.
565///
566/// **Addresses that read as unset mean "no route, or the sink could not work
567/// one out" - never "definitely not subscribed".** This block is the one part
568/// of a device configuration with no validity marker of its own, so a sender
569/// with nothing to say sends zeros and every receiver stores them. A sender
570/// leaves it empty when its own stream configuration does not resolve, and that
571/// covers more than having no route: a selected source whose record has not
572/// arrived yet, which is the state after a restart at either end, missing audio
573/// bay configuration, or any of the three streams failing its validity check.
574/// The audio format has a second gate of its own, so it can be absent while the
575/// addresses are not.
576///
577/// This is worth expecting rather than guarding against. Any scaling change
578/// makes the device rebuild and rebroadcast this block - so the empty reading
579/// arrives most often during exactly the no-signal troubleshooting that
580/// prompted the change. A device's periodic report puts a real route back
581/// within a minute of it having one.
582///
583/// An empty reading is applied rather than ignored on purpose. A sink that has
584/// genuinely dropped its route sends the same zeros, and so does every report
585/// after it, so refusing them would cache a route that nothing later could ever
586/// clear.
587///
588/// A configuration frame sets this only when the device sent it about itself.
589/// A controller writing another device's configuration sends the block zeroed
590/// because it has nothing to say about that sink, so its frame is ignored here.
591#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
592pub struct DeviceV2ipSink {
593 /// The streams the sink subscribes to.
594 pub addresses: V2ipStreamSources,
595 /// The resolved audio format, when the sender reported one.
596 pub audio_fmt: Option<V2ipAudioFormat>,
597}
598
599/// The device settings of a V2IP unit, as it reports them and as its
600/// controller changes them.
601///
602/// Each setting is carried only behind its bit in [`valid`](Self::valid), so a
603/// frame changes one setting without restating the others, and a device
604/// reports only the settings it has. Read a setting through the accessors,
605/// which answer `None` for one the device has not reported.
606#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
607pub struct V2ipDeviceSettings {
608 /// The settings reported so far.
609 pub valid: V2ipDeviceSetting,
610 /// The values of the on/off settings among [`valid`](Self::valid).
611 pub flags: V2ipDeviceSetting,
612 /// The infrared profiles stored on the device, bit n for profile n.
613 pub ir_profiles: u32,
614 /// The infrared profile of the global infrared port.
615 pub ir_profile: i8,
616 /// The infrared profile of the output's infrared port, or
617 /// [`V2IP_IR_PROFILE_NOT_SET`] when it follows the global one.
618 pub ir_profile_sink: i8,
619}
620
621impl V2ipDeviceSettings {
622 /// Whether an on/off setting is on, `None` while the device has not
623 /// reported it.
624 pub const fn get(&self, setting: V2ipDeviceSetting) -> Option<bool> {
625 if !self.valid.has(setting) {
626 return None;
627 }
628 Some(self.flags.has(setting))
629 }
630
631 /// The global infrared port's profile, `None` while it is not reported.
632 pub const fn ir_profile(&self) -> Option<i8> {
633 if !self.valid.has(V2ipDeviceSetting::IR_PROFILE) {
634 return None;
635 }
636 Some(self.ir_profile)
637 }
638
639 /// The output infrared port's profile, `None` while it is not reported.
640 /// [`V2IP_IR_PROFILE_NOT_SET`] means the port follows the global one.
641 pub const fn ir_profile_sink(&self) -> Option<i8> {
642 if !self.valid.has(V2ipDeviceSetting::IR_PROFILE_SINK) {
643 return None;
644 }
645 Some(self.ir_profile_sink)
646 }
647
648 /// The infrared profiles stored on the device, bit n for profile n, `None`
649 /// while it is not reported.
650 pub const fn stored_ir_profiles(&self) -> Option<u32> {
651 if !self.valid.has(V2ipDeviceSetting::IR_PROFILES) {
652 return None;
653 }
654 Some(self.ir_profiles)
655 }
656
657 /// Folds a received settings block onto the cached one.
658 ///
659 /// Each bit in the frame's [`valid`](Self::valid) replaces its own setting
660 /// and leaves the others alone, so a write about one setting does not
661 /// clear what was known about the rest.
662 #[must_use]
663 pub(crate) fn merge(self, previous: Self) -> Self {
664 let valid = self.valid;
665 let mut out = previous;
666 out.valid |= valid;
667 out.flags = previous.flags.without(valid) | (self.flags & valid);
668 if valid.has(V2ipDeviceSetting::IR_PROFILE) {
669 out.ir_profile = self.ir_profile;
670 }
671 if valid.has(V2ipDeviceSetting::IR_PROFILE_SINK) {
672 out.ir_profile_sink = self.ir_profile_sink;
673 }
674 if valid.has(V2ipDeviceSetting::IR_PROFILES) {
675 out.ir_profiles = self.ir_profiles;
676 }
677 out
678 }
679
680 /// This block limited to what a device takes from a write about it.
681 ///
682 /// A device applies a setting only if it has it, a profile only within
683 /// its range, and never the list of stored profiles, which only it knows.
684 #[must_use]
685 pub(crate) fn as_applied_to(self, reported: V2ipDeviceSetting) -> Self {
686 let mut valid = (self.valid & reported).without(V2ipDeviceSetting::IR_PROFILES);
687 if !(0..V2IP_IR_PROFILE_MAX).contains(&self.ir_profile) {
688 valid = valid.without(V2ipDeviceSetting::IR_PROFILE);
689 }
690 if !(V2IP_IR_PROFILE_NOT_SET..V2IP_IR_PROFILE_MAX).contains(&self.ir_profile_sink) {
691 valid = valid.without(V2ipDeviceSetting::IR_PROFILE_SINK);
692 }
693 Self { valid, ..self }
694 }
695}
696
697/// Transmitter stream statistics.
698#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
699pub struct V2ipTxStats {
700 /// Video packets sent.
701 pub video: u32,
702 /// Audio packets sent.
703 pub audio: u32,
704 /// Ancillary-data packets sent.
705 pub anc: u32,
706 /// Times the stream went down.
707 pub stream_down: u32,
708 /// Transmit overflows.
709 pub overflow: u32,
710}
711
712/// The health state of a V2IP decoder.
713#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
714pub struct V2ipDecoderState(u8);
715
716impl V2ipDecoderState {
717 /// The sink has not reported a state.
718 pub const UNKNOWN: Self = Self(0);
719 /// Decoding normally.
720 pub const HEALTHY: Self = Self(1);
721 /// Failed to decode.
722 pub const BAD: Self = Self(2);
723 /// Still coming up, which any sink subscribed to during a route change
724 /// reports.
725 pub const STARTING: Self = Self(3);
726
727 /// Wraps a raw wire value, including one this library has no name for.
728 pub const fn from_wire(value: u8) -> Self {
729 Self(value)
730 }
731
732 /// Returns the raw wire value.
733 pub const fn to_wire(self) -> u8 {
734 self.0
735 }
736
737 /// Reports whether the decoder has reached a verdict.
738 ///
739 /// Only healthy and bad are verdicts. Testing for failure as "not healthy"
740 /// reads a receiver that is merely coming up as one that failed to decode,
741 /// which is what a sink reports for a moment after every route change.
742 pub const fn is_settled(self) -> bool {
743 matches!(self, Self::HEALTHY | Self::BAD)
744 }
745}
746
747impl fmt::Display for V2ipDecoderState {
748 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749 match *self {
750 Self::UNKNOWN => f.write_str("Unknown"),
751 Self::HEALTHY => f.write_str("Healthy"),
752 Self::BAD => f.write_str("Bad"),
753 Self::STARTING => f.write_str("Starting"),
754 Self(v) => write!(f, "state {v}"),
755 }
756 }
757}
758
759/// Receiver stream statistics.
760#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
761pub struct V2ipRxStats {
762 /// Video packets received.
763 pub video_total: u32,
764 /// Video packets dropped.
765 pub video_dropped: u32,
766 /// Video sequence errors.
767 pub video_seq_errors: u32,
768 /// Watchdog timeouts.
769 pub wdt_timeout: u32,
770 /// Audio packets received.
771 pub audio_total: u32,
772 /// Audio packets dropped.
773 pub audio_dropped: u32,
774 /// Audio sequence errors.
775 pub audio_seq_errors: u32,
776 /// Ancillary-data packets received.
777 pub anc_total: u32,
778 /// Ancillary-data packets dropped.
779 pub anc_dropped: u32,
780 /// Ancillary-data sequence errors.
781 pub anc_seq_errors: u32,
782 /// The decoder's health state.
783 pub decoder_state: V2ipDecoderState,
784}
785
786/// Why a decoder reports the state it does.
787///
788/// The primary cause only. Several causes can be true at once, and which of
789/// them lands here is a fixed priority order in the firmware that the numbering
790/// does not express: these values are identities, not ranks, and comparing or
791/// ordering them says nothing. Ask [`V2ipDecoderReport::has_cause`] whether a
792/// particular cause applies - a test against this field answers "is this the
793/// one that won" instead, which is a different question.
794///
795/// Firmware adds causes, so the wire value is carried as it arrived: folding an
796/// unrecognised one onto a named cause would report a fault this library
797/// invented. Appending one cannot reorder the existing priorities.
798#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
799pub struct V2ipDecoderReason(u8);
800
801impl V2ipDecoderReason {
802 /// Decoding normally.
803 pub const OK: Self = Self(0);
804 /// No packets are arriving.
805 pub const NO_PACKETS: Self = Self(1);
806 /// Packets are arriving, degraded.
807 pub const PACKETS_DEGRADED: Self = Self(2);
808 /// No format could be recovered from the codestream.
809 pub const NO_FORMAT: Self = Self(3);
810 /// The recovered format is not the one the sink is configured for.
811 pub const FORMAT_MISMATCH: Self = Self(4);
812 /// The configured output format was refused.
813 pub const FORMAT_REJECTED: Self = Self(5);
814 /// The converter watchdog is holding the stream back.
815 pub const DECODER_BLOCKED: Self = Self(6);
816 /// A source switch is in progress: a step in an operation someone asked
817 /// for, rather than a fault.
818 pub const SWITCH_PENDING: Self = Self(7);
819 /// PTP is unlocked. That costs audio alone; the picture is unaffected.
820 pub const PTP_UNLOCKED: Self = Self(8);
821 /// The pipeline is rebuilding after the HDMI transmitter stayed unlocked.
822 ///
823 /// The picture is down, and has been for five seconds before this can
824 /// appear: the sender debounces the unlocked reading for that long, so
825 /// this never reports a transient. Unlike [`Self::SWITCH_PENDING`] nobody
826 /// asked for it.
827 ///
828 /// The debounce restarts each time it elapses, so this holding across
829 /// reports is a restart loop rather than one event, and that is what to
830 /// escalate on.
831 ///
832 /// It sits near the bottom of the priority order, below every input-side
833 /// cause, so a rebuilding pipeline names one of those in
834 /// [`V2ipDecoderReport::reason`] and carries this in
835 /// [`V2ipDecoderReport::flags`] alone - always, rather than briefly.
836 ///
837 /// It is evaluated only while no format change is in progress. Across a
838 /// switch it holds its previous value and clears on the first reading
839 /// after the change settles, which [`V2ipDecoderReport::updates`] cannot
840 /// distinguish: a value carried forward is still a stored reading.
841 pub const TX_BRIDGE_UNLOCKED: Self = Self(9);
842 /// The sink is configured but switched off, so no stream is expected.
843 ///
844 /// This outranks every other cause: whenever it applies it is what
845 /// [`V2ipDecoderReport::reason`] carries.
846 ///
847 /// **The causes beneath it stay set in [`V2ipDecoderReport::flags`].** A
848 /// sink switched off while it was running keeps the bits the decoder
849 /// genuinely observed on the way down - no packets, no format - so a
850 /// classifier that tests a fault mask over the whole word calls a
851 /// deliberately disabled sink broken. Ask for this cause first and stop
852 /// there; the bits below it describe what was seen, not a fault to report.
853 ///
854 /// This says nothing about geometry, in either direction. The decoder
855 /// reports what it currently detects whatever the cause, so a switched-off
856 /// sink still detecting a codestream carries a real geometry, and a zero
857 /// one means the decoder has nothing rather than that the sink is off.
858 ///
859 /// Older senders never report this and give [`Self::NO_PACKETS`] for a
860 /// disabled sink instead, indistinguishable from one whose source has
861 /// died. So an absent [`Self::IDLE`] is not evidence a sink is enabled,
862 /// and **nothing in this block answers enablement**: it carries no such
863 /// field, and the answer comes from `V2IP_DEVICE_CFG` or the device's HTTP
864 /// status.
865 pub const IDLE: Self = Self(10);
866
867 /// Wraps a raw wire value, including one this library has no name for.
868 pub const fn from_wire(value: u8) -> Self {
869 Self(value)
870 }
871
872 /// Returns the raw wire value.
873 pub const fn to_wire(self) -> u8 {
874 self.0
875 }
876}
877
878impl fmt::Display for V2ipDecoderReason {
879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880 match *self {
881 Self::OK => f.write_str("ok"),
882 Self::NO_PACKETS => f.write_str("no packets"),
883 Self::PACKETS_DEGRADED => f.write_str("packets degraded"),
884 Self::NO_FORMAT => f.write_str("no format recovered"),
885 Self::FORMAT_MISMATCH => f.write_str("format mismatch"),
886 Self::FORMAT_REJECTED => f.write_str("format rejected"),
887 Self::DECODER_BLOCKED => f.write_str("decoder blocked"),
888 Self::SWITCH_PENDING => f.write_str("switch pending"),
889 Self::PTP_UNLOCKED => f.write_str("PTP unlocked"),
890 Self::TX_BRIDGE_UNLOCKED => f.write_str("TX bridge unlocked"),
891 Self::IDLE => f.write_str("idle"),
892 Self(v) => write!(f, "reason {v}"),
893 }
894 }
895}
896
897/// The colour space a decoder recovered from a codestream.
898///
899/// Zero is RGB and is also what a decoder with nothing to decode reports, so no
900/// value here means "no signal" - [`V2ipDecoderReport::has_geometry`] is what
901/// answers that.
902#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
903pub struct V2ipDecoderFormat(u16);
904
905impl V2ipDecoderFormat {
906 /// RGB.
907 pub const RGB: Self = Self(0);
908 /// YCbCr 4:4:4.
909 pub const YCBCR_444: Self = Self(1);
910 /// YCbCr 4:2:2.
911 pub const YCBCR_422: Self = Self(2);
912 /// YCbCr 4:2:0.
913 pub const YCBCR_420: Self = Self(3);
914 /// The decoder cannot name the format.
915 ///
916 /// 255, which is a value of its own rather than the 0xF a signal report
917 /// uses for an unknown colour space. Mapping one onto the other yields a
918 /// colour space the decoder never reported.
919 pub const UNNAMED: Self = Self(255);
920
921 /// Wraps a raw wire value, including one this library has no name for.
922 pub const fn from_wire(value: u16) -> Self {
923 Self(value)
924 }
925
926 /// Returns the raw wire value.
927 pub const fn to_wire(self) -> u16 {
928 self.0
929 }
930}
931
932impl fmt::Display for V2ipDecoderFormat {
933 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
934 match *self {
935 Self::RGB => f.write_str("RGB"),
936 Self::YCBCR_444 => f.write_str("YCbCr 4:4:4"),
937 Self::YCBCR_422 => f.write_str("YCbCr 4:2:2"),
938 Self::YCBCR_420 => f.write_str("YCbCr 4:2:0"),
939 Self::UNNAMED => f.write_str("unnamed"),
940 Self(v) => write!(f, "format {v}"),
941 }
942 }
943}
944
945/// What a sink's decoder recovered from the codestream it is being given.
946///
947/// This is what the decoder understood, read ahead of the scaler: the geometry
948/// is unrounded and is not what the display is being sent. It separates "the
949/// decoder understood the codestream" from "a picture came out the other end".
950///
951/// Colour depth is absent on purpose and will stay absent. The video processor
952/// answers that one from a driver constant rather than from the codestream, so
953/// there is no reading to carry; assert depth at the encoder's input bay
954/// instead.
955#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
956pub struct V2ipDecoderReport {
957 /// The primary cause of the state the decoder is in.
958 pub reason: V2ipDecoderReason,
959 /// The converter watchdog is holding the stream back.
960 pub blocking: bool,
961 /// The recovered picture width, and 0 when none was recovered.
962 pub width: u16,
963 /// The recovered picture height, and 0 when none was recovered.
964 pub height: u16,
965 /// The recovered colour space.
966 pub format: V2ipDecoderFormat,
967 /// How many readings the sink has stored. Monotonic, wrapping at 65535
968 /// after some 36 hours, and never reset.
969 ///
970 /// A sink reads its video processor every two seconds and reports every
971 /// second, so roughly every other report repeats a reading already seen:
972 /// a frame arriving says nothing about how fresh the values in it are.
973 /// This counter moves only when a reading is stored, so a processor that
974 /// stopped answering leaves it still rather than implying a refresh.
975 ///
976 /// After pointing a sink at something else, wait for this to advance by
977 /// two before trusting the geometry. It ticks when a reply lands rather
978 /// than when a query is sent, so the first tick can carry an answer the
979 /// processor read fractionally before the switch; the second cannot,
980 /// because at most one query is outstanding at a time.
981 pub updates: u16,
982 /// Every cause that applies, as bit N for reason N. See
983 /// [`Self::has_cause`].
984 ///
985 /// This is what to classify on, once [`V2ipDecoderReason::IDLE`] has been
986 /// ruled out: that cause outranks the whole word and leaves the bits below
987 /// it set, so a fault mask over `flags` reports a switched-off sink as
988 /// broken. [`Self::reason`] carries whichever cause won a fixed priority
989 /// contest, so a cause that is true can be absent from it while present
990 /// here. Bit 0 is cleared by the sender, so an empty word means nothing
991 /// beyond the primary cause applies.
992 ///
993 /// [`V2ipDecoderReason::NO_FORMAT`] and
994 /// [`V2ipDecoderReason::FORMAT_MISMATCH`] are the two arms of one decision
995 /// and never appear together.
996 pub flags: u32,
997 /// How many times the converter watchdog has triggered.
998 pub blocked_count: u32,
999}
1000
1001impl V2ipDecoderReport {
1002 /// Reports whether the decoder recovered a geometry.
1003 ///
1004 /// This is what says whether the decoder is being given a codestream it
1005 /// understands. [`Self::format`] cannot: it reads
1006 /// [`V2ipDecoderFormat::RGB`] when nothing is arriving, which is
1007 /// indistinguishable from a real RGB reading.
1008 ///
1009 /// It answers that and nothing else. The reading is taken before any cause
1010 /// is decided, so it does not say whether the sink is switched on: a sink
1011 /// that is off can still detect a codestream, and one that is on can
1012 /// detect nothing.
1013 pub const fn has_geometry(&self) -> bool {
1014 self.width != 0 && self.height != 0
1015 }
1016
1017 /// Reports whether `reason` is among the causes that apply.
1018 ///
1019 /// [`Self::reason`] carries the primary cause and `flags` carries all of
1020 /// them at once. Bit 0 is unused, so [`V2ipDecoderReason::OK`] is never
1021 /// among them and an empty word means nothing beyond the primary cause
1022 /// applies.
1023 pub const fn has_cause(&self, reason: V2ipDecoderReason) -> bool {
1024 let bit = reason.to_wire();
1025 bit > 0 && bit < u32::BITS as u8 && self.flags & (1 << bit) != 0
1026 }
1027}
1028
1029/// What a statistics report says about the sink's decoder.
1030///
1031/// The three states are distinct answers and only [`Self::Answered`] carries a
1032/// reading. `valid` follows the sink being configured rather than the sink
1033/// being enabled, so a sink that is switched off still reports: as
1034/// [`V2ipDecoderReason::IDLE`], or from an older sender as
1035/// [`V2ipDecoderReason::NO_PACKETS`], which is the same reading a sink whose
1036/// source has died produces.
1037#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1038pub enum V2ipDecoderDetail {
1039 /// The report carried no decoder block: the sender's firmware predates it.
1040 #[default]
1041 Absent,
1042 /// The block is there and the decoder has never answered. Every field it
1043 /// would carry is meaningless, so none is offered.
1044 NeverAnswered,
1045 /// A reading.
1046 Answered(V2ipDecoderReport),
1047}
1048
1049impl V2ipDecoderDetail {
1050 /// The reading, for a caller that treats both of the other states as
1051 /// "nothing to show".
1052 pub const fn reading(self) -> Option<V2ipDecoderReport> {
1053 match self {
1054 Self::Answered(report) => Some(report),
1055 _ => None,
1056 }
1057 }
1058}
1059
1060/// The cumulative and per-minute transmit and receive statistics.
1061#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1062pub struct V2ipDeviceStats {
1063 /// Transmit totals since boot.
1064 pub tx: V2ipTxStats,
1065 /// Transmit counts over the last minute.
1066 pub tx_per_minute: V2ipTxStats,
1067 /// Receive totals since boot.
1068 pub rx: V2ipRxStats,
1069 /// Receive counts over the last minute.
1070 pub rx_per_minute: V2ipRxStats,
1071 /// What the sink's decoder recovered from the codestream it is decoding.
1072 pub decoder: V2ipDecoderDetail,
1073}