Skip to main content

mx_remote/types/
commands.rs

1// Author: Lars Op den Kamp (lars@opdenkamp-it.nl)
2// Copyright (c) 2026 Op den Kamp IT Solutions
3
4//! Payloads of the command and notification opcodes.
5//!
6//! These frames are addressed to a device rather than reporting its state, so
7//! most surface as events rather than cached state. A frame addressed to
8//! another unit still reaches every client on the group: the target field says
9//! who it was for, and that is neither necessarily this client nor the sender.
10
11use core::fmt;
12use std::net::Ipv4Addr;
13
14use crate::wire::{DeviceUid, EdidProfile, RcAction, RcKey};
15
16/// Asks a device, addressed by serial, to switch a sink.
17#[derive(Clone, Debug, Default, PartialEq, Eq)]
18pub struct SetRouteRequest {
19    /// Serial of the device to act on.
20    pub serial: String,
21    /// Output bay to switch.
22    pub sink_bay: u16,
23    /// Source bay to switch it to.
24    pub source_bay: u16,
25    /// Whether to skip the power-on commands that normally accompany a switch.
26    pub no_power_on: bool,
27    /// True when this arrived on `AUDIO_SET_ROUTE` rather than `MX_SET_ROUTE`.
28    pub audio_only: bool,
29}
30
31impl fmt::Display for SetRouteRequest {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        write!(
34            f,
35            "set route on {}: sink={} source={}",
36            self.serial, self.sink_bay, self.source_bay
37        )
38    }
39}
40
41/// One EDID block from a `DEV_EDID` reply.
42///
43/// A reply carries one record per bay mode, so a combined reply produces two.
44#[derive(Clone, Debug, Default, PartialEq, Eq)]
45pub struct EdidRecord {
46    /// True for a sink's EDID, false for a source's.
47    pub output: bool,
48    /// A 256-byte EDID: a base block plus exactly one extension block. A
49    /// display publishing further extension blocks yields only the first.
50    pub data: Vec<u8>,
51}
52
53/// Asks one device for its EDID.
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
55pub struct EdidRequest {
56    /// The device being asked.
57    pub target: DeviceUid,
58    /// Whether the sink's EDID is wanted rather than the source's.
59    pub output: bool,
60}
61
62/// Asks a device to rename one of its bays.
63#[derive(Clone, Debug, Default, PartialEq, Eq)]
64pub struct BayNameChange {
65    /// The device to act on.
66    pub target: DeviceUid,
67    /// The bay to rename.
68    pub port: u16,
69    /// The new name.
70    pub name: String,
71}
72
73/// Asks a device to switch its input EDID profile.
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
75pub struct EdidProfileChange {
76    /// The device to act on.
77    pub target: DeviceUid,
78    /// The profile to switch to.
79    pub profile: EdidProfile,
80}
81
82/// Asks peers to factory-reset.
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
84pub struct FactoryResetRequest {
85    /// Set by the broadcast form, which targets every peer.
86    pub all: bool,
87    /// Set by the single-uid form. With neither this nor `all`, the request
88    /// addresses only the sender.
89    pub target: Option<DeviceUid>,
90}
91
92/// Asks one device to reboot.
93#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
94pub struct RebootRequest {
95    /// The device to reboot.
96    pub target: DeviceUid,
97}
98
99/// The window a sink is currently told to show.
100///
101/// This is the readable, pollable view of a sink's window. It is not the
102/// persisted video wall setting: on a sink running the v2ipwall module a write
103/// here is transient, because that module's reconciler pushes its own target
104/// window back within about a second. [`VideoWallCommand`] carries intent.
105#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
106pub struct V2ipTilingConfig {
107    /// The sink this window belongs to.
108    pub target: DeviceUid,
109    /// Window origin, horizontal.
110    pub pos_x: u16,
111    /// Window origin, vertical.
112    pub pos_y: u16,
113    /// Window width.
114    pub width: u16,
115    /// Window height.
116    pub height: u16,
117}
118
119impl fmt::Display for V2ipTilingConfig {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        write!(
122            f,
123            "tiling x={} y={} {}x{}",
124            self.pos_x, self.pos_y, self.width, self.height
125        )
126    }
127}
128
129/// Asks a sink to enter or leave power save.
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131pub struct V2ipPowerSaveRequest {
132    /// The sink to act on, or `None` on the broadcast form.
133    pub target: Option<DeviceUid>,
134    /// Whether power save is being entered.
135    pub enabled: bool,
136}
137
138/// The remote-control configuration of a source bay.
139#[derive(Clone, Debug, Default, PartialEq, Eq)]
140pub struct RcSettings {
141    /// The device this configuration belongs to.
142    pub target: DeviceUid,
143    /// The control method.
144    ///
145    /// A single byte: the enum is plain and Cortex-M builds with
146    /// `-fshort-enums`, so three bytes of padding follow it before the address.
147    /// That padding is not zero - firmware copies an uncleared stack local over
148    /// the payload - so widening this to a `u32` makes one unchanged setting
149    /// decode differently on every frame.
150    pub rc_target: u8,
151    /// The control target's address, `None` when unset.
152    pub ip: Option<Ipv4Addr>,
153    /// Whether CEC is enabled.
154    pub cec_enabled: bool,
155    /// Whether CEC powers the sink on automatically.
156    pub cec_auto_on: bool,
157    /// Whether remote-control commands are forwarded.
158    pub forward_rc: bool,
159    /// Whether infrared is forwarded.
160    pub forward_ir: bool,
161    /// The driver state on the source.
162    ///
163    /// A value above the last one this library knows is passed through as it
164    /// arrived rather than clamped, so a firmware update cannot make it read as
165    /// a known state.
166    pub rc_status: u8,
167    /// The driver-reported status string, empty when unknown.
168    pub status_name: String,
169}
170
171/// The raw-IR metadata shared by the IR capture and transmit frames.
172#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
173pub struct IrMeta {
174    /// Tick length the sender says its timing values are in.
175    ///
176    /// Reported and then ignored: a device replaying a burst applies its own
177    /// tick length rather than this one, and the two differ between products.
178    /// So it describes the sender, not the timings as the receiver will read
179    /// them, and converting with it does not make a burst portable.
180    pub timer_resolution: u16,
181    /// Carrier frequency in Hz.
182    pub frequency: u16,
183    /// How many timing values the sender says it appended.
184    ///
185    /// A declaration, not a measurement: nothing on the wire ties it to the
186    /// bytes that arrived, and a device replaying the burst indexes this many
187    /// rather than counting. Bound any read by the timing list itself, which is
188    /// the only part of a frame that cannot claim more than it carries.
189    pub nb_timings: u16,
190    /// Index at which the repeat section starts, declared on the same terms as
191    /// `nb_timings` and equally unbounded by the list.
192    pub repeat_offset: u16,
193    /// Capture status.
194    pub status: u8,
195}
196
197/// Raw IR captured on a bay of the sending device.
198#[derive(Clone, Debug, Default, PartialEq, Eq)]
199pub struct IrCapture {
200    /// The bay that captured it.
201    pub port: u16,
202    /// Sender clock at capture time.
203    pub timestamp: u32,
204    /// Sender clock at the last signal change.
205    pub last_change: u32,
206    /// Metadata for the timings.
207    pub meta: IrMeta,
208    /// The raw on/off timing blob following the header.
209    ///
210    /// Index 0 is never replayed. A device blasting this list starts at the
211    /// second timing, so the first holds the gap captured ahead of the burst
212    /// and goes nowhere. A capture of a single timing therefore carries no
213    /// burst at all, and a caller counting pulses is counting one fewer than
214    /// this holds.
215    pub timings: Vec<u8>,
216}
217
218/// Asks one device to blast raw IR on one of its local bays.
219#[derive(Clone, Debug, Default, PartialEq, Eq)]
220pub struct IrTransmitRequest {
221    /// The device to act on.
222    pub target: DeviceUid,
223    /// Bay mode in the target's own numbering, not a port.
224    pub local_mode: u8,
225    /// Bay number in the target's own numbering, not a port.
226    pub local_bay: u8,
227    /// Sender clock at send time.
228    pub timestamp: u32,
229    /// Metadata for the timings.
230    pub meta: IrMeta,
231    /// The raw on/off timing blob following the header.
232    ///
233    /// Laid out as a capture is, and index 0 is discarded the same way, so a
234    /// capture is replayed by passing its timings through unchanged. A request
235    /// carrying one timing asks for nothing.
236    ///
237    /// Rebuild the rest of the request rather than forwarding a capture's
238    /// header: `timestamp` must be the sending client's own clock at send
239    /// time, because the addressed device measures the gap ahead of the burst
240    /// from it rather than from anything in this list.
241    pub timings: Vec<u8>,
242}
243
244/// Asks one device to send a remote-control key on a bay.
245#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
246pub struct KeyTransmitRequest {
247    /// The device to act on.
248    pub target: DeviceUid,
249    /// Bay in the target's own numbering.
250    pub local_bay: u16,
251    /// The key to send.
252    pub key: RcKey,
253}
254
255/// Asks one device to perform a remote-control action.
256#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
257pub struct ActionTransmitRequest {
258    /// The device to act on.
259    pub target: DeviceUid,
260    /// Bay in the target's own numbering.
261    pub local_bay: u16,
262    /// The action to perform.
263    pub action: RcAction,
264}
265
266/// Reports that a bay detected audio clipping.
267#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
268pub struct AudioClip {
269    /// The bay that clipped.
270    pub port: u16,
271    /// The clip level reported.
272    pub clip: u8,
273}
274
275/// Registers or unregisters a device on the source blacklist.
276///
277/// The firmware guards this opcode behind `V2IP_SUPPORT_BLACKLIST`, which is 0
278/// in shipping builds, so nothing in current firmware emits it.
279#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
280pub struct V2ipBlacklistChange {
281    /// The device being listed.
282    pub target: DeviceUid,
283    /// Whether it is being registered rather than removed.
284    pub registered: bool,
285}
286
287/// What a [`VideoWallCommand`] asks the sink to do with the window.
288#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
289pub struct VideoWallOp(u8);
290
291impl VideoWallOp {
292    /// Applies the window without persisting it.
293    pub const PREVIEW: Self = Self(0);
294    /// Persists the window as the sink's wall setting.
295    pub const STORE: Self = Self(1);
296    /// Restores the persisted setting; carries no window.
297    pub const REVERT: Self = Self(2);
298
299    /// Wraps a raw wire value, including one this library has no name for.
300    pub const fn from_wire(value: u8) -> Self {
301        Self(value)
302    }
303
304    /// Returns the raw wire value.
305    pub const fn to_wire(self) -> u8 {
306        self.0
307    }
308}
309
310impl fmt::Display for VideoWallOp {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        f.write_str(match *self {
313            Self::PREVIEW => "preview",
314            Self::STORE => "store",
315            Self::REVERT => "revert",
316            _ => "unknown",
317        })
318    }
319}
320
321/// Where a video-wall sink's window sits, and the picture it was measured
322/// against.
323///
324/// The raster travels with the window because only the sender knows what the
325/// installer drew against; a sink deriving it from what it happens to be
326/// showing would place the window against the wrong picture.
327///
328/// Nothing on the receiving side is guaranteed to check any of this, so
329/// [`VideoWallWindow::validate`] runs before every send. See
330/// [`crate::Remote::store_video_wall`] for why that matters.
331#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
332pub struct VideoWallWindow {
333    /// Window origin, horizontal. A multiple of [`VIDEO_WALL_POS_ALIGN`].
334    pub pos_x: u16,
335    /// Window origin, vertical. No alignment constraint.
336    pub pos_y: u16,
337    /// Window width. A multiple of [`VIDEO_WALL_WIDTH_ALIGN`], and at least
338    /// [`VIDEO_WALL_MIN_SIZE`] unless it is zero.
339    pub width: u16,
340    /// Window height, at least [`VIDEO_WALL_MIN_SIZE`] unless it is zero. No
341    /// alignment constraint.
342    pub height: u16,
343    /// Active picture width the window was measured against.
344    pub raster_w: u16,
345    /// Active picture height the window was measured against.
346    pub raster_h: u16,
347}
348
349/// The window that clears a wall, leaving the sink showing the whole frame.
350///
351/// A zero width or height is how the protocol spells "clear", so this is a
352/// legitimate window rather than one that fails [`VideoWallWindow::validate`].
353pub const VIDEO_WALL_CLEARED: VideoWallWindow = VideoWallWindow {
354    pos_x: 0,
355    pos_y: 0,
356    width: 0,
357    height: 0,
358    raster_w: 0,
359    raster_h: 0,
360};
361
362/// The horizontal origin must be a multiple of this: the sink's buffer start
363/// has to be aligned.
364pub const VIDEO_WALL_POS_ALIGN: u16 = 64;
365
366/// The width must be a multiple of this: the sink's pipeline moves four pixels
367/// per clock.
368pub const VIDEO_WALL_WIDTH_ALIGN: u16 = 4;
369
370/// Neither side of a window may be smaller than this, the scaler's minimum.
371pub const VIDEO_WALL_MIN_SIZE: u16 = 64;
372
373impl VideoWallWindow {
374    /// Reports whether this window clears the wall rather than placing one.
375    pub const fn is_cleared(&self) -> bool {
376        self.width == 0 || self.height == 0
377    }
378
379    /// Checks the geometry the sink is not guaranteed to check itself.
380    ///
381    /// The three alignments follow the sink's hardware and a live unit reports
382    /// them over HTTP, so a caller with access to one can read them rather
383    /// than trust the constants here. The containment rule has no such source:
384    /// it is checked by the sink's own HTTP path and by nothing on the mesh
385    /// path, at any version.
386    ///
387    /// A cleared window passes: zero is the protocol's word for "clear", not a
388    /// window too small to draw.
389    pub fn validate(&self) -> Result<(), &'static str> {
390        if self.is_cleared() {
391            return Ok(());
392        }
393        if self.pos_x % VIDEO_WALL_POS_ALIGN != 0 {
394            return Err("a video wall window's horizontal origin must be a multiple of 64");
395        }
396        if self.width % VIDEO_WALL_WIDTH_ALIGN != 0 {
397            return Err("a video wall window's width must be a multiple of 4");
398        }
399        if self.width < VIDEO_WALL_MIN_SIZE || self.height < VIDEO_WALL_MIN_SIZE {
400            return Err("neither side of a video wall window may be smaller than 64");
401        }
402        // Widened, because a window running off the raster is exactly the case
403        // where a u16 sum would wrap and read as containment.
404        if u32::from(self.pos_x) + u32::from(self.width) > u32::from(self.raster_w)
405            || u32::from(self.pos_y) + u32::from(self.height) > u32::from(self.raster_h)
406        {
407            return Err("a video wall window must fit inside the raster it names");
408        }
409        Ok(())
410    }
411}
412
413impl fmt::Display for VideoWallWindow {
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        if self.is_cleared() {
416            return f.write_str("cleared");
417        }
418        write!(
419            f,
420            "{}x{}+{}+{} of {}x{}",
421            self.width, self.height, self.pos_x, self.pos_y, self.raster_w, self.raster_h
422        )
423    }
424}
425
426/// Asks one sink to crop its source to a wall window.
427///
428/// This replaces the sink's window outright: unlike a V2IP device config, no
429/// field carries a validity marker, and a zero width or height is the wire
430/// spelling of "clear the wall and show the full frame" rather than "unset".
431///
432/// The opcode belongs to the loadable v2ipwall module rather than MatrixOS, and
433/// a wall has no object of its own on the wire: it is a set of sinks each
434/// holding one rectangle, one frame each. It is a command with no reply, so
435/// nothing here is ever a status readback.
436#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
437pub struct VideoWallCommand {
438    /// The sink to act on.
439    pub target: DeviceUid,
440    /// Window origin, horizontal.
441    pub pos_x: u16,
442    /// Window origin, vertical.
443    pub pos_y: u16,
444    /// Window width.
445    pub width: u16,
446    /// Window height.
447    pub height: u16,
448    /// Active picture width the window was authored against, as on
449    /// [`VideoWallWindow`].
450    pub raster_w: u16,
451    /// Active picture height the window was authored against.
452    pub raster_h: u16,
453    /// What to do with the window.
454    pub op: VideoWallOp,
455}
456
457impl VideoWallCommand {
458    /// Reports whether the geometry in this command is meaningful.
459    ///
460    /// A revert zeroes the window and raster and the receiver ignores those
461    /// bytes, so its zeros are not a clear.
462    pub fn has_window(&self) -> bool {
463        self.op != VideoWallOp::REVERT
464    }
465
466    /// Reports a command that clears the wall and shows the full frame.
467    pub fn is_cleared(&self) -> bool {
468        self.has_window() && (self.width == 0 || self.height == 0)
469    }
470}
471
472impl fmt::Display for VideoWallCommand {
473    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474        if !self.has_window() {
475            return f.write_str("video wall revert");
476        }
477        if self.is_cleared() {
478            return write!(f, "video wall {}: clear", self.op);
479        }
480        write!(
481            f,
482            "video wall {}: {}x{}+{}+{} of {}x{}",
483            self.op, self.width, self.height, self.pos_x, self.pos_y, self.raster_w, self.raster_h
484        )
485    }
486}
487
488/// A command addressed to a multiviewer.
489///
490/// The parameters past the envelope are exposed as raw bytes: the opcode
491/// belongs to the multiviewer module rather than MatrixOS, so beyond the
492/// envelope there is no firmware source here to pin per-sub-command field
493/// semantics against.
494#[derive(Clone, Debug, Default, PartialEq, Eq)]
495pub struct MultiviewerCommand {
496    /// The multiviewer being addressed.
497    pub target: DeviceUid,
498    /// The sub-opcode. A value this library has no name for still arrives.
499    pub op: u8,
500    /// Everything after the envelope, empty when the frame carries none.
501    pub params: Vec<u8>,
502}
503
504impl fmt::Display for MultiviewerCommand {
505    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506        write!(
507            f,
508            "multiviewer command {} for {} ({} param bytes)",
509            self.op,
510            self.target,
511            self.params.len()
512        )
513    }
514}
515
516/// An audio input-selection change: which source endpoint a sink endpoint was
517/// switched to.
518///
519/// The sink is named twice on the wire, once as the command header's target and
520/// again at the head of the body; the body's second uid is the source.
521#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
522pub struct AudioChangeSource {
523    /// The device whose endpoint is being listened to.
524    pub source_uid: DeviceUid,
525    /// The endpoint being listened to.
526    pub source_id: u16,
527    /// The device doing the listening.
528    pub target_uid: DeviceUid,
529    /// The endpoint doing the listening.
530    pub target_id: u16,
531}
532
533impl fmt::Display for AudioChangeSource {
534    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
535        write!(
536            f,
537            "audio source change {}:{} -> {}:{}",
538            self.source_uid, self.source_id, self.target_uid, self.target_id
539        )
540    }
541}