Skip to main content

mx_remote_ffi/
events.rs

1// Author: Lars Op den Kamp (lars@opdenkamp-it.nl)
2// Copyright (c) 2026 Op den Kamp IT Solutions
3
4//! The event bridge: a C table of function pointers, and the handler that
5//! calls into it.
6//!
7//! Every member may be null, and a null member drops its event. Two of them
8//! are worth naming first, because a program that sets only those two is
9//! already complete: `on_device_update` fires after every device-level event
10//! and `on_bay_update` after every bay-level one, so a caller that redraws
11//! from `mxr_device()` and `mxr_bay()`
12//! needs nothing else.
13//!
14//! The rest divide by what they can tell a caller that a snapshot cannot. An
15//! event whose payload is state carries only the identifier, because the
16//! snapshot is where that value lives and a copy in the callback could only be
17//! staler. An event that is a request or a one-off - a key press, a reboot
18//! demand, an IR blast - carries a struct, because nothing stores it.
19//!
20//! Callbacks run on the receive thread with no lock held, one at a time.
21//! Calling back into the library from one is safe; blocking in one stalls
22//! every device. Pointers handed to a callback are borrowed for the length of
23//! that call, so anything needed afterwards must be copied.
24
25use std::ffi::{c_char, c_void, CString};
26
27use mx_remote::{
28    ActionTransmitRequest, ArcStatus, AudioChangeSource, AudioClip, BayNameChange, BayUid,
29    DeviceUid, EdidProfileChange, EdidRecord, EdidRequest, EventHandler, FactoryResetRequest,
30    IrCapture, IrMeta, IrTransmitRequest, KeyTransmitRequest, LinkFeature, MultiviewerCommand,
31    PowerStatus, RcAction, RcKey, RebootRequest, SetRouteRequest, V2ipBlacklistChange,
32    V2ipPowerSaveRequest, VideoWallCommand, VolumeMuteStatus,
33};
34
35use crate::abi::{bay_or_zero, guard, mxr_bay_uid_t, mxr_tribool_t, mxr_uid_t};
36use crate::info::{mxr_arc_status_t, mxr_power_status_t};
37
38// ---- callback signatures ----
39
40/// Names only the device the event concerns.
41pub type mxr_device_cb = Option<extern "C" fn(userdata: *mut c_void, device: mxr_uid_t)>;
42/// Names a device and a flag.
43pub type mxr_device_bool_cb =
44    Option<extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, value: bool)>;
45/// Names a device and a second device.
46pub type mxr_device_uid_cb =
47    Option<extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, other: mxr_uid_t)>;
48/// Names a device and a 16-bit value.
49pub type mxr_device_u16_cb =
50    Option<extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, value: u16)>;
51/// Names a device, one of its audio endpoints, and a flag.
52pub type mxr_endpoint_bool_cb =
53    Option<extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, endpoint: u16, value: bool)>;
54/// Names a device, one of its audio endpoints, and a 32-bit value.
55pub type mxr_endpoint_u32_cb =
56    Option<extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, endpoint: u16, value: u32)>;
57/// Names a device, a status code and a message.
58pub type mxr_system_status_cb = Option<
59    extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, status: u16, message: *const c_char),
60>;
61
62/// Names only the bay the event concerns.
63pub type mxr_bay_cb = Option<extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t)>;
64/// Names a bay and a flag.
65pub type mxr_bay_bool_cb =
66    Option<extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, value: bool)>;
67/// Names a bay and a string, borrowed for the call.
68pub type mxr_bay_str_cb =
69    Option<extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, value: *const c_char)>;
70/// Names a bay and another bay, the zero device standing for none.
71pub type mxr_bay_bay_cb =
72    Option<extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, other: mxr_bay_uid_t)>;
73/// Names a bay and an 8-bit value.
74pub type mxr_bay_u8_cb =
75    Option<extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, value: u8)>;
76/// Names a bay and a 16-bit value.
77pub type mxr_bay_u16_cb =
78    Option<extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, value: u16)>;
79/// Names a bay, its combined volume percentage and its mute state.
80pub type mxr_volume_cb = Option<
81    extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, volume: u8, muted: mxr_tribool_t),
82>;
83/// Names a bay and the power state of what is connected to it.
84pub type mxr_power_cb =
85    Option<extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, power: mxr_power_status_t)>;
86/// Names a bay and its audio return channel.
87pub type mxr_arc_cb =
88    Option<extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, arc: mxr_arc_status_t)>;
89/// Names a bay and the link that was made to it.
90pub type mxr_bay_linked_cb = Option<
91    extern "C" fn(
92        userdata: *mut c_void,
93        bay: mxr_bay_uid_t,
94        linked_serial: *const c_char,
95        bay_name: *const c_char,
96        features: u32,
97    ),
98>;
99/// Names a bay and the link that was removed from it.
100pub type mxr_bay_unlinked_cb = Option<
101    extern "C" fn(
102        userdata: *mut c_void,
103        bay: mxr_bay_uid_t,
104        linked_serial: *const c_char,
105        bay_name: *const c_char,
106    ),
107>;
108
109// ---- notification payloads ----
110
111/// Asks a device, addressed by serial, to switch a sink.
112#[repr(C)]
113#[derive(Clone, Copy)]
114pub struct mxr_set_route_request_t {
115    /// Serial of the device to act on, borrowed for the call.
116    pub serial: *const c_char,
117    /// Output bay to switch.
118    pub sink_bay: u16,
119    /// Source bay to switch it to.
120    pub source_bay: u16,
121    /// Whether to skip the power-on commands that normally accompany a switch.
122    pub no_power_on: bool,
123    /// Set when the request routes audio only.
124    pub audio_only: bool,
125}
126
127/// Asks one device for its EDID.
128#[repr(C)]
129#[derive(Clone, Copy)]
130pub struct mxr_edid_request_t {
131    /// The device being asked.
132    pub target: mxr_uid_t,
133    /// Whether the sink's EDID is wanted rather than the source's.
134    pub output: bool,
135}
136
137/// One EDID block from a device's reply.
138#[repr(C)]
139#[derive(Clone, Copy)]
140pub struct mxr_edid_record_t {
141    /// True for a sink's EDID, false for a source's.
142    pub output: bool,
143    /// A base block plus one extension block, borrowed for the call.
144    pub data: *const u8,
145    /// Length of `data`, normally 256.
146    pub data_len: usize,
147}
148
149/// Asks a device to rename one of its bays.
150#[repr(C)]
151#[derive(Clone, Copy)]
152pub struct mxr_bay_name_change_t {
153    /// The device to act on.
154    pub target: mxr_uid_t,
155    /// The bay to rename.
156    pub port: u16,
157    /// The new name, borrowed for the call.
158    pub name: *const c_char,
159}
160
161/// Asks a device to switch its input EDID profile.
162#[repr(C)]
163#[derive(Clone, Copy)]
164pub struct mxr_edid_profile_change_t {
165    /// The device to act on.
166    pub target: mxr_uid_t,
167    /// The profile to switch to.
168    pub profile: u16,
169}
170
171/// Asks peers to factory-reset.
172#[repr(C)]
173#[derive(Clone, Copy)]
174pub struct mxr_factory_reset_request_t {
175    /// Set by the broadcast form, which targets every peer.
176    pub all: bool,
177    /// The single device addressed, zero when `all` is set or when the request
178    /// addresses only its sender.
179    pub target: mxr_uid_t,
180}
181
182/// Asks a sink to enter or leave power save.
183#[repr(C)]
184#[derive(Clone, Copy)]
185pub struct mxr_power_save_request_t {
186    /// The sink to act on, zero on the broadcast form.
187    pub target: mxr_uid_t,
188    /// Whether power save is being entered.
189    pub enabled: bool,
190}
191
192/// Asks one device to send a remote-control key on a bay.
193#[repr(C)]
194#[derive(Clone, Copy)]
195pub struct mxr_key_transmit_request_t {
196    /// The device to act on.
197    pub target: mxr_uid_t,
198    /// Bay in the target's own numbering, which is not a port number.
199    pub local_bay: u16,
200    /// The key to send.
201    pub key: u16,
202}
203
204/// Asks one device to perform a remote-control action.
205#[repr(C)]
206#[derive(Clone, Copy)]
207pub struct mxr_action_transmit_request_t {
208    /// The device to act on.
209    pub target: mxr_uid_t,
210    /// Bay in the target's own numbering, which is not a port number.
211    pub local_bay: u16,
212    /// The action to perform.
213    pub action: u16,
214}
215
216/// The metadata shared by the raw-IR capture and transmit frames.
217#[repr(C)]
218#[derive(Clone, Copy)]
219pub struct mxr_ir_meta_t {
220    /// Tick length of the timing values.
221    pub timer_resolution: u16,
222    /// Carrier frequency in Hz.
223    pub frequency: u16,
224    /// Number of timing values that follow.
225    pub nb_timings: u16,
226    /// Index at which the repeat section starts.
227    pub repeat_offset: u16,
228    /// Capture status.
229    pub status: u8,
230}
231
232impl From<IrMeta> for mxr_ir_meta_t {
233    fn from(m: IrMeta) -> Self {
234        Self {
235            timer_resolution: m.timer_resolution,
236            frequency: m.frequency,
237            nb_timings: m.nb_timings,
238            repeat_offset: m.repeat_offset,
239            status: m.status,
240        }
241    }
242}
243
244/// Raw IR captured on a bay of the sending device.
245#[repr(C)]
246#[derive(Clone, Copy)]
247pub struct mxr_ir_capture_t {
248    /// Sender clock at capture time.
249    pub timestamp: u32,
250    /// Sender clock at the last signal change.
251    pub last_change: u32,
252    /// Metadata for the timings.
253    pub meta: mxr_ir_meta_t,
254    /// The raw on/off timing blob, borrowed for the call.
255    pub timings: *const u8,
256    /// Length of `timings`.
257    pub timings_len: usize,
258}
259
260/// Asks one device to blast raw IR on one of its local bays.
261#[repr(C)]
262#[derive(Clone, Copy)]
263pub struct mxr_ir_transmit_request_t {
264    /// The device to act on.
265    pub target: mxr_uid_t,
266    /// Bay mode in the target's own numbering, which is not a port number.
267    pub local_mode: u8,
268    /// Bay number in the target's own numbering, which is not a port number.
269    pub local_bay: u8,
270    /// Sender clock at send time.
271    pub timestamp: u32,
272    /// Metadata for the timings.
273    pub meta: mxr_ir_meta_t,
274    /// The raw on/off timing blob, borrowed for the call.
275    pub timings: *const u8,
276    /// Length of `timings`.
277    pub timings_len: usize,
278}
279
280/// Registers or unregisters a device on the source blacklist.
281#[repr(C)]
282#[derive(Clone, Copy)]
283pub struct mxr_blacklist_change_t {
284    /// The device being listed.
285    pub target: mxr_uid_t,
286    /// Whether it is being registered rather than removed.
287    pub registered: bool,
288}
289
290/// Asks one sink to crop its source to a wall window.
291///
292/// The window replaces the sink's outright: a zero width or height is the wire
293/// spelling of "clear the wall and show the full frame", not of "unset". A
294/// revert carries no window, and the geometry in it means nothing.
295#[repr(C)]
296#[derive(Clone, Copy)]
297pub struct mxr_video_wall_command_t {
298    /// The sink to act on.
299    pub target: mxr_uid_t,
300    /// Window origin, horizontal.
301    pub pos_x: u16,
302    /// Window origin, vertical.
303    pub pos_y: u16,
304    /// Window width.
305    pub width: u16,
306    /// Window height.
307    pub height: u16,
308    /// Active picture width the window was authored against.
309    pub raster_w: u16,
310    /// Active picture height the window was authored against.
311    pub raster_h: u16,
312    /// 0 preview, 1 store, 2 revert.
313    pub op: u8,
314}
315
316/// A command addressed to a multiviewer.
317///
318/// The parameters are raw: the opcode belongs to the multiviewer module rather
319/// than to MatrixOS, so there is no firmware source here to pin per-sub-command
320/// field semantics against.
321#[repr(C)]
322#[derive(Clone, Copy)]
323pub struct mxr_multiviewer_command_t {
324    /// The multiviewer being addressed.
325    pub target: mxr_uid_t,
326    /// The sub-opcode. A value this library has no name for still arrives.
327    pub op: u8,
328    /// Everything after the envelope, borrowed for the call.
329    pub params: *const u8,
330    /// Length of `params`.
331    pub params_len: usize,
332}
333
334/// Which source endpoint an audio sink endpoint was switched to.
335#[repr(C)]
336#[derive(Clone, Copy)]
337pub struct mxr_audio_change_source_t {
338    /// The device whose endpoint is being listened to.
339    pub source_uid: mxr_uid_t,
340    /// The endpoint being listened to.
341    pub source_id: u16,
342    /// The device doing the listening.
343    pub target_uid: mxr_uid_t,
344    /// The endpoint doing the listening.
345    pub target_id: u16,
346}
347
348/// Carries a request addressed to a device.
349pub type mxr_set_route_cb = Option<
350    extern "C" fn(
351        userdata: *mut c_void,
352        device: mxr_uid_t,
353        request: *const mxr_set_route_request_t,
354    ),
355>;
356/// Carries a request for a device's EDID.
357pub type mxr_edid_request_cb = Option<
358    extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, request: *const mxr_edid_request_t),
359>;
360/// Carries one EDID block a device replied with.
361pub type mxr_edid_record_cb = Option<
362    extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, record: *const mxr_edid_record_t),
363>;
364/// Carries a request to rename a bay.
365pub type mxr_bay_name_change_cb = Option<
366    extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, change: *const mxr_bay_name_change_t),
367>;
368/// Carries a request to switch an EDID profile.
369pub type mxr_edid_profile_change_cb = Option<
370    extern "C" fn(
371        userdata: *mut c_void,
372        device: mxr_uid_t,
373        change: *const mxr_edid_profile_change_t,
374    ),
375>;
376/// Carries a factory-reset request.
377pub type mxr_factory_reset_cb = Option<
378    extern "C" fn(
379        userdata: *mut c_void,
380        device: mxr_uid_t,
381        request: *const mxr_factory_reset_request_t,
382    ),
383>;
384/// Carries a power-save request.
385pub type mxr_power_save_cb = Option<
386    extern "C" fn(
387        userdata: *mut c_void,
388        device: mxr_uid_t,
389        request: *const mxr_power_save_request_t,
390    ),
391>;
392/// Carries a request to send a remote-control key.
393pub type mxr_key_transmit_cb = Option<
394    extern "C" fn(
395        userdata: *mut c_void,
396        device: mxr_uid_t,
397        request: *const mxr_key_transmit_request_t,
398    ),
399>;
400/// Carries a request to perform a remote-control action.
401pub type mxr_action_transmit_cb = Option<
402    extern "C" fn(
403        userdata: *mut c_void,
404        device: mxr_uid_t,
405        request: *const mxr_action_transmit_request_t,
406    ),
407>;
408/// Carries a request to blast raw infrared.
409pub type mxr_ir_transmit_cb = Option<
410    extern "C" fn(
411        userdata: *mut c_void,
412        device: mxr_uid_t,
413        request: *const mxr_ir_transmit_request_t,
414    ),
415>;
416/// Carries a blacklist change.
417pub type mxr_blacklist_cb = Option<
418    extern "C" fn(userdata: *mut c_void, device: mxr_uid_t, change: *const mxr_blacklist_change_t),
419>;
420/// Carries a video wall command.
421pub type mxr_video_wall_cb = Option<
422    extern "C" fn(
423        userdata: *mut c_void,
424        device: mxr_uid_t,
425        command: *const mxr_video_wall_command_t,
426    ),
427>;
428/// Carries a multiviewer command.
429pub type mxr_multiviewer_command_cb = Option<
430    extern "C" fn(
431        userdata: *mut c_void,
432        device: mxr_uid_t,
433        command: *const mxr_multiviewer_command_t,
434    ),
435>;
436/// Carries an audio input selection.
437pub type mxr_audio_select_cb = Option<
438    extern "C" fn(
439        userdata: *mut c_void,
440        device: mxr_uid_t,
441        change: *const mxr_audio_change_source_t,
442    ),
443>;
444/// Carries raw infrared captured on a bay.
445pub type mxr_ir_capture_cb = Option<
446    extern "C" fn(userdata: *mut c_void, bay: mxr_bay_uid_t, capture: *const mxr_ir_capture_t),
447>;
448
449/// What to call when something happens.
450///
451/// Zero the whole struct and fill in only what is wanted: a null member drops
452/// its event. `userdata` is whatever was passed to
453/// `mxr_remote_new()` and is never examined here.
454#[repr(C)]
455#[derive(Clone, Copy)]
456pub struct mxr_callbacks_t {
457    /// Fires after every device-level event below.
458    pub on_device_update: mxr_device_cb,
459    /// Fires after every bay-level event below.
460    pub on_bay_update: mxr_bay_cb,
461
462    /// The device's configuration changed.
463    pub on_device_config_changed: mxr_device_cb,
464    /// The device has reported every part of its configuration.
465    pub on_device_config_complete: mxr_device_cb,
466    /// The device started or stopped answering.
467    pub on_device_online_changed: mxr_device_bool_cb,
468    /// The device reported new temperatures; read them with
469    /// `mxr_device_temperatures()`.
470    pub on_device_temperature_changed: mxr_device_cb,
471    /// A firmware component reported its version; read it with
472    /// `mxr_device_firmware()`.
473    pub on_firmware_version_changed: mxr_device_cb,
474    /// The device reported a status about itself.
475    pub on_system_status_changed: mxr_system_status_cb,
476    /// A network port reported its link state; read it with
477    /// `mxr_network_status()`.
478    pub on_network_status_changed: mxr_device_cb,
479    /// The device reported V2IP statistics; read them with
480    /// `mxr_v2ip_stats()`.
481    pub on_v2ip_stats_changed: mxr_device_cb,
482    /// The streams the device's source bays advertise changed; read them with
483    /// `mxr_v2ip_sources()`.
484    pub on_v2ip_sources_changed: mxr_device_cb,
485    /// The device's V2IP encoder configuration changed; read it with
486    /// `mxr_v2ip_details()`.
487    pub on_v2ip_details_changed: mxr_device_cb,
488    /// The streams the device's sink is subscribed to changed; read them with
489    /// `mxr_v2ip_sink()`.
490    ///
491    /// A route request addressed to the device fires this as soon as it is
492    /// seen, so this reports what the mesh now believes rather than what the
493    /// device confirmed - it acknowledges nothing, and only its own
494    /// configuration report, sent on its own schedule, settles a route.
495    pub on_v2ip_sink_changed: mxr_device_cb,
496    /// A multiviewer reported its state; read it with
497    /// `mxr_multiviewer_status()`.
498    pub on_multiviewer_status_changed: mxr_device_cb,
499    /// The device reported its audio endpoint tree; read it with
500    /// `mxr_audio_endpoints()`.
501    pub on_audio_endpoints_changed: mxr_device_cb,
502    /// The device reported its mesh master.
503    pub on_mesh_master_changed: mxr_device_uid_cb,
504    /// The device reported its view of the mesh topology; read it with
505    /// `mxr_topology()`.
506    pub on_topology_changed: mxr_device_cb,
507    /// A ProAmp8 reported its Dolby settings; read them with
508    /// `mxr_dolby_settings()`.
509    pub on_amp_dolby_settings_changed: mxr_device_cb,
510    /// Installer setup was completed or cleared.
511    pub on_setup_status_changed: mxr_device_bool_cb,
512    /// The installer identifier changed.
513    pub on_installer_id_changed: mxr_device_u16_cb,
514    /// The sink was told to show a window; read it with
515    /// `mxr_v2ip_tiling()`.
516    pub on_tiling_changed: mxr_device_cb,
517    /// A source bay's remote-control configuration changed; read it with
518    /// `mxr_rc_settings()`.
519    pub on_rc_settings_changed: mxr_device_cb,
520    /// A V2IP device was linked to a remote peer.
521    pub on_v2ip_link_changed: mxr_device_uid_cb,
522    /// A multiviewer command arrived.
523    pub on_multiviewer_command: mxr_multiviewer_command_cb,
524    /// An audio endpoint was switched to a new source.
525    pub on_audio_select_input: mxr_audio_select_cb,
526    /// An audio endpoint was muted or unmuted.
527    pub on_audio_endpoint_mute: mxr_endpoint_bool_cb,
528    /// An audio endpoint's trigger changed.
529    pub on_audio_endpoint_trigger: mxr_endpoint_bool_cb,
530    /// An audio endpoint's volume changed.
531    pub on_audio_endpoint_volume: mxr_endpoint_u32_cb,
532    /// A peer asked every device to announce itself.
533    pub on_discover_request: mxr_device_cb,
534    /// A peer asked a device to switch a sink.
535    pub on_set_route_requested: mxr_set_route_cb,
536    /// A peer asked a device for its EDID.
537    pub on_edid_requested: mxr_edid_request_cb,
538    /// A device answered with its EDID.
539    pub on_edid_received: mxr_edid_record_cb,
540    /// A peer asked a device to rename a bay.
541    pub on_bay_name_change_requested: mxr_bay_name_change_cb,
542    /// A peer asked a device to switch its EDID profile.
543    pub on_edid_profile_change_requested: mxr_edid_profile_change_cb,
544    /// A peer asked a device to reboot. The second identifier is the device
545    /// being asked, which is not always the sender.
546    pub on_reboot_requested: mxr_device_uid_cb,
547    /// A peer asked devices to factory-reset.
548    pub on_factory_reset_requested: mxr_factory_reset_cb,
549    /// A device sent its monitoring pulse.
550    pub on_monitoring_pulse: mxr_device_cb,
551    /// A peer asked a device to upgrade its FPGA.
552    pub on_upgrade_fpga_requested: mxr_device_cb,
553    /// A peer asked a device to re-detect its bays.
554    pub on_detect_bays_requested: mxr_device_cb,
555    /// A peer asked a sink to enter or leave power save.
556    pub on_power_save_requested: mxr_power_save_cb,
557    /// A peer asked a device to send a remote-control key.
558    pub on_key_transmit_requested: mxr_key_transmit_cb,
559    /// A peer asked a device to perform a remote-control action.
560    pub on_action_transmit_requested: mxr_action_transmit_cb,
561    /// A peer asked a device to blast raw infrared.
562    pub on_ir_transmit_requested: mxr_ir_transmit_cb,
563    /// A device was added to or removed from the source blacklist.
564    pub on_blacklist_changed: mxr_blacklist_cb,
565    /// A video wall command arrived.
566    pub on_video_wall_command: mxr_video_wall_cb,
567
568    /// A bay was seen for the first time.
569    pub on_bay_registered: mxr_bay_cb,
570    /// The bay's routed video source changed, zero when it was unrouted.
571    pub on_video_source_changed: mxr_bay_bay_cb,
572    /// The bay's routed audio source changed, zero when it was unrouted.
573    pub on_audio_source_changed: mxr_bay_bay_cb,
574    /// The bay's volume or mute state changed.
575    pub on_volume_changed: mxr_volume_cb,
576    /// The attached device's power state changed.
577    pub on_power_changed: mxr_power_cb,
578    /// The bay was renamed.
579    pub on_name_changed: mxr_bay_str_cb,
580    /// A signal appeared or disappeared.
581    pub on_signal_detected_changed: mxr_bay_bool_cb,
582    /// The bay started or stopped reporting a fault.
583    pub on_faulty_changed: mxr_bay_bool_cb,
584    /// The bay was hidden or shown.
585    pub on_hidden_changed: mxr_bay_bool_cb,
586    /// Power over Ethernet started or stopped supplying the bay.
587    pub on_poe_powered_changed: mxr_bay_bool_cb,
588    /// The HDBaseT link came up or went down.
589    pub on_hdbt_connected_changed: mxr_bay_bool_cb,
590    /// The signal format description changed.
591    pub on_signal_type_changed: mxr_bay_str_cb,
592    /// Hot-plug detect was asserted or released.
593    pub on_hpd_detected_changed: mxr_bay_bool_cb,
594    /// A CEC device answered or stopped answering.
595    pub on_cec_detected_changed: mxr_bay_bool_cb,
596    /// The audio return channel changed.
597    pub on_arc_changed: mxr_arc_cb,
598    /// The input's EDID profile changed.
599    pub on_edid_profile_changed: mxr_bay_u16_cb,
600    /// The input's remote-control type changed.
601    pub on_rc_type_changed: mxr_bay_u8_cb,
602    /// A remote-control key was pressed on the bay.
603    pub on_key_pressed: mxr_bay_u16_cb,
604    /// A remote-control action was received on the bay.
605    pub on_action_received: mxr_bay_u16_cb,
606    /// The bay started or stopped mirroring another output, zero when it
607    /// stopped.
608    pub on_mirror_status_changed: mxr_bay_bay_cb,
609    /// A ProAmp8 zone's settings changed; read them with
610    /// `mxr_bay_amp_settings()`.
611    pub on_amp_zone_settings_changed: mxr_bay_cb,
612    /// A volume step was requested on the bay.
613    pub on_volume_step: mxr_bay_bool_cb,
614    /// The bay detected audio clipping, at the reported level.
615    pub on_audio_clip: mxr_bay_u8_cb,
616    /// Raw infrared was captured on the bay.
617    pub on_ir_captured: mxr_ir_capture_cb,
618    /// The devices filtered out of this sink's picker changed; read them with
619    /// `mxr_bay_filtered()`.
620    pub on_filtered_devices_changed: mxr_bay_cb,
621    /// The audio endpoint the bay carries changed.
622    pub on_audio_endpoint_changed: mxr_bay_u8_cb,
623    /// The bay's V2IP encoder was enabled or disabled.
624    pub on_encoder_disabled_changed: mxr_bay_bool_cb,
625    /// The bay's V2IP decoder was enabled or disabled.
626    pub on_decoder_disabled_changed: mxr_bay_bool_cb,
627
628    /// The bay was linked to a bay on another device. Both ends are told, so
629    /// both fire: `bay_name` names the bay whose link record changed, which is
630    /// this bay on the device that reported the change and the far bay on its
631    /// peer.
632    pub on_bay_linked: mxr_bay_linked_cb,
633    /// The bay's link to another device was removed. The arguments describe
634    /// the link that went, and mean what they do on `on_bay_linked`.
635    pub on_bay_unlinked: mxr_bay_unlinked_cb,
636}
637
638/// The caller's cookie, which this library carries and never reads.
639///
640/// # Safety
641///
642/// The contract on `mxr_remote_new()` is what makes
643/// these impls sound: the caller keeps the pointer valid, and safe to use from
644/// the library's threads, until the client is freed. Nothing here dereferences
645/// it.
646struct UserData(*mut c_void);
647
648// SAFETY: an opaque pointer this library only ever copies. See the type's own
649// docs for the contract the caller holds up.
650unsafe impl Send for UserData {}
651// SAFETY: as above.
652unsafe impl Sync for UserData {}
653
654/// Turns library events into calls through a C table.
655pub(crate) struct Bridge {
656    cb: mxr_callbacks_t,
657    userdata: UserData,
658}
659
660impl Bridge {
661    /// Copies the caller's table, so a caller may free or reuse theirs.
662    pub(crate) fn new(table: &mxr_callbacks_t, userdata: *mut c_void) -> Self {
663        Self {
664            cb: *table,
665            userdata: UserData(userdata),
666        }
667    }
668
669    fn ud(&self) -> *mut c_void {
670        self.userdata.0
671    }
672}
673
674/// Calls one member of the table, if the caller set it.
675///
676/// The guard is here rather than at the caller because this is an exit point,
677/// not an entry one: a panic while marshalling would otherwise unwind through
678/// the receive thread and take the client down with it.
679macro_rules! forward {
680    ($self:ident.$field:ident( $($arg:expr),* $(,)? )) => {
681        if let Some(f) = $self.cb.$field {
682            guard((), || f($self.ud() $(, $arg)*));
683        }
684    };
685}
686
687/// Calls `body` with `text` as a C string that lives for the call.
688fn with_cstr<R>(text: &str, body: impl FnOnce(*const c_char) -> R) -> R {
689    // A NUL inside would cut the string short in C. Protocol strings are read
690    // up to their first NUL, so this is a fallback, not a case that happens.
691    let owned = CString::new(text).unwrap_or_else(|_| c"".to_owned());
692    body(owned.as_ptr())
693}
694
695/// The identifier a request names, where the protocol's zero stands for
696/// "unaddressed": a broadcast, or a request that addresses only its sender.
697fn uid_or_zero(uid: Option<DeviceUid>) -> mxr_uid_t {
698    uid.unwrap_or(DeviceUid::ZERO).into()
699}
700
701impl EventHandler for Bridge {
702    fn on_device_update(&self, device: DeviceUid) {
703        forward!(self.on_device_update(device.into()));
704    }
705
706    fn on_bay_update(&self, bay: BayUid) {
707        forward!(self.on_bay_update(bay.into()));
708    }
709
710    // ---- device ----
711
712    fn on_device_config_changed(&self, device: DeviceUid) {
713        forward!(self.on_device_config_changed(device.into()));
714    }
715
716    fn on_device_config_complete(&self, device: DeviceUid) {
717        forward!(self.on_device_config_complete(device.into()));
718    }
719
720    fn on_device_online_changed(&self, device: DeviceUid, online: bool) {
721        forward!(self.on_device_online_changed(device.into(), online));
722    }
723
724    fn on_device_temperature_changed(&self, device: DeviceUid, _temperatures: Vec<u8>) {
725        forward!(self.on_device_temperature_changed(device.into()));
726    }
727
728    fn on_firmware_version_changed(&self, device: DeviceUid, _version: mx_remote::FirmwareVersion) {
729        forward!(self.on_firmware_version_changed(device.into()));
730    }
731
732    fn on_system_status_changed(&self, device: DeviceUid, status: u16, message: String) {
733        with_cstr(&message, |m| {
734            forward!(self.on_system_status_changed(device.into(), status, m));
735        });
736    }
737
738    fn on_network_status_changed(&self, device: DeviceUid, _status: mx_remote::NetworkPortStatus) {
739        forward!(self.on_network_status_changed(device.into()));
740    }
741
742    fn on_v2ip_stats_changed(&self, device: DeviceUid, _stats: mx_remote::V2ipDeviceStats) {
743        forward!(self.on_v2ip_stats_changed(device.into()));
744    }
745
746    fn on_v2ip_sources_changed(
747        &self,
748        device: DeviceUid,
749        _sources: Vec<mx_remote::V2ipStreamSources>,
750    ) {
751        forward!(self.on_v2ip_sources_changed(device.into()));
752    }
753
754    fn on_v2ip_details_changed(&self, device: DeviceUid, _details: mx_remote::DeviceV2ipDetails) {
755        forward!(self.on_v2ip_details_changed(device.into()));
756    }
757
758    fn on_v2ip_sink_changed(&self, device: DeviceUid, _sink: mx_remote::DeviceV2ipSink) {
759        forward!(self.on_v2ip_sink_changed(device.into()));
760    }
761
762    fn on_multiviewer_status_changed(
763        &self,
764        device: DeviceUid,
765        _status: mx_remote::MultiviewerStatus,
766    ) {
767        forward!(self.on_multiviewer_status_changed(device.into()));
768    }
769
770    fn on_audio_endpoints_changed(&self, device: DeviceUid, _endpoints: mx_remote::AudioEndpoints) {
771        forward!(self.on_audio_endpoints_changed(device.into()));
772    }
773
774    fn on_mesh_master_changed(&self, device: DeviceUid, master: DeviceUid) {
775        forward!(self.on_mesh_master_changed(device.into(), master.into()));
776    }
777
778    fn on_topology_changed(&self, device: DeviceUid, _topology: Vec<mx_remote::TopologyEntry>) {
779        forward!(self.on_topology_changed(device.into()));
780    }
781
782    fn on_amp_dolby_settings_changed(
783        &self,
784        device: DeviceUid,
785        _settings: mx_remote::AmpDolbySettings,
786    ) {
787        forward!(self.on_amp_dolby_settings_changed(device.into()));
788    }
789
790    fn on_setup_status_changed(&self, device: DeviceUid, completed: bool) {
791        forward!(self.on_setup_status_changed(device.into(), completed));
792    }
793
794    fn on_installer_id_changed(&self, device: DeviceUid, installer_id: u16) {
795        forward!(self.on_installer_id_changed(device.into(), installer_id));
796    }
797
798    fn on_tiling_changed(&self, device: DeviceUid, _tiling: mx_remote::V2ipTilingConfig) {
799        forward!(self.on_tiling_changed(device.into()));
800    }
801
802    fn on_rc_settings_changed(&self, device: DeviceUid, _settings: mx_remote::RcSettings) {
803        forward!(self.on_rc_settings_changed(device.into()));
804    }
805
806    fn on_v2ip_link_changed(&self, device: DeviceUid, target: DeviceUid) {
807        forward!(self.on_v2ip_link_changed(device.into(), target.into()));
808    }
809
810    fn on_multiviewer_command(&self, device: DeviceUid, command: MultiviewerCommand) {
811        let payload = mxr_multiviewer_command_t {
812            target: command.target.into(),
813            op: command.op,
814            params: command.params.as_ptr(),
815            params_len: command.params.len(),
816        };
817        forward!(self.on_multiviewer_command(device.into(), &payload));
818    }
819
820    fn on_audio_select_input(&self, device: DeviceUid, change: AudioChangeSource) {
821        let payload = mxr_audio_change_source_t {
822            source_uid: change.source_uid.into(),
823            source_id: change.source_id,
824            target_uid: change.target_uid.into(),
825            target_id: change.target_id,
826        };
827        forward!(self.on_audio_select_input(device.into(), &payload));
828    }
829
830    fn on_audio_endpoint_mute(&self, device: DeviceUid, endpoint: u16, muted: bool) {
831        forward!(self.on_audio_endpoint_mute(device.into(), endpoint, muted));
832    }
833
834    fn on_audio_endpoint_trigger(&self, device: DeviceUid, endpoint: u16, active: bool) {
835        forward!(self.on_audio_endpoint_trigger(device.into(), endpoint, active));
836    }
837
838    fn on_audio_endpoint_volume(&self, device: DeviceUid, endpoint: u16, volume: u32) {
839        forward!(self.on_audio_endpoint_volume(device.into(), endpoint, volume));
840    }
841
842    fn on_discover_request(&self, device: DeviceUid) {
843        forward!(self.on_discover_request(device.into()));
844    }
845
846    fn on_set_route_requested(&self, device: DeviceUid, request: SetRouteRequest) {
847        with_cstr(&request.serial, |serial| {
848            let payload = mxr_set_route_request_t {
849                serial,
850                sink_bay: request.sink_bay,
851                source_bay: request.source_bay,
852                no_power_on: request.no_power_on,
853                audio_only: request.audio_only,
854            };
855            forward!(self.on_set_route_requested(device.into(), &payload));
856        });
857    }
858
859    fn on_edid_requested(&self, device: DeviceUid, request: EdidRequest) {
860        let payload = mxr_edid_request_t {
861            target: request.target.into(),
862            output: request.output,
863        };
864        forward!(self.on_edid_requested(device.into(), &payload));
865    }
866
867    fn on_edid_received(&self, device: DeviceUid, edid: EdidRecord) {
868        let payload = mxr_edid_record_t {
869            output: edid.output,
870            data: edid.data.as_ptr(),
871            data_len: edid.data.len(),
872        };
873        forward!(self.on_edid_received(device.into(), &payload));
874    }
875
876    fn on_bay_name_change_requested(&self, device: DeviceUid, change: BayNameChange) {
877        with_cstr(&change.name, |name| {
878            let payload = mxr_bay_name_change_t {
879                target: change.target.into(),
880                port: change.port,
881                name,
882            };
883            forward!(self.on_bay_name_change_requested(device.into(), &payload));
884        });
885    }
886
887    fn on_edid_profile_change_requested(&self, device: DeviceUid, change: EdidProfileChange) {
888        let payload = mxr_edid_profile_change_t {
889            target: change.target.into(),
890            profile: change.profile.to_wire(),
891        };
892        forward!(self.on_edid_profile_change_requested(device.into(), &payload));
893    }
894
895    fn on_reboot_requested(&self, device: DeviceUid, request: RebootRequest) {
896        forward!(self.on_reboot_requested(device.into(), request.target.into()));
897    }
898
899    fn on_factory_reset_requested(&self, device: DeviceUid, request: FactoryResetRequest) {
900        let payload = mxr_factory_reset_request_t {
901            all: request.all,
902            target: uid_or_zero(request.target),
903        };
904        forward!(self.on_factory_reset_requested(device.into(), &payload));
905    }
906
907    fn on_monitoring_pulse(&self, device: DeviceUid) {
908        forward!(self.on_monitoring_pulse(device.into()));
909    }
910
911    fn on_upgrade_fpga_requested(&self, device: DeviceUid) {
912        forward!(self.on_upgrade_fpga_requested(device.into()));
913    }
914
915    fn on_detect_bays_requested(&self, device: DeviceUid) {
916        forward!(self.on_detect_bays_requested(device.into()));
917    }
918
919    fn on_power_save_requested(&self, device: DeviceUid, request: V2ipPowerSaveRequest) {
920        let payload = mxr_power_save_request_t {
921            target: uid_or_zero(request.target),
922            enabled: request.enabled,
923        };
924        forward!(self.on_power_save_requested(device.into(), &payload));
925    }
926
927    fn on_key_transmit_requested(&self, device: DeviceUid, request: KeyTransmitRequest) {
928        let payload = mxr_key_transmit_request_t {
929            target: request.target.into(),
930            local_bay: request.local_bay,
931            key: request.key.to_wire(),
932        };
933        forward!(self.on_key_transmit_requested(device.into(), &payload));
934    }
935
936    fn on_action_transmit_requested(&self, device: DeviceUid, request: ActionTransmitRequest) {
937        let payload = mxr_action_transmit_request_t {
938            target: request.target.into(),
939            local_bay: request.local_bay,
940            action: request.action.to_wire(),
941        };
942        forward!(self.on_action_transmit_requested(device.into(), &payload));
943    }
944
945    fn on_ir_transmit_requested(&self, device: DeviceUid, request: IrTransmitRequest) {
946        let payload = mxr_ir_transmit_request_t {
947            target: request.target.into(),
948            local_mode: request.local_mode,
949            local_bay: request.local_bay,
950            timestamp: request.timestamp,
951            meta: request.meta.into(),
952            timings: request.timings.as_ptr(),
953            timings_len: request.timings.len(),
954        };
955        forward!(self.on_ir_transmit_requested(device.into(), &payload));
956    }
957
958    fn on_blacklist_changed(&self, device: DeviceUid, change: V2ipBlacklistChange) {
959        let payload = mxr_blacklist_change_t {
960            target: change.target.into(),
961            registered: change.registered,
962        };
963        forward!(self.on_blacklist_changed(device.into(), &payload));
964    }
965
966    fn on_video_wall_command(&self, device: DeviceUid, command: VideoWallCommand) {
967        let payload = mxr_video_wall_command_t {
968            target: command.target.into(),
969            pos_x: command.pos_x,
970            pos_y: command.pos_y,
971            width: command.width,
972            height: command.height,
973            raster_w: command.raster_w,
974            raster_h: command.raster_h,
975            op: command.op.to_wire(),
976        };
977        forward!(self.on_video_wall_command(device.into(), &payload));
978    }
979
980    // ---- bay ----
981
982    fn on_bay_registered(&self, bay: BayUid) {
983        forward!(self.on_bay_registered(bay.into()));
984    }
985
986    fn on_video_source_changed(&self, bay: BayUid, source: Option<BayUid>) {
987        forward!(self.on_video_source_changed(bay.into(), bay_or_zero(source)));
988    }
989
990    fn on_audio_source_changed(&self, bay: BayUid, source: Option<BayUid>) {
991        forward!(self.on_audio_source_changed(bay.into(), bay_or_zero(source)));
992    }
993
994    fn on_volume_changed(&self, bay: BayUid, volume: VolumeMuteStatus) {
995        forward!(self.on_volume_changed(bay.into(), volume.volume(), volume.muted().into()));
996    }
997
998    fn on_power_changed(&self, bay: BayUid, power: PowerStatus) {
999        forward!(self.on_power_changed(bay.into(), Some(power).into()));
1000    }
1001
1002    fn on_name_changed(&self, bay: BayUid, name: String) {
1003        with_cstr(&name, |n| forward!(self.on_name_changed(bay.into(), n)));
1004    }
1005
1006    fn on_signal_detected_changed(&self, bay: BayUid, detected: bool) {
1007        forward!(self.on_signal_detected_changed(bay.into(), detected));
1008    }
1009
1010    fn on_faulty_changed(&self, bay: BayUid, faulty: bool) {
1011        forward!(self.on_faulty_changed(bay.into(), faulty));
1012    }
1013
1014    fn on_hidden_changed(&self, bay: BayUid, hidden: bool) {
1015        forward!(self.on_hidden_changed(bay.into(), hidden));
1016    }
1017
1018    fn on_poe_powered_changed(&self, bay: BayUid, powered: bool) {
1019        forward!(self.on_poe_powered_changed(bay.into(), powered));
1020    }
1021
1022    fn on_hdbt_connected_changed(&self, bay: BayUid, connected: bool) {
1023        forward!(self.on_hdbt_connected_changed(bay.into(), connected));
1024    }
1025
1026    fn on_signal_type_changed(&self, bay: BayUid, signal_type: String) {
1027        with_cstr(&signal_type, |s| {
1028            forward!(self.on_signal_type_changed(bay.into(), s))
1029        });
1030    }
1031
1032    fn on_hpd_detected_changed(&self, bay: BayUid, detected: bool) {
1033        forward!(self.on_hpd_detected_changed(bay.into(), detected));
1034    }
1035
1036    fn on_cec_detected_changed(&self, bay: BayUid, detected: bool) {
1037        forward!(self.on_cec_detected_changed(bay.into(), detected));
1038    }
1039
1040    fn on_arc_changed(&self, bay: BayUid, arc: ArcStatus) {
1041        forward!(self.on_arc_changed(bay.into(), arc.into()));
1042    }
1043
1044    fn on_edid_profile_changed(&self, bay: BayUid, profile: mx_remote::EdidProfile) {
1045        forward!(self.on_edid_profile_changed(bay.into(), profile.to_wire()));
1046    }
1047
1048    fn on_rc_type_changed(&self, bay: BayUid, rc_type: mx_remote::RcType) {
1049        forward!(self.on_rc_type_changed(bay.into(), rc_type.to_wire()));
1050    }
1051
1052    fn on_key_pressed(&self, bay: BayUid, key: RcKey) {
1053        forward!(self.on_key_pressed(bay.into(), key.to_wire()));
1054    }
1055
1056    fn on_action_received(&self, bay: BayUid, action: RcAction) {
1057        forward!(self.on_action_received(bay.into(), action.to_wire()));
1058    }
1059
1060    fn on_mirror_status_changed(&self, bay: BayUid, mirror: mx_remote::BayMirrorStatus) {
1061        forward!(self.on_mirror_status_changed(bay.into(), bay_or_zero(mirror.target)));
1062    }
1063
1064    fn on_amp_zone_settings_changed(&self, bay: BayUid, _settings: mx_remote::AmpZoneSettings) {
1065        forward!(self.on_amp_zone_settings_changed(bay.into()));
1066    }
1067
1068    fn on_volume_step(&self, bay: BayUid, up: bool) {
1069        forward!(self.on_volume_step(bay.into(), up));
1070    }
1071
1072    fn on_audio_clip(&self, bay: BayUid, clip: AudioClip) {
1073        forward!(self.on_audio_clip(bay.into(), clip.clip));
1074    }
1075
1076    fn on_ir_captured(&self, bay: BayUid, capture: IrCapture) {
1077        let payload = mxr_ir_capture_t {
1078            timestamp: capture.timestamp,
1079            last_change: capture.last_change,
1080            meta: capture.meta.into(),
1081            timings: capture.timings.as_ptr(),
1082            timings_len: capture.timings.len(),
1083        };
1084        forward!(self.on_ir_captured(bay.into(), &payload));
1085    }
1086
1087    fn on_filtered_devices_changed(&self, bay: BayUid, _filtered: Vec<DeviceUid>) {
1088        forward!(self.on_filtered_devices_changed(bay.into()));
1089    }
1090
1091    fn on_audio_endpoint_changed(&self, bay: BayUid, endpoint: u8) {
1092        forward!(self.on_audio_endpoint_changed(bay.into(), endpoint));
1093    }
1094
1095    fn on_encoder_disabled_changed(&self, bay: BayUid, disabled: bool) {
1096        forward!(self.on_encoder_disabled_changed(bay.into(), disabled));
1097    }
1098
1099    fn on_decoder_disabled_changed(&self, bay: BayUid, disabled: bool) {
1100        forward!(self.on_decoder_disabled_changed(bay.into(), disabled));
1101    }
1102
1103    // ---- both ----
1104
1105    fn on_bay_linked(
1106        &self,
1107        bay: BayUid,
1108        linked_serial: String,
1109        bay_name: String,
1110        features: LinkFeature,
1111    ) {
1112        with_cstr(&linked_serial, |serial| {
1113            with_cstr(&bay_name, |name| {
1114                forward!(self.on_bay_linked(bay.into(), serial, name, features.bits()));
1115            });
1116        });
1117    }
1118
1119    fn on_bay_unlinked(&self, bay: BayUid, linked_serial: String, bay_name: String) {
1120        with_cstr(&linked_serial, |serial| {
1121            with_cstr(&bay_name, |name| {
1122                forward!(self.on_bay_unlinked(bay.into(), serial, name));
1123            });
1124        });
1125    }
1126}