Skip to main content

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, V2ipPowerSaveLevel, V2ipPtpFlag,
11    V2ipPtpLock, V2ipPtpMode, V2ipSdpClockMode, V2ipSdpClockState, V2ipSdpEncoding, V2ipSdpFlag,
12    V2ipSdpMediaClock, V2ipSdpRefClock, V2ipTestPattern, V2ipTestcardFlag, V2ipToneMode,
13    V2ipVlanFlag, V2IP_AUDIO_DEFAULT_CHANNELS, V2IP_AUDIO_DEFAULT_SAMPLE_RATE, V2IP_DSCP_MAX,
14    V2IP_DSCP_SET, V2IP_IR_PROFILE_MAX, V2IP_IR_PROFILE_NOT_SET,
15};
16
17/// Which of a V2IP device's streams an address describes.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum StreamKind {
20    /// The video stream.
21    #[default]
22    Video,
23    /// The audio stream.
24    Audio,
25    /// The ancillary-data stream.
26    Anc,
27    /// The audio-return stream.
28    Arc,
29}
30
31impl fmt::Display for StreamKind {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.write_str(match self {
34            Self::Video => "video",
35            Self::Audio => "audio",
36            Self::Anc => "anc",
37            Self::Arc => "arc",
38        })
39    }
40}
41
42/// A single multicast stream address.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct V2ipStreamSource {
45    /// Which stream this address is for.
46    pub kind: StreamKind,
47    /// The multicast group.
48    pub ip: Ipv4Addr,
49    /// The destination UDP port.
50    pub port: u16,
51}
52
53impl Default for V2ipStreamSource {
54    fn default() -> Self {
55        Self {
56            kind: StreamKind::default(),
57            ip: Ipv4Addr::UNSPECIFIED,
58            port: 0,
59        }
60    }
61}
62
63impl V2ipStreamSource {
64    /// Reports whether this carries a usable address: a multicast group and a
65    /// non-zero port, both, matching firmware `mxr_v2ip_stream_valid`.
66    pub const fn is_valid(&self) -> bool {
67        self.ip.is_multicast() && self.port != 0
68    }
69}
70
71impl fmt::Display for V2ipStreamSource {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        write!(f, "{}={}:{}", self.kind, self.ip, self.port)
74    }
75}
76
77/// The streams advertised by a single V2IP source.
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
79pub struct V2ipStreamSources {
80    /// The originating device, or the zero UID when it is not known.
81    pub uid: DeviceUid,
82    /// The video stream.
83    pub video: V2ipStreamSource,
84    /// The audio stream.
85    pub audio: V2ipStreamSource,
86    /// The ancillary-data stream.
87    pub anc: V2ipStreamSource,
88    /// The audio-return stream, when one is advertised.
89    pub arc: Option<V2ipStreamSource>,
90}
91
92impl fmt::Display for V2ipStreamSources {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        write!(
95            f,
96            "video:{} audio:{} anc:{}",
97            self.video, self.audio, self.anc
98        )
99    }
100}
101
102/// One multicast destination in a route the caller assembles.
103///
104/// The unspecified address sends the slot zeroed, naming no group for that
105/// stream. It is not a way to leave one stream alone: the firmware decides
106/// whether a sink has a manual route at all by reading the video and
107/// ancillary slots, so an empty one of those disqualifies the whole route
108/// rather than preserving anything - see
109/// [`crate::Remote::select_source_addr`].
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct V2ipRouteTarget {
112    /// The multicast group.
113    pub ip: Ipv4Addr,
114    /// The destination UDP port. Zero means the standard port for the stream
115    /// this target is given as.
116    pub port: u16,
117}
118
119impl Default for V2ipRouteTarget {
120    fn default() -> Self {
121        Self {
122            ip: Ipv4Addr::UNSPECIFIED,
123            port: 0,
124        }
125    }
126}
127
128impl V2ipRouteTarget {
129    /// A target at the standard port for its stream.
130    pub const fn new(ip: Ipv4Addr) -> Self {
131        Self { ip, port: 0 }
132    }
133
134    /// The port to send, substituting `standard` for an unset one.
135    pub(crate) const fn port_or(self, standard: u16) -> u16 {
136        if self.port == 0 {
137            standard
138        } else {
139            self.port
140        }
141    }
142}
143
144impl fmt::Display for V2ipRouteTarget {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        write!(f, "{}:{}", self.ip, self.port)
147    }
148}
149
150/// The three streams a manual route points a V2IP sink at.
151///
152/// Fill in all three. The firmware decides whether a sink has a manual route
153/// at all by looking at the video and ancillary groups, so a route carrying
154/// only audio does not register as one and the sink falls back to the audio
155/// source its mesh picks.
156#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
157pub struct V2ipRoute {
158    /// The video stream, at [`crate::V2IP_PORT_VIDEO`] unless the port says otherwise.
159    pub video: V2ipRouteTarget,
160    /// The audio stream, at [`crate::V2IP_PORT_AUDIO`] unless the port says otherwise.
161    pub audio: V2ipRouteTarget,
162    /// The ancillary-data stream, at [`crate::V2IP_PORT_ANC`] unless the port says
163    /// otherwise.
164    pub anc: V2ipRouteTarget,
165}
166
167impl V2ipRoute {
168    /// The three streams of one source, at the ports it advertises them on.
169    pub fn of(sources: &V2ipStreamSources) -> Self {
170        let target = |s: &V2ipStreamSource| V2ipRouteTarget {
171            ip: s.ip,
172            port: s.port,
173        };
174        Self {
175            video: target(&sources.video),
176            audio: target(&sources.audio),
177            anc: target(&sources.anc),
178        }
179    }
180}
181
182impl fmt::Display for V2ipRoute {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        write!(
185            f,
186            "video:{} audio:{} anc:{}",
187            self.video, self.audio, self.anc
188        )
189    }
190}
191
192/// The sample rate and channel count a V2IP audio stream is decoded at.
193///
194/// Fill both in. The firmware header calls zero "use the default", but the
195/// path that applies a manual route substitutes nothing: it hands the pair to
196/// the FPGA as it arrived, and the FPGA rejects a zero rate and takes the
197/// whole switch down with it. [`V2ipAudioFormat::STANDARD`] is the pair the
198/// header documents as the default.
199#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
200pub struct V2ipAudioFormat {
201    /// Sample rate in Hz.
202    pub sample_rate: u32,
203    /// Channel count.
204    pub channels: u8,
205}
206
207impl V2ipAudioFormat {
208    /// 48kHz stereo: the rate and channel count the firmware header names as
209    /// its default, which a caller has to send because firmware does not
210    /// substitute it.
211    pub const STANDARD: Self = Self {
212        sample_rate: V2IP_AUDIO_DEFAULT_SAMPLE_RATE,
213        channels: V2IP_AUDIO_DEFAULT_CHANNELS,
214    };
215
216    /// Encodes `v2ip_audio_format`: a `u32` rate, a channel byte and three
217    /// reserved bytes, padded to the struct's 8-byte alignment.
218    pub(crate) fn wire(&self) -> [u8; 8] {
219        let r = self.sample_rate.to_le_bytes();
220        [r[0], r[1], r[2], r[3], self.channels, 0, 0, 0]
221    }
222}
223
224impl fmt::Display for V2ipAudioFormat {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        write!(f, "{}Hz/{}ch", self.sample_rate, self.channels)
227    }
228}
229
230/// A V2IP output's scaling mode, refresh rate and flags.
231#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
232pub struct V2ipScalingSettings {
233    /// The signal type the output scales to.
234    pub mode: MxrSignalType,
235    /// Refresh rate in Hz.
236    pub refresh: u16,
237    /// The flag bits below.
238    pub flags: u8,
239}
240
241/// Set when the frame carries a scaling mode and refresh rate.
242pub const SCALING_FLAG_MODE_VALID: u8 = 1 << 0;
243
244/// Set when the frame carries the scaling options.
245pub const SCALING_FLAG_OPTIONS_VALID: u8 = 1 << 1;
246
247/// Set when the frame carries the second group of scaling options.
248///
249/// Firmware that has those options sets this on every configuration it sends
250/// about itself, so it doubles as the report that the device has them at all.
251pub const SCALING_FLAG_OPTIONS2_VALID: u8 = 1 << 4;
252
253/// Set when the output follows its source's format instead of a fixed one.
254pub const SCALING_FLAG_MATCH_SOURCE: u8 = 1 << 5;
255
256/// Set when the output declines 4:2:0 rather than scaling it.
257pub const SCALING_FLAG_SKIP_420: u8 = 1 << 6;
258
259/// Set when the output scales automatically.
260pub const SCALING_FLAG_AUTO_SCALING: u8 = 1 << 7;
261
262/// The flag bits that carry meaning.
263///
264/// Bits 2 and 3 have no meaning and are excluded: they are not reliably zero
265/// on the wire, because firmware that does not initialise the configuration it
266/// broadcasts builds this frame from an uninitialised stack local and ORs its
267/// flags onto whatever was there. The same is true of every bit here on such a
268/// sender, which is why each reading below says what it rests on.
269pub const SCALING_FLAGS_DEFINED: u8 = SCALING_FLAG_MODE_VALID
270    | SCALING_FLAG_OPTIONS_VALID
271    | SCALING_FLAG_OPTIONS2_VALID
272    | SCALING_FLAG_MATCH_SOURCE
273    | SCALING_FLAG_SKIP_420
274    | SCALING_FLAG_AUTO_SCALING;
275
276/// Lowest refresh rate a V2IP output stage accepts, in Hz.
277///
278/// A receiver replaces anything outside
279/// [`V2IP_SCALING_REFRESH_MIN`]..=[`V2IP_SCALING_REFRESH_MAX`] with 50 rather
280/// than refusing the write, so 0 asks for 50Hz here instead of asking for
281/// nothing.
282pub const V2IP_SCALING_REFRESH_MIN: u16 = 24;
283
284/// Highest refresh rate a V2IP output stage accepts, in Hz. See
285/// [`V2IP_SCALING_REFRESH_MIN`].
286pub const V2IP_SCALING_REFRESH_MAX: u16 = 120;
287
288/// The output format to scale a V2IP sink to.
289///
290/// Built from a depth and a colour space rather than from a packed signal-type
291/// word, so the word a caller sends cannot carry the unset bpp index a sink
292/// reports while it has no mode configured.
293#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
294pub struct V2ipOutputMode {
295    /// The CTA-861 short video descriptor to output.
296    pub svd: u8,
297    /// Bit depth: 8, 10 or 12.
298    pub depth: u8,
299    /// The colour space to output.
300    pub colour: V2ipColourSpace,
301    /// Refresh rate in Hz, [`V2IP_SCALING_REFRESH_MIN`] to
302    /// [`V2IP_SCALING_REFRESH_MAX`].
303    pub refresh: u16,
304}
305
306impl V2ipOutputMode {
307    /// Reports whether a sink will take this mode, or why it will not.
308    ///
309    /// Checked here because a sink checks it and then says nothing: every value
310    /// this rejects is one the receiver decodes cleanly and drops, leaving a
311    /// caller with a send that succeeded and a setting that did not move.
312    ///
313    /// Passing is not a guarantee. A sink also weighs the format against the
314    /// EDID of the display attached to it and against what its own clock and
315    /// output stage can produce, and none of that is knowable from here.
316    pub fn validate(&self) -> Result<(), &'static str> {
317        if self.svd == 0 {
318            return Err("svd 0 is how a mode is cleared, not a mode to set");
319        }
320        if crate::lookup_svd(u16::from(self.svd)).is_none() {
321            return Err("the svd names no known video descriptor");
322        }
323        if MxrSignalType::bpp_index_for_depth(self.depth).is_none() {
324            return Err("a V2IP output stage takes 8, 10 or 12 bits per pixel");
325        }
326        if self.colour > V2ipColourSpace::YCBCR420 {
327            return Err("the colour space names none of RGB, 4:4:4, 4:2:2 or 4:2:0");
328        }
329        if !(V2IP_SCALING_REFRESH_MIN..=V2IP_SCALING_REFRESH_MAX).contains(&self.refresh) {
330            return Err("the refresh rate is outside 24..=120Hz");
331        }
332        Ok(())
333    }
334
335    /// The packed signal type a scaling write carries for this mode.
336    ///
337    /// Call [`V2ipOutputMode::validate`] first: an unvalidated depth packs as
338    /// the index for "no depth", which a receiver drops.
339    pub(crate) fn to_signal_type(self) -> MxrSignalType {
340        MxrSignalType::from_parts(
341            self.svd,
342            self.colour.to_wire(),
343            MxrSignalType::bpp_index_for_depth(self.depth).unwrap_or(0),
344        )
345    }
346}
347
348impl fmt::Display for V2ipOutputMode {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        write!(
351            f,
352            "svd {}, colour {}, {}bpp, {}Hz",
353            self.svd,
354            self.colour.to_wire(),
355            self.depth,
356            self.refresh
357        )
358    }
359}
360
361impl V2ipScalingSettings {
362    /// The mode this sink is configured to scale to, `None` when it has none.
363    ///
364    /// The two are distinct on the wire: a sink with no mode configured leaves
365    /// [`SCALING_FLAG_MODE_VALID`] clear, and never sets it over a zero mode.
366    ///
367    /// Trust it only where the sender reports
368    /// [`crate::DeviceInfo::config_initialised`]. Firmware without that builds
369    /// this block over uninitialised stack, where the valid bit itself is
370    /// noise.
371    pub const fn configured_mode(&self) -> Option<(MxrSignalType, u16)> {
372        if self.flags & SCALING_FLAG_MODE_VALID == 0 {
373            return None;
374        }
375        Some((self.mode, self.refresh))
376    }
377
378    /// Whether the output scales automatically, `None` when the sender did not
379    /// say.
380    pub const fn auto_scaling(&self) -> Option<bool> {
381        if self.flags & SCALING_FLAG_OPTIONS_VALID == 0 {
382            return None;
383        }
384        Some(self.flags & SCALING_FLAG_AUTO_SCALING != 0)
385    }
386
387    /// Whether the output follows its source's format, `None` when the device
388    /// has never said.
389    ///
390    /// Firmware with this option announces it on every configuration it sends
391    /// about itself, so a device that has reported it once is known to have
392    /// it. The cached block accumulates its validity bits, so a later write
393    /// carrying only the first options group does not take that back.
394    ///
395    /// Reported only from a sender announcing
396    /// [`crate::DeviceInfo::config_initialised`], so this needs no caveat of
397    /// its own: no firmware has these options without that announcement, and
398    /// one that lacks it would be reporting uninitialised stack. That is the
399    /// difference from [`Self::configured_mode`], which is reported from any
400    /// sender because a mode can be genuine on one of those.
401    pub const fn match_source(&self) -> Option<bool> {
402        if self.flags & SCALING_FLAG_OPTIONS2_VALID == 0 {
403            return None;
404        }
405        Some(self.flags & SCALING_FLAG_MATCH_SOURCE != 0)
406    }
407
408    /// Whether the output declines 4:2:0 rather than scaling it, `None` when
409    /// the device has never said. Reported on the same terms as
410    /// [`Self::match_source`], which shares its validity bit.
411    pub const fn skip_420(&self) -> Option<bool> {
412        if self.flags & SCALING_FLAG_OPTIONS2_VALID == 0 {
413            return None;
414        }
415        Some(self.flags & SCALING_FLAG_SKIP_420 != 0)
416    }
417
418    /// Folds a received scaling config onto the cached one, field by field.
419    ///
420    /// A write carries the mode or the options alone, so taking the block
421    /// wholesale would drop whichever half was not being written. The options
422    /// branch replaces the option bit rather than adding to it, which is what
423    /// lets an options-only write clear [`SCALING_FLAG_AUTO_SCALING`].
424    #[must_use]
425    pub fn merge(self, previous: Self) -> Self {
426        let mut out = previous;
427        if self.flags & SCALING_FLAG_MODE_VALID != 0 {
428            out.mode = self.mode;
429            out.refresh = self.refresh;
430            out.flags |= SCALING_FLAG_MODE_VALID;
431        }
432        if self.flags & SCALING_FLAG_OPTIONS_VALID != 0 {
433            out.flags &= !SCALING_FLAG_AUTO_SCALING;
434            out.flags |= SCALING_FLAG_OPTIONS_VALID;
435            out.flags |= self.flags & SCALING_FLAG_AUTO_SCALING;
436        }
437        // One validity bit covers both options in this group, so a frame
438        // carrying it replaces both and a frame without it leaves both alone -
439        // which is also what keeps the bit itself, and so the knowledge that
440        // the device has these options, from being taken back by a later write
441        // that carries only the first group.
442        if self.flags & SCALING_FLAG_OPTIONS2_VALID != 0 {
443            out.flags &= !(SCALING_FLAG_MATCH_SOURCE | SCALING_FLAG_SKIP_420);
444            out.flags |= SCALING_FLAG_OPTIONS2_VALID;
445            out.flags |= self.flags & (SCALING_FLAG_MATCH_SOURCE | SCALING_FLAG_SKIP_420);
446        }
447        out
448    }
449}
450
451/// The per-stream DSCP marking in a V2IP device configuration.
452///
453/// A stream whose wire byte carries no [`V2IP_DSCP_SET`] bit reads back as
454/// `None`. Firmware treats the marking as all-or-nothing: it applies one only
455/// when all three streams carry a value and otherwise falls back to the
456/// default, so [`V2ipDscpConfig::is_complete`] reports which case a frame is in.
457#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
458pub struct V2ipDscpConfig {
459    /// Marking for the video stream.
460    pub video: Option<u8>,
461    /// Marking for the audio stream.
462    pub audio: Option<u8>,
463    /// Marking for the ancillary-data stream.
464    pub anc: Option<u8>,
465}
466
467impl V2ipDscpConfig {
468    /// Reports whether all three streams carry a marking, which is what
469    /// firmware requires before it applies one.
470    pub const fn is_complete(&self) -> bool {
471        self.video.is_some() && self.audio.is_some() && self.anc.is_some()
472    }
473}
474
475impl fmt::Display for V2ipDscpConfig {
476    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477        match (self.video, self.audio, self.anc) {
478            (Some(v), Some(a), Some(n)) => write!(f, "video:{v} audio:{a} anc:{n}"),
479            _ => f.write_str("no marking"),
480        }
481    }
482}
483
484/// Decodes one `dscp` byte, or `None` when the byte carries no marking.
485pub(crate) fn parse_dscp(raw: u8) -> Option<u8> {
486    (raw & V2IP_DSCP_SET != 0).then_some(raw & V2IP_DSCP_MAX)
487}
488
489/// The local encoder/decoder configuration of a V2IP device.
490#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
491pub struct DeviceV2ipDetails {
492    /// The video stream this device sources.
493    pub video: V2ipStreamSource,
494    /// The audio stream this device sources.
495    pub audio: V2ipStreamSource,
496    /// The ancillary-data stream this device sources.
497    pub anc: V2ipStreamSource,
498    /// The audio-return stream this device sources.
499    pub arc: V2ipStreamSource,
500
501    /// Encoder rate in units of 10Mb/s, or `None` when the sender offered no
502    /// rate.
503    ///
504    /// A rate-only write carries the rate on its own; every other controller
505    /// write puts a value outside the valid range here, which firmware drops as
506    /// invalid so that address-only and scaling writes leave the peer's rate
507    /// alone.
508    pub tx_rate: Option<u8>,
509
510    /// Per-stream DSCP marking.
511    pub dscp: V2ipDscpConfig,
512    /// Scaling mode, refresh rate and flags.
513    pub scaling: V2ipScalingSettings,
514}
515
516impl DeviceV2ipDetails {
517    /// Reports whether the source block carries usable addresses.
518    ///
519    /// Firmware requires video and anc; audio is optional and is carried with
520    /// them.
521    pub const fn source_is_valid(&self) -> bool {
522        self.video.is_valid() && self.anc.is_valid()
523    }
524
525    /// Folds a received device configuration onto the cached one.
526    ///
527    /// Every field is optional behind its own validity marker: the payload is
528    /// zeroed before a sender fills in the one field it is writing, so a
529    /// controller writing a TX rate sends zeroed addresses and a controller
530    /// writing addresses sends an out-of-range rate. Firmware applies each
531    /// field only behind its own test, so replacing the whole cached config on
532    /// every frame would make the peer read back with its addresses, rate or
533    /// marking gone.
534    #[must_use]
535    pub fn merge(mut self, previous: Option<Self>) -> Self {
536        let Some(previous) = previous else {
537            return self;
538        };
539        if !self.source_is_valid() {
540            self.video = previous.video;
541            self.audio = previous.audio;
542            self.anc = previous.anc;
543        }
544        if !self.arc.is_valid() {
545            self.arc = previous.arc;
546        }
547        if self.tx_rate.is_none() {
548            self.tx_rate = previous.tx_rate;
549        }
550        // A unit keeps the markings only when all three carry their set bit.
551        if !self.dscp.is_complete() {
552            self.dscp = previous.dscp;
553        }
554        self.scaling = self.scaling.merge(previous.scaling);
555        self
556    }
557}
558
559/// The sink-side route a V2IP device is subscribed to, as the mesh believes it.
560///
561/// A route request addressed to the device sets this the moment it is seen,
562/// which is what every device on the mesh does with one. So a request the
563/// device refused, or that reached it while it was offline, reads back here as
564/// though it had taken effect. Only the device's own configuration report
565/// confirms a route, and it sends that on its own schedule rather than in reply.
566///
567/// **Addresses that read as unset mean "no route, or the sink could not work
568/// one out" - never "definitely not subscribed".** This block is the one part
569/// of a device configuration with no validity marker of its own, so a sender
570/// with nothing to say sends zeros and every receiver stores them. A sender
571/// leaves it empty when its own stream configuration does not resolve, and that
572/// covers more than having no route: a selected source whose record has not
573/// arrived yet, which is the state after a restart at either end, missing audio
574/// bay configuration, or any of the three streams failing its validity check.
575/// The audio format has a second gate of its own, so it can be absent while the
576/// addresses are not.
577///
578/// This is worth expecting rather than guarding against. Any scaling change
579/// makes the device rebuild and rebroadcast this block - so the empty reading
580/// arrives most often during exactly the no-signal troubleshooting that
581/// prompted the change. A device's periodic report puts a real route back
582/// within a minute of it having one.
583///
584/// An empty reading is applied rather than ignored on purpose. A sink that has
585/// genuinely dropped its route sends the same zeros, and so does every report
586/// after it, so refusing them would cache a route that nothing later could ever
587/// clear.
588///
589/// A configuration frame sets this only when the device sent it about itself.
590/// A controller writing another device's configuration sends the block zeroed
591/// because it has nothing to say about that sink, so its frame is ignored here.
592#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
593pub struct DeviceV2ipSink {
594    /// The streams the sink subscribes to.
595    pub addresses: V2ipStreamSources,
596    /// The resolved audio format, when the sender reported one.
597    pub audio_fmt: Option<V2ipAudioFormat>,
598}
599
600/// The highest PTP domain a V2IP device runs in.
601pub const V2IP_PTP_DOMAIN_MAX: u8 = 127;
602
603/// Minutes in a day: every time in a [`V2ipPowerSaveSchedule`] is below this.
604pub const V2IP_MINUTES_PER_DAY: u16 = 24 * 60;
605
606/// A V2IP device's daily power save windows, Monday first, in the device's
607/// time zone.
608///
609/// Day `d` powers down at `start[d]` and up again at `end[d]`, both in minutes
610/// after midnight. A window belongs to the day it starts on and runs past
611/// midnight into the next when it ends before it starts; one that ends where it
612/// starts means no window that day.
613#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
614pub struct V2ipPowerSaveSchedule {
615    /// When each day's window starts.
616    pub start: [u16; 7],
617    /// When each day's window ends.
618    pub end: [u16; 7],
619}
620
621impl V2ipPowerSaveSchedule {
622    /// The window of day `day`, Monday being 0, or `None` for a day without
623    /// one or past Sunday.
624    pub fn window(&self, day: usize) -> Option<(u16, u16)> {
625        let (start, end) = (*self.start.get(day)?, *self.end.get(day)?);
626        (start != end).then_some((start, end))
627    }
628
629    /// Whether every time is a time of day.
630    pub fn is_valid(&self) -> bool {
631        self.start
632            .iter()
633            .chain(&self.end)
634            .all(|m| *m < V2IP_MINUTES_PER_DAY)
635    }
636}
637
638/// The device settings of a V2IP unit, as it reports them and as its
639/// controller changes them.
640///
641/// Each setting is carried only behind its bit in [`valid`](Self::valid), so a
642/// frame changes one setting without restating the others, and a device
643/// reports only the settings it has. Read a setting through the accessors,
644/// which answer `None` for one the device has not reported.
645#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
646pub struct V2ipDeviceSettings {
647    /// The settings reported so far.
648    pub valid: V2ipDeviceSetting,
649    /// The values of the on/off settings among [`valid`](Self::valid).
650    pub flags: V2ipDeviceSetting,
651    /// The infrared profiles stored on the device, bit n for profile n.
652    pub ir_profiles: u32,
653    /// The infrared profile of the global infrared port.
654    pub ir_profile: i8,
655    /// The infrared profile of the output's infrared port, or
656    /// [`V2IP_IR_PROFILE_NOT_SET`] when it follows the global one.
657    pub ir_profile_sink: i8,
658    /// The minutes the device stays idle before it powers down by itself, 0
659    /// for never.
660    pub auto_power_save: u16,
661    /// The daily windows in which the device powers down.
662    pub power_save: V2ipPowerSaveSchedule,
663    /// The PTP mode the device runs.
664    pub ptp_mode: V2ipPtpMode,
665    /// The PTP domain the device runs in, up to [`V2IP_PTP_DOMAIN_MAX`].
666    pub ptp_domain: u8,
667    /// The priority1 the device announces as a PTP grandmaster, lower winning.
668    pub ptp_priority1: u8,
669    /// The level the device powers down to in power save. While
670    /// [`POWER_SAVE_DISABLED`](V2ipDeviceSetting::POWER_SAVE_DISABLED) is on,
671    /// the level a power save request powers it down to.
672    pub power_save_level: V2ipPowerSaveLevel,
673    /// The device's PTP message settings.
674    pub ptp_messages: V2ipPtpMessages,
675}
676
677/// How a V2IP device paces its PTP messages, its SAP timings and its streams'
678/// TTL, which a frame carries in the same block. Each value is behind its own bit of
679/// [`V2ipDeviceSettings::valid`], one of
680/// [`SETTINGS_BLOCK`](V2ipDeviceSetting::SETTINGS_BLOCK).
681///
682/// Intervals are base-2 logarithms of seconds, so -3 is 125 ms and 1 is 2 s.
683#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
684pub struct V2ipPtpMessages {
685    /// Between announce messages, behind
686    /// [`PTP_ANNOUNCE`](V2ipDeviceSetting::PTP_ANNOUNCE).
687    pub log_announce_interval: i8,
688    /// Between sync messages, behind [`PTP_SYNC`](V2ipDeviceSetting::PTP_SYNC).
689    pub log_sync_interval: i8,
690    /// Between delay requests, behind
691    /// [`PTP_DELAY_REQ`](V2ipDeviceSetting::PTP_DELAY_REQ).
692    pub log_delay_req_interval: i8,
693    /// The announce intervals before a silent master is dropped, behind
694    /// [`PTP_ANNOUNCE_TIMEOUT`](V2ipDeviceSetting::PTP_ANNOUNCE_TIMEOUT).
695    pub announce_timeout: u8,
696    /// The DSCP of the messages, at most [`V2IP_DSCP_MAX`], behind
697    /// [`PTP_DSCP`](V2ipDeviceSetting::PTP_DSCP).
698    pub dscp: u8,
699    /// The minutes after which a SAP announcement the device heard is
700    /// forgotten, behind [`SAP_EXPIRE`](V2ipDeviceSetting::SAP_EXPIRE).
701    pub sap_expire_min: u8,
702    /// The seconds between the device's SAP announcements, behind
703    /// [`SAP_INTERVAL`](V2ipDeviceSetting::SAP_INTERVAL).
704    pub sap_interval_s: u16,
705    /// The TTL of the device's streams, 1 to 255, behind
706    /// [`STREAM_TTL`](V2ipDeviceSetting::STREAM_TTL). A device whose video
707    /// processor cannot change it keeps the setting and sends
708    /// [`V2IP_STREAM_TTL_DEFAULT`].
709    pub stream_ttl: u8,
710}
711
712/// The TTL a V2IP device's streams carry until it is set.
713pub const V2IP_STREAM_TTL_DEFAULT: u8 = 64;
714
715impl V2ipPtpMessages {
716    /// The values behind the bits of `which` copied from `from`, the rest
717    /// kept.
718    #[must_use]
719    pub(crate) fn merge(self, from: Self, which: V2ipDeviceSetting) -> Self {
720        let mut out = self;
721        if which.has(V2ipDeviceSetting::PTP_ANNOUNCE) {
722            out.log_announce_interval = from.log_announce_interval;
723        }
724        if which.has(V2ipDeviceSetting::PTP_SYNC) {
725            out.log_sync_interval = from.log_sync_interval;
726        }
727        if which.has(V2ipDeviceSetting::PTP_DELAY_REQ) {
728            out.log_delay_req_interval = from.log_delay_req_interval;
729        }
730        if which.has(V2ipDeviceSetting::PTP_ANNOUNCE_TIMEOUT) {
731            out.announce_timeout = from.announce_timeout;
732        }
733        if which.has(V2ipDeviceSetting::PTP_DSCP) {
734            out.dscp = from.dscp;
735        }
736        if which.has(V2ipDeviceSetting::SAP_EXPIRE) {
737            out.sap_expire_min = from.sap_expire_min;
738        }
739        if which.has(V2ipDeviceSetting::SAP_INTERVAL) {
740            out.sap_interval_s = from.sap_interval_s;
741        }
742        if which.has(V2ipDeviceSetting::STREAM_TTL) {
743            out.stream_ttl = from.stream_ttl;
744        }
745        out
746    }
747}
748
749impl V2ipDeviceSettings {
750    /// Whether an on/off setting is on, `None` while the device has not
751    /// reported it.
752    pub const fn get(&self, setting: V2ipDeviceSetting) -> Option<bool> {
753        if !self.valid.has(setting) {
754            return None;
755        }
756        Some(self.flags.has(setting))
757    }
758
759    /// The global infrared port's profile, `None` while it is not reported.
760    pub const fn ir_profile(&self) -> Option<i8> {
761        if !self.valid.has(V2ipDeviceSetting::IR_PROFILE) {
762            return None;
763        }
764        Some(self.ir_profile)
765    }
766
767    /// The output infrared port's profile, `None` while it is not reported.
768    /// [`V2IP_IR_PROFILE_NOT_SET`] means the port follows the global one.
769    pub const fn ir_profile_sink(&self) -> Option<i8> {
770        if !self.valid.has(V2ipDeviceSetting::IR_PROFILE_SINK) {
771            return None;
772        }
773        Some(self.ir_profile_sink)
774    }
775
776    /// The infrared profiles stored on the device, bit n for profile n, `None`
777    /// while it is not reported.
778    pub const fn stored_ir_profiles(&self) -> Option<u32> {
779        if !self.valid.has(V2ipDeviceSetting::IR_PROFILES) {
780            return None;
781        }
782        Some(self.ir_profiles)
783    }
784
785    /// The idle minutes before the device powers down by itself, 0 for never,
786    /// `None` while it is not reported.
787    pub const fn auto_power_save(&self) -> Option<u16> {
788        if !self.valid.has(V2ipDeviceSetting::AUTO_POWER_SAVE) {
789            return None;
790        }
791        Some(self.auto_power_save)
792    }
793
794    /// The daily power save windows, `None` while they are not reported.
795    pub const fn power_save_schedule(&self) -> Option<V2ipPowerSaveSchedule> {
796        if !self.valid.has(V2ipDeviceSetting::POWER_SAVE_SCHEDULE) {
797            return None;
798        }
799        Some(self.power_save)
800    }
801
802    /// The PTP mode, `None` while it is not reported.
803    pub const fn ptp_mode(&self) -> Option<V2ipPtpMode> {
804        if !self.valid.has(V2ipDeviceSetting::PTP_MODE) {
805            return None;
806        }
807        Some(self.ptp_mode)
808    }
809
810    /// The PTP domain, `None` while it is not reported.
811    pub const fn ptp_domain(&self) -> Option<u8> {
812        if !self.valid.has(V2ipDeviceSetting::PTP_DOMAIN) {
813            return None;
814        }
815        Some(self.ptp_domain)
816    }
817
818    /// The PTP priority1, `None` while it is not reported.
819    pub const fn ptp_priority1(&self) -> Option<u8> {
820        if !self.valid.has(V2ipDeviceSetting::PTP_PRIORITY1) {
821            return None;
822        }
823        Some(self.ptp_priority1)
824    }
825
826    /// The power save level, `None` while it is not reported.
827    pub const fn power_save_level(&self) -> Option<V2ipPowerSaveLevel> {
828        if !self.valid.has(V2ipDeviceSetting::POWER_SAVE_LEVEL) {
829            return None;
830        }
831        Some(self.power_save_level)
832    }
833
834    /// The PTP message and SAP settings the device has reported, `None` while
835    /// it has reported none of them; each value is meaningful only behind its
836    /// own bit of [`valid`](Self::valid).
837    pub fn ptp_messages(&self) -> Option<V2ipPtpMessages> {
838        (!(self.valid & V2ipDeviceSetting::SETTINGS_BLOCK).is_empty()).then_some(self.ptp_messages)
839    }
840
841    /// Folds a received settings block onto the cached one.
842    ///
843    /// Each bit in the frame's [`valid`](Self::valid) replaces its own setting
844    /// and leaves the others alone, so a write about one setting does not
845    /// clear what was known about the rest.
846    #[must_use]
847    pub(crate) fn merge(self, previous: Self) -> Self {
848        let valid = self.valid;
849        let mut out = previous;
850        out.valid |= valid;
851        out.flags = previous.flags.without(valid) | (self.flags & valid);
852        // A device takes a power save level as leaving power save enabled.
853        if valid.has(V2ipDeviceSetting::POWER_SAVE_LEVEL)
854            && !valid.has(V2ipDeviceSetting::POWER_SAVE_DISABLED)
855        {
856            out.flags = out.flags.without(V2ipDeviceSetting::POWER_SAVE_DISABLED);
857        }
858        if valid.has(V2ipDeviceSetting::IR_PROFILE) {
859            out.ir_profile = self.ir_profile;
860        }
861        if valid.has(V2ipDeviceSetting::IR_PROFILE_SINK) {
862            out.ir_profile_sink = self.ir_profile_sink;
863        }
864        if valid.has(V2ipDeviceSetting::IR_PROFILES) {
865            out.ir_profiles = self.ir_profiles;
866        }
867        if valid.has(V2ipDeviceSetting::AUTO_POWER_SAVE) {
868            out.auto_power_save = self.auto_power_save;
869        }
870        if valid.has(V2ipDeviceSetting::POWER_SAVE_SCHEDULE) {
871            out.power_save = self.power_save;
872        }
873        if valid.has(V2ipDeviceSetting::PTP_MODE) {
874            out.ptp_mode = self.ptp_mode;
875        }
876        if valid.has(V2ipDeviceSetting::PTP_DOMAIN) {
877            out.ptp_domain = self.ptp_domain;
878        }
879        if valid.has(V2ipDeviceSetting::PTP_PRIORITY1) {
880            out.ptp_priority1 = self.ptp_priority1;
881        }
882        if valid.has(V2ipDeviceSetting::POWER_SAVE_LEVEL) {
883            out.power_save_level = self.power_save_level;
884        }
885        out.ptp_messages = previous.ptp_messages.merge(self.ptp_messages, valid);
886        out
887    }
888
889    /// This block limited to what a device takes from a write about it.
890    ///
891    /// A device applies a setting only if it has it, a profile only within
892    /// its range, and never what only it can report about itself.
893    #[must_use]
894    pub(crate) fn as_applied_to(self, reported: V2ipDeviceSetting) -> Self {
895        let mut valid = (self.valid & reported).without(V2ipDeviceSetting::REPORTED_ONLY);
896        if !(0..V2IP_IR_PROFILE_MAX).contains(&self.ir_profile) {
897            valid = valid.without(V2ipDeviceSetting::IR_PROFILE);
898        }
899        if !(V2IP_IR_PROFILE_NOT_SET..V2IP_IR_PROFILE_MAX).contains(&self.ir_profile_sink) {
900            valid = valid.without(V2ipDeviceSetting::IR_PROFILE_SINK);
901        }
902        if self.ptp_mode > V2ipPtpMode::AUTO {
903            valid = valid.without(V2ipDeviceSetting::PTP_MODE);
904        }
905        if self.ptp_domain > V2IP_PTP_DOMAIN_MAX {
906            valid = valid.without(V2ipDeviceSetting::PTP_DOMAIN);
907        }
908        if self.power_save_level > V2ipPowerSaveLevel::OFF {
909            valid = valid.without(V2ipDeviceSetting::POWER_SAVE_LEVEL);
910        }
911        if self.ptp_messages.dscp > V2IP_DSCP_MAX {
912            valid = valid.without(V2ipDeviceSetting::PTP_DSCP);
913        }
914        if self.ptp_messages.stream_ttl == 0 {
915            valid = valid.without(V2ipDeviceSetting::STREAM_TTL);
916        }
917        Self { valid, ..self }
918    }
919}
920
921/// The longest session description a V2IP output takes, in bytes.
922pub const V2IP_SDP_MAX: usize = 2048;
923
924/// What a V2IP output plays from a session description, as it last reported
925/// it. The stream's fields are zero while it plays none.
926#[derive(Clone, Debug, PartialEq, Eq)]
927pub struct V2ipSinkSdp {
928    /// The report's flags.
929    pub flags: V2ipSdpFlag,
930    /// What the output shows while it plays audio alone, as the wire value.
931    pub screen: u8,
932    /// The sample encoding.
933    pub encoding: V2ipSdpEncoding,
934    /// The channel count.
935    pub channels: u8,
936    /// The RTP payload type.
937    pub payload_type: u8,
938    /// Where the media clock comes from.
939    pub media_clock: V2ipSdpMediaClock,
940    /// The reference clock.
941    pub ref_clock: V2ipSdpRefClock,
942    /// What the video processor times the stream by, when `flags` has
943    /// [`CLOCK`](V2ipSdpFlag::CLOCK).
944    pub clock_mode: V2ipSdpClockMode,
945    /// How far the video processor has got with the timing, when `flags` has
946    /// [`CLOCK`](V2ipSdpFlag::CLOCK).
947    pub clock_state: V2ipSdpClockState,
948    /// The destination UDP port.
949    pub port: u16,
950    /// The sample rate, in Hz.
951    pub rate_hz: u32,
952    /// The media clock offset.
953    pub media_clock_offset: u32,
954    /// The multicast group.
955    pub group: Ipv4Addr,
956    /// The session name (`s=`).
957    pub name: String,
958    /// The channel grouping it plays, empty without one.
959    pub layout: String,
960}
961
962impl V2ipSinkSdp {
963    /// Whether the output plays a stream from a description.
964    pub const fn is_active(&self) -> bool {
965        self.flags.has(V2ipSdpFlag::ACTIVE)
966    }
967}
968
969/// A V2IP device's PTP state, as it reports it about itself.
970///
971/// Only the device can read its own video processor, so this is never written
972/// to a device, and a controller's frame about one carries none.
973#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
974pub struct V2ipPtpState {
975    /// The block's flags.
976    pub flags: V2ipPtpFlag,
977    /// The mode the video processor runs.
978    pub mode: V2ipPtpMode,
979    /// The domain the video processor runs in.
980    pub domain: u8,
981    /// The IEEE 1588 portState.
982    pub port_state: u8,
983    /// How far the clock has locked.
984    pub lock: V2ipPtpLock,
985    /// The device's own clock identity.
986    pub clock_identity: [u8; 8],
987    /// The clock identity of the grandmaster the device runs on, all zero
988    /// while it runs on none.
989    pub grandmaster_identity: [u8; 8],
990}
991
992impl V2ipPtpState {
993    /// Whether the device locked to a master since its PTP started, so its
994    /// mesh holds a time.
995    pub const fn followed(&self) -> bool {
996        self.flags.has(V2ipPtpFlag::FOLLOWED)
997    }
998
999    /// The grandmaster the device runs on, `None` while it runs on none.
1000    pub fn grandmaster(&self) -> Option<[u8; 8]> {
1001        (self.grandmaster_identity != [0; 8]).then_some(self.grandmaster_identity)
1002    }
1003}
1004
1005/// The external network ports a [`V2ipVlan`] covers, in the order of
1006/// [`V2ipVlan::port`]: the SFP port, the UTP port with PoE, then the UTP port.
1007pub const V2IP_VLAN_PORTS: usize = 3;
1008
1009/// The index of the SFP port in [`V2ipVlan::port`].
1010pub const V2IP_VLAN_PORT_SFP: usize = 0;
1011
1012/// The highest VLAN id: 0 means untagged, and 4095 is reserved by IEEE 802.1Q.
1013pub const V2IP_VLAN_ID_MAX: u16 = 4094;
1014
1015/// VLAN tagging on a V2IP device's uplink.
1016///
1017/// Only the device knows what it runs, so this is what it reported about
1018/// itself. A change written to it is applied at once and stays
1019/// [`PENDING`](V2ipVlanFlag::PENDING) until the mesh controller confirms it,
1020/// which proves the device still reaches the mesh and the mesh still reaches
1021/// it; unconfirmed, the device reverts it.
1022#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1023pub struct V2ipVlan {
1024    /// The block's flags.
1025    pub flags: V2ipVlanFlag,
1026    /// The VLAN id of the device's own traffic, 0 for untagged.
1027    pub device: u16,
1028    /// The VLAN id each downlink port carries, 0 to share the device's
1029    /// untagged traffic, indexed as [`V2IP_VLAN_PORTS`] orders them.
1030    pub port: [u16; V2IP_VLAN_PORTS],
1031    /// The port pinned as the uplink as 1 + its index, 0 to detect it.
1032    pub uplink: u8,
1033    /// Reported by the device: the port in use as the uplink, as 1 + its
1034    /// index.
1035    pub active_uplink: u8,
1036    /// Reported by the device: the seconds before a pending configuration is
1037    /// reverted.
1038    pub revert_s: u8,
1039}
1040
1041impl V2ipVlan {
1042    /// Whether untagged frames arriving on the uplink are dropped.
1043    pub const fn trunk(&self) -> bool {
1044        self.flags.has(V2ipVlanFlag::TRUNK)
1045    }
1046
1047    /// Whether the device reverts this configuration unless the mesh
1048    /// controller confirms it.
1049    pub const fn is_pending(&self) -> bool {
1050        self.flags.has(V2ipVlanFlag::PENDING)
1051    }
1052
1053    /// Whether the device has an SFP port.
1054    pub const fn has_sfp(&self) -> bool {
1055        self.flags.has(V2ipVlanFlag::HAS_SFP)
1056    }
1057
1058    /// The index of the port pinned as the uplink, `None` when the device
1059    /// detects it.
1060    pub const fn pinned_uplink(&self) -> Option<usize> {
1061        port_index(self.uplink)
1062    }
1063
1064    /// The index of the port the device uses as its uplink, `None` for a
1065    /// value that names no port.
1066    pub const fn active_uplink(&self) -> Option<usize> {
1067        port_index(self.active_uplink)
1068    }
1069
1070    /// Whether every VLAN id is at most [`V2IP_VLAN_ID_MAX`] and the uplink is
1071    /// detected or names a port.
1072    pub fn is_valid(&self) -> bool {
1073        let ids_ok = core::iter::once(&self.device)
1074            .chain(&self.port)
1075            .all(|id| *id <= V2IP_VLAN_ID_MAX);
1076        ids_ok && (self.uplink == 0 || self.pinned_uplink().is_some())
1077    }
1078}
1079
1080/// A port index from its 1-based wire form.
1081const fn port_index(wire: u8) -> Option<usize> {
1082    match wire {
1083        1..=3 => Some(wire as usize - 1),
1084        _ => None,
1085    }
1086}
1087
1088/// The lowest test tone frequency, in Hz.
1089pub const V2IP_TONE_FREQ_MIN: u16 = 20;
1090/// The highest test tone frequency, in Hz.
1091pub const V2IP_TONE_FREQ_MAX: u16 = 20_000;
1092/// The quietest test tone level, in dBFS; the loudest is 0.
1093pub const V2IP_TONE_LEVEL_MIN: i8 = -60;
1094/// The most channels a test tone plays on.
1095pub const V2IP_TONE_CHANNELS_MAX: u8 = 8;
1096/// The sample rates a test tone plays at, in Hz.
1097pub const V2IP_TONE_RATES: [u32; 3] = [44_100, 48_000, 96_000];
1098/// The largest lip-sync beep offset, in sample periods.
1099pub const V2IP_SYNC_OFFSET_MAX: u32 = 0x00FF_FFFF;
1100/// The shortest lip-sync beep, in milliseconds.
1101pub const V2IP_SYNC_BEEP_MS_MIN: u16 = 1;
1102/// The longest lip-sync beep, in milliseconds.
1103pub const V2IP_SYNC_BEEP_MS_MAX: u16 = 10_000;
1104
1105/// A V2IP sink's test tone.
1106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1107pub struct V2ipTestTone {
1108    /// What plays.
1109    pub mode: V2ipToneMode,
1110    /// The frequency, in Hz.
1111    pub freq: u16,
1112    /// The level, in dBFS.
1113    pub level: i8,
1114    /// The channels it plays on.
1115    pub channels: u8,
1116    /// The sample rate, in Hz.
1117    pub rate: u32,
1118}
1119
1120impl V2ipTestTone {
1121    /// Whether a sink plays this tone: a mode it names, and every value in
1122    /// range. A line-up tone needs two channels or more.
1123    pub fn is_valid(&self) -> bool {
1124        let min_channels = if self.mode == V2ipToneMode::LINEUP {
1125            2
1126        } else {
1127            1
1128        };
1129        self.mode.to_wire() <= V2ipToneMode::BEEP.to_wire()
1130            && (V2IP_TONE_FREQ_MIN..=V2IP_TONE_FREQ_MAX).contains(&self.freq)
1131            && (V2IP_TONE_LEVEL_MIN..=0).contains(&self.level)
1132            && (min_channels..=V2IP_TONE_CHANNELS_MAX).contains(&self.channels)
1133            && V2IP_TONE_RATES.contains(&self.rate)
1134    }
1135}
1136
1137/// A V2IP sink's lip-sync flash: a pattern frame is marked every `period`,
1138/// the frame `lead` after a mark flashes white, and a
1139/// [`BEEP`](V2ipToneMode::BEEP) tone starts `offset` sample periods after it.
1140///
1141/// The offset is a calibration: nothing measures the sink's own delay between
1142/// a picture and a sample reaching the HDMI link, and a display adds its own.
1143#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1144pub struct V2ipTestSync {
1145    /// Every this many pattern frames is marked, 0 for none.
1146    pub period: u16,
1147    /// The frame this many after a mark flashes.
1148    pub lead: u16,
1149    /// The sample periods between a mark and the beep.
1150    pub offset: u32,
1151    /// How long the beep lasts, in milliseconds.
1152    pub beep_ms: u16,
1153}
1154
1155impl V2ipTestSync {
1156    /// Whether a sink takes these settings: the lead is below the period, or
1157    /// 0 without one, and the offset and beep are in range.
1158    pub fn is_valid(&self) -> bool {
1159        let lead_ok = if self.period == 0 {
1160            self.lead == 0
1161        } else {
1162            self.lead < self.period
1163        };
1164        lead_ok
1165            && self.offset <= V2IP_SYNC_OFFSET_MAX
1166            && (V2IP_SYNC_BEEP_MS_MIN..=V2IP_SYNC_BEEP_MS_MAX).contains(&self.beep_ms)
1167    }
1168}
1169
1170/// The test card a V2IP sink draws on its output, as it last reported it.
1171///
1172/// A sink reports it only when asked, with
1173/// [`Remote::request_v2ip_testcard`](crate::Remote::request_v2ip_testcard) or
1174/// in answer to a change. The counters run free and wrap.
1175#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1176pub struct V2ipTestcard {
1177    /// What the sink reports about its test card.
1178    pub flags: V2ipTestcardFlag,
1179    /// The pattern.
1180    pub pattern: V2ipTestPattern,
1181    /// The colour of a [`FLAT`](V2ipTestPattern::FLAT) pattern, `0xRRGGBB`.
1182    pub colour: u32,
1183    /// The tone.
1184    pub tone: V2ipTestTone,
1185    /// The lip-sync flash.
1186    pub sync: V2ipTestSync,
1187    /// Pattern frames sent.
1188    pub frames: u32,
1189    /// Sample periods since the tone started.
1190    pub periods: u32,
1191    /// Lip-sync marks the tone has seen.
1192    pub marks: u32,
1193}
1194
1195impl V2ipTestcard {
1196    /// Whether the sink can draw the test card.
1197    pub const fn supported(&self) -> bool {
1198        self.flags.has(V2ipTestcardFlag::SUPPORTED)
1199    }
1200}
1201
1202/// Transmitter stream statistics.
1203#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1204pub struct V2ipTxStats {
1205    /// Video packets sent.
1206    pub video: u32,
1207    /// Audio packets sent.
1208    pub audio: u32,
1209    /// Ancillary-data packets sent.
1210    pub anc: u32,
1211    /// Times the stream went down.
1212    pub stream_down: u32,
1213    /// Transmit overflows.
1214    pub overflow: u32,
1215}
1216
1217/// The health state of a V2IP decoder.
1218#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
1219pub struct V2ipDecoderState(u8);
1220
1221impl V2ipDecoderState {
1222    /// The sink has not reported a state.
1223    pub const UNKNOWN: Self = Self(0);
1224    /// Decoding normally.
1225    pub const HEALTHY: Self = Self(1);
1226    /// Failed to decode.
1227    pub const BAD: Self = Self(2);
1228    /// Still coming up, which any sink subscribed to during a route change
1229    /// reports.
1230    pub const STARTING: Self = Self(3);
1231
1232    /// Wraps a raw wire value, including one this library has no name for.
1233    pub const fn from_wire(value: u8) -> Self {
1234        Self(value)
1235    }
1236
1237    /// Returns the raw wire value.
1238    pub const fn to_wire(self) -> u8 {
1239        self.0
1240    }
1241
1242    /// Reports whether the decoder has reached a verdict.
1243    ///
1244    /// Only healthy and bad are verdicts. Testing for failure as "not healthy"
1245    /// reads a receiver that is merely coming up as one that failed to decode,
1246    /// which is what a sink reports for a moment after every route change.
1247    pub const fn is_settled(self) -> bool {
1248        matches!(self, Self::HEALTHY | Self::BAD)
1249    }
1250}
1251
1252impl fmt::Display for V2ipDecoderState {
1253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1254        match *self {
1255            Self::UNKNOWN => f.write_str("Unknown"),
1256            Self::HEALTHY => f.write_str("Healthy"),
1257            Self::BAD => f.write_str("Bad"),
1258            Self::STARTING => f.write_str("Starting"),
1259            Self(v) => write!(f, "state {v}"),
1260        }
1261    }
1262}
1263
1264/// Receiver stream statistics.
1265#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1266pub struct V2ipRxStats {
1267    /// Video packets received.
1268    pub video_total: u32,
1269    /// Video packets dropped.
1270    pub video_dropped: u32,
1271    /// Video sequence errors.
1272    pub video_seq_errors: u32,
1273    /// Watchdog timeouts.
1274    pub wdt_timeout: u32,
1275    /// Audio packets received.
1276    pub audio_total: u32,
1277    /// Audio packets dropped.
1278    pub audio_dropped: u32,
1279    /// Audio sequence errors.
1280    pub audio_seq_errors: u32,
1281    /// Ancillary-data packets received.
1282    pub anc_total: u32,
1283    /// Ancillary-data packets dropped.
1284    pub anc_dropped: u32,
1285    /// Ancillary-data sequence errors.
1286    pub anc_seq_errors: u32,
1287    /// The decoder's health state.
1288    pub decoder_state: V2ipDecoderState,
1289}
1290
1291/// Why a decoder reports the state it does.
1292///
1293/// The primary cause only. Several causes can be true at once, and which of
1294/// them lands here is a fixed priority order in the firmware that the numbering
1295/// does not express: these values are identities, not ranks, and comparing or
1296/// ordering them says nothing. Ask [`V2ipDecoderReport::has_cause`] whether a
1297/// particular cause applies - a test against this field answers "is this the
1298/// one that won" instead, which is a different question.
1299///
1300/// Firmware adds causes, so the wire value is carried as it arrived: folding an
1301/// unrecognised one onto a named cause would report a fault this library
1302/// invented. Appending one cannot reorder the existing priorities.
1303#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
1304pub struct V2ipDecoderReason(u8);
1305
1306impl V2ipDecoderReason {
1307    /// Decoding normally.
1308    pub const OK: Self = Self(0);
1309    /// No packets are arriving.
1310    pub const NO_PACKETS: Self = Self(1);
1311    /// Packets are arriving, degraded.
1312    pub const PACKETS_DEGRADED: Self = Self(2);
1313    /// No format could be recovered from the codestream.
1314    pub const NO_FORMAT: Self = Self(3);
1315    /// The recovered format is not the one the sink is configured for.
1316    pub const FORMAT_MISMATCH: Self = Self(4);
1317    /// The configured output format was refused.
1318    pub const FORMAT_REJECTED: Self = Self(5);
1319    /// The converter watchdog is holding the stream back.
1320    pub const DECODER_BLOCKED: Self = Self(6);
1321    /// A source switch is in progress: a step in an operation someone asked
1322    /// for, rather than a fault.
1323    pub const SWITCH_PENDING: Self = Self(7);
1324    /// PTP is unlocked. That costs audio alone; the picture is unaffected.
1325    pub const PTP_UNLOCKED: Self = Self(8);
1326    /// The pipeline is rebuilding after the HDMI transmitter stayed unlocked.
1327    ///
1328    /// The picture is down, and has been for five seconds before this can
1329    /// appear: the sender debounces the unlocked reading for that long, so
1330    /// this never reports a transient. Unlike [`Self::SWITCH_PENDING`] nobody
1331    /// asked for it.
1332    ///
1333    /// The debounce restarts each time it elapses, so this holding across
1334    /// reports is a restart loop rather than one event, and that is what to
1335    /// escalate on.
1336    ///
1337    /// It sits near the bottom of the priority order, below every input-side
1338    /// cause, so a rebuilding pipeline names one of those in
1339    /// [`V2ipDecoderReport::reason`] and carries this in
1340    /// [`V2ipDecoderReport::flags`] alone - always, rather than briefly.
1341    ///
1342    /// It is evaluated only while no format change is in progress. Across a
1343    /// switch it holds its previous value and clears on the first reading
1344    /// after the change settles, which [`V2ipDecoderReport::updates`] cannot
1345    /// distinguish: a value carried forward is still a stored reading.
1346    pub const TX_BRIDGE_UNLOCKED: Self = Self(9);
1347    /// The sink is configured but switched off, so no stream is expected.
1348    ///
1349    /// This outranks every other cause: whenever it applies it is what
1350    /// [`V2ipDecoderReport::reason`] carries.
1351    ///
1352    /// **The causes beneath it stay set in [`V2ipDecoderReport::flags`].** A
1353    /// sink switched off while it was running keeps the bits the decoder
1354    /// genuinely observed on the way down - no packets, no format - so a
1355    /// classifier that tests a fault mask over the whole word calls a
1356    /// deliberately disabled sink broken. Ask for this cause first and stop
1357    /// there; the bits below it describe what was seen, not a fault to report.
1358    ///
1359    /// This says nothing about geometry, in either direction. The decoder
1360    /// reports what it currently detects whatever the cause, so a switched-off
1361    /// sink still detecting a codestream carries a real geometry, and a zero
1362    /// one means the decoder has nothing rather than that the sink is off.
1363    ///
1364    /// Older senders never report this and give [`Self::NO_PACKETS`] for a
1365    /// disabled sink instead, indistinguishable from one whose source has
1366    /// died. So an absent [`Self::IDLE`] is not evidence a sink is enabled,
1367    /// and **nothing in this block answers enablement**: it carries no such
1368    /// field, and the answer comes from `V2IP_DEVICE_CFG` or the device's HTTP
1369    /// status.
1370    pub const IDLE: Self = Self(10);
1371
1372    /// Wraps a raw wire value, including one this library has no name for.
1373    pub const fn from_wire(value: u8) -> Self {
1374        Self(value)
1375    }
1376
1377    /// Returns the raw wire value.
1378    pub const fn to_wire(self) -> u8 {
1379        self.0
1380    }
1381}
1382
1383impl fmt::Display for V2ipDecoderReason {
1384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1385        match *self {
1386            Self::OK => f.write_str("ok"),
1387            Self::NO_PACKETS => f.write_str("no packets"),
1388            Self::PACKETS_DEGRADED => f.write_str("packets degraded"),
1389            Self::NO_FORMAT => f.write_str("no format recovered"),
1390            Self::FORMAT_MISMATCH => f.write_str("format mismatch"),
1391            Self::FORMAT_REJECTED => f.write_str("format rejected"),
1392            Self::DECODER_BLOCKED => f.write_str("decoder blocked"),
1393            Self::SWITCH_PENDING => f.write_str("switch pending"),
1394            Self::PTP_UNLOCKED => f.write_str("PTP unlocked"),
1395            Self::TX_BRIDGE_UNLOCKED => f.write_str("TX bridge unlocked"),
1396            Self::IDLE => f.write_str("idle"),
1397            Self(v) => write!(f, "reason {v}"),
1398        }
1399    }
1400}
1401
1402/// The colour space a decoder recovered from a codestream.
1403///
1404/// Zero is RGB and is also what a decoder with nothing to decode reports, so no
1405/// value here means "no signal" - [`V2ipDecoderReport::has_geometry`] is what
1406/// answers that.
1407#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
1408pub struct V2ipDecoderFormat(u16);
1409
1410impl V2ipDecoderFormat {
1411    /// RGB.
1412    pub const RGB: Self = Self(0);
1413    /// YCbCr 4:4:4.
1414    pub const YCBCR_444: Self = Self(1);
1415    /// YCbCr 4:2:2.
1416    pub const YCBCR_422: Self = Self(2);
1417    /// YCbCr 4:2:0.
1418    pub const YCBCR_420: Self = Self(3);
1419    /// The decoder cannot name the format.
1420    ///
1421    /// 255, which is a value of its own rather than the 0xF a signal report
1422    /// uses for an unknown colour space. Mapping one onto the other yields a
1423    /// colour space the decoder never reported.
1424    pub const UNNAMED: Self = Self(255);
1425
1426    /// Wraps a raw wire value, including one this library has no name for.
1427    pub const fn from_wire(value: u16) -> Self {
1428        Self(value)
1429    }
1430
1431    /// Returns the raw wire value.
1432    pub const fn to_wire(self) -> u16 {
1433        self.0
1434    }
1435}
1436
1437impl fmt::Display for V2ipDecoderFormat {
1438    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1439        match *self {
1440            Self::RGB => f.write_str("RGB"),
1441            Self::YCBCR_444 => f.write_str("YCbCr 4:4:4"),
1442            Self::YCBCR_422 => f.write_str("YCbCr 4:2:2"),
1443            Self::YCBCR_420 => f.write_str("YCbCr 4:2:0"),
1444            Self::UNNAMED => f.write_str("unnamed"),
1445            Self(v) => write!(f, "format {v}"),
1446        }
1447    }
1448}
1449
1450/// What a sink's decoder recovered from the codestream it is being given.
1451///
1452/// This is what the decoder understood, read ahead of the scaler: the geometry
1453/// is unrounded and is not what the display is being sent. It separates "the
1454/// decoder understood the codestream" from "a picture came out the other end".
1455///
1456/// Colour depth is absent on purpose and will stay absent. The video processor
1457/// answers that one from a driver constant rather than from the codestream, so
1458/// there is no reading to carry; assert depth at the encoder's input bay
1459/// instead.
1460#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1461pub struct V2ipDecoderReport {
1462    /// The primary cause of the state the decoder is in.
1463    pub reason: V2ipDecoderReason,
1464    /// The converter watchdog is holding the stream back.
1465    pub blocking: bool,
1466    /// The recovered picture width, and 0 when none was recovered.
1467    pub width: u16,
1468    /// The recovered picture height, and 0 when none was recovered.
1469    pub height: u16,
1470    /// The recovered colour space.
1471    pub format: V2ipDecoderFormat,
1472    /// How many readings the sink has stored. Monotonic, wrapping at 65535
1473    /// after some 36 hours, and never reset.
1474    ///
1475    /// A sink reads its video processor every two seconds and reports every
1476    /// second, so roughly every other report repeats a reading already seen:
1477    /// a frame arriving says nothing about how fresh the values in it are.
1478    /// This counter moves only when a reading is stored, so a processor that
1479    /// stopped answering leaves it still rather than implying a refresh.
1480    ///
1481    /// After pointing a sink at something else, wait for this to advance by
1482    /// two before trusting the geometry. It ticks when a reply lands rather
1483    /// than when a query is sent, so the first tick can carry an answer the
1484    /// processor read fractionally before the switch; the second cannot,
1485    /// because at most one query is outstanding at a time.
1486    pub updates: u16,
1487    /// Every cause that applies, as bit N for reason N. See
1488    /// [`Self::has_cause`].
1489    ///
1490    /// This is what to classify on, once [`V2ipDecoderReason::IDLE`] has been
1491    /// ruled out: that cause outranks the whole word and leaves the bits below
1492    /// it set, so a fault mask over `flags` reports a switched-off sink as
1493    /// broken. [`Self::reason`] carries whichever cause won a fixed priority
1494    /// contest, so a cause that is true can be absent from it while present
1495    /// here. Bit 0 is cleared by the sender, so an empty word means nothing
1496    /// beyond the primary cause applies.
1497    ///
1498    /// [`V2ipDecoderReason::NO_FORMAT`] and
1499    /// [`V2ipDecoderReason::FORMAT_MISMATCH`] are the two arms of one decision
1500    /// and never appear together.
1501    pub flags: u32,
1502    /// How many times the converter watchdog has triggered.
1503    pub blocked_count: u32,
1504}
1505
1506impl V2ipDecoderReport {
1507    /// Reports whether the decoder recovered a geometry.
1508    ///
1509    /// This is what says whether the decoder is being given a codestream it
1510    /// understands. [`Self::format`] cannot: it reads
1511    /// [`V2ipDecoderFormat::RGB`] when nothing is arriving, which is
1512    /// indistinguishable from a real RGB reading.
1513    ///
1514    /// It answers that and nothing else. The reading is taken before any cause
1515    /// is decided, so it does not say whether the sink is switched on: a sink
1516    /// that is off can still detect a codestream, and one that is on can
1517    /// detect nothing.
1518    pub const fn has_geometry(&self) -> bool {
1519        self.width != 0 && self.height != 0
1520    }
1521
1522    /// Reports whether `reason` is among the causes that apply.
1523    ///
1524    /// [`Self::reason`] carries the primary cause and `flags` carries all of
1525    /// them at once. Bit 0 is unused, so [`V2ipDecoderReason::OK`] is never
1526    /// among them and an empty word means nothing beyond the primary cause
1527    /// applies.
1528    pub const fn has_cause(&self, reason: V2ipDecoderReason) -> bool {
1529        let bit = reason.to_wire();
1530        bit > 0 && bit < u32::BITS as u8 && self.flags & (1 << bit) != 0
1531    }
1532}
1533
1534/// What a statistics report says about the sink's decoder.
1535///
1536/// The three states are distinct answers and only [`Self::Answered`] carries a
1537/// reading. `valid` follows the sink being configured rather than the sink
1538/// being enabled, so a sink that is switched off still reports: as
1539/// [`V2ipDecoderReason::IDLE`], or from an older sender as
1540/// [`V2ipDecoderReason::NO_PACKETS`], which is the same reading a sink whose
1541/// source has died produces.
1542#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1543pub enum V2ipDecoderDetail {
1544    /// The report carried no decoder block: the sender's firmware predates it.
1545    #[default]
1546    Absent,
1547    /// The block is there and the decoder has never answered. Every field it
1548    /// would carry is meaningless, so none is offered.
1549    NeverAnswered,
1550    /// A reading.
1551    Answered(V2ipDecoderReport),
1552}
1553
1554impl V2ipDecoderDetail {
1555    /// The reading, for a caller that treats both of the other states as
1556    /// "nothing to show".
1557    pub const fn reading(self) -> Option<V2ipDecoderReport> {
1558        match self {
1559            Self::Answered(report) => Some(report),
1560            _ => None,
1561        }
1562    }
1563}
1564
1565/// The cumulative and per-minute transmit and receive statistics.
1566#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1567pub struct V2ipDeviceStats {
1568    /// Transmit totals since boot.
1569    pub tx: V2ipTxStats,
1570    /// Transmit counts over the last minute.
1571    pub tx_per_minute: V2ipTxStats,
1572    /// Receive totals since boot.
1573    pub rx: V2ipRxStats,
1574    /// Receive counts over the last minute.
1575    pub rx_per_minute: V2ipRxStats,
1576    /// What the sink's decoder recovered from the codestream it is decoding.
1577    pub decoder: V2ipDecoderDetail,
1578}