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    /// The device reported what its video processor supports; read it with
518    /// `mxr_v2ip_features()`.
519    pub on_v2ip_features_changed: mxr_device_cb,
520    /// A source bay's remote-control configuration changed; read it with
521    /// `mxr_rc_settings()`.
522    pub on_rc_settings_changed: mxr_device_cb,
523    /// A V2IP device was linked to a remote peer.
524    pub on_v2ip_link_changed: mxr_device_uid_cb,
525    /// A multiviewer command arrived.
526    pub on_multiviewer_command: mxr_multiviewer_command_cb,
527    /// An audio endpoint was switched to a new source.
528    pub on_audio_select_input: mxr_audio_select_cb,
529    /// An audio endpoint was muted or unmuted.
530    pub on_audio_endpoint_mute: mxr_endpoint_bool_cb,
531    /// An audio endpoint's trigger changed.
532    pub on_audio_endpoint_trigger: mxr_endpoint_bool_cb,
533    /// An audio endpoint's volume changed.
534    pub on_audio_endpoint_volume: mxr_endpoint_u32_cb,
535    /// A peer asked every device to announce itself.
536    pub on_discover_request: mxr_device_cb,
537    /// A peer asked a device to switch a sink.
538    pub on_set_route_requested: mxr_set_route_cb,
539    /// A peer asked a device for its EDID.
540    pub on_edid_requested: mxr_edid_request_cb,
541    /// A device answered with its EDID.
542    pub on_edid_received: mxr_edid_record_cb,
543    /// A peer asked a device to rename a bay.
544    pub on_bay_name_change_requested: mxr_bay_name_change_cb,
545    /// A peer asked a device to switch its EDID profile.
546    pub on_edid_profile_change_requested: mxr_edid_profile_change_cb,
547    /// A peer asked a device to reboot. The second identifier is the device
548    /// being asked, which is not always the sender.
549    pub on_reboot_requested: mxr_device_uid_cb,
550    /// A peer asked devices to factory-reset.
551    pub on_factory_reset_requested: mxr_factory_reset_cb,
552    /// A device sent its monitoring pulse.
553    pub on_monitoring_pulse: mxr_device_cb,
554    /// A peer asked a device to upgrade its FPGA.
555    pub on_upgrade_fpga_requested: mxr_device_cb,
556    /// A peer asked a device to re-detect its bays.
557    pub on_detect_bays_requested: mxr_device_cb,
558    /// A peer asked a sink to enter or leave power save.
559    pub on_power_save_requested: mxr_power_save_cb,
560    /// A peer asked a device to send a remote-control key.
561    pub on_key_transmit_requested: mxr_key_transmit_cb,
562    /// A peer asked a device to perform a remote-control action.
563    pub on_action_transmit_requested: mxr_action_transmit_cb,
564    /// A peer asked a device to blast raw infrared.
565    pub on_ir_transmit_requested: mxr_ir_transmit_cb,
566    /// A device was added to or removed from the source blacklist.
567    pub on_blacklist_changed: mxr_blacklist_cb,
568    /// A video wall command arrived.
569    pub on_video_wall_command: mxr_video_wall_cb,
570
571    /// A bay was seen for the first time.
572    pub on_bay_registered: mxr_bay_cb,
573    /// The bay's routed video source changed, zero when it was unrouted.
574    pub on_video_source_changed: mxr_bay_bay_cb,
575    /// The bay's routed audio source changed, zero when it was unrouted.
576    pub on_audio_source_changed: mxr_bay_bay_cb,
577    /// The bay's volume or mute state changed.
578    pub on_volume_changed: mxr_volume_cb,
579    /// The attached device's power state changed.
580    pub on_power_changed: mxr_power_cb,
581    /// The bay was renamed.
582    pub on_name_changed: mxr_bay_str_cb,
583    /// A signal appeared or disappeared.
584    pub on_signal_detected_changed: mxr_bay_bool_cb,
585    /// The bay started or stopped reporting a fault.
586    pub on_faulty_changed: mxr_bay_bool_cb,
587    /// The bay was hidden or shown.
588    pub on_hidden_changed: mxr_bay_bool_cb,
589    /// Power over Ethernet started or stopped supplying the bay.
590    pub on_poe_powered_changed: mxr_bay_bool_cb,
591    /// The HDBaseT link came up or went down.
592    pub on_hdbt_connected_changed: mxr_bay_bool_cb,
593    /// The signal format description changed.
594    pub on_signal_type_changed: mxr_bay_str_cb,
595    /// Hot-plug detect was asserted or released.
596    pub on_hpd_detected_changed: mxr_bay_bool_cb,
597    /// A CEC device answered or stopped answering.
598    pub on_cec_detected_changed: mxr_bay_bool_cb,
599    /// The audio return channel changed.
600    pub on_arc_changed: mxr_arc_cb,
601    /// The input's EDID profile changed.
602    pub on_edid_profile_changed: mxr_bay_u16_cb,
603    /// The input's remote-control type changed.
604    pub on_rc_type_changed: mxr_bay_u8_cb,
605    /// A remote-control key was pressed on the bay.
606    pub on_key_pressed: mxr_bay_u16_cb,
607    /// A remote-control action was received on the bay.
608    pub on_action_received: mxr_bay_u16_cb,
609    /// The bay started or stopped mirroring another output, zero when it
610    /// stopped.
611    pub on_mirror_status_changed: mxr_bay_bay_cb,
612    /// A ProAmp8 zone's settings changed; read them with
613    /// `mxr_bay_amp_settings()`.
614    pub on_amp_zone_settings_changed: mxr_bay_cb,
615    /// A volume step was requested on the bay.
616    pub on_volume_step: mxr_bay_bool_cb,
617    /// The bay detected audio clipping, at the reported level.
618    pub on_audio_clip: mxr_bay_u8_cb,
619    /// Raw infrared was captured on the bay.
620    pub on_ir_captured: mxr_ir_capture_cb,
621    /// The devices filtered out of this sink's picker changed; read them with
622    /// `mxr_bay_filtered()`.
623    pub on_filtered_devices_changed: mxr_bay_cb,
624    /// The audio endpoint the bay carries changed.
625    pub on_audio_endpoint_changed: mxr_bay_u8_cb,
626    /// The bay's V2IP encoder was enabled or disabled.
627    pub on_encoder_disabled_changed: mxr_bay_bool_cb,
628    /// The bay's V2IP decoder was enabled or disabled.
629    pub on_decoder_disabled_changed: mxr_bay_bool_cb,
630
631    /// The bay was linked to a bay on another device. Both ends are told, so
632    /// both fire: `bay_name` names the bay whose link record changed, which is
633    /// this bay on the device that reported the change and the far bay on its
634    /// peer.
635    pub on_bay_linked: mxr_bay_linked_cb,
636    /// The bay's link to another device was removed. The arguments describe
637    /// the link that went, and mean what they do on `on_bay_linked`.
638    pub on_bay_unlinked: mxr_bay_unlinked_cb,
639}
640
641/// The caller's cookie, which this library carries and never reads.
642///
643/// # Safety
644///
645/// The contract on `mxr_remote_new()` is what makes
646/// these impls sound: the caller keeps the pointer valid, and safe to use from
647/// the library's threads, until the client is freed. Nothing here dereferences
648/// it.
649struct UserData(*mut c_void);
650
651// SAFETY: an opaque pointer this library only ever copies. See the type's own
652// docs for the contract the caller holds up.
653unsafe impl Send for UserData {}
654// SAFETY: as above.
655unsafe impl Sync for UserData {}
656
657/// Turns library events into calls through a C table.
658pub(crate) struct Bridge {
659    cb: mxr_callbacks_t,
660    userdata: UserData,
661}
662
663impl Bridge {
664    /// Copies the caller's table, so a caller may free or reuse theirs.
665    pub(crate) fn new(table: &mxr_callbacks_t, userdata: *mut c_void) -> Self {
666        Self {
667            cb: *table,
668            userdata: UserData(userdata),
669        }
670    }
671
672    fn ud(&self) -> *mut c_void {
673        self.userdata.0
674    }
675}
676
677/// Calls one member of the table, if the caller set it.
678///
679/// The guard is here rather than at the caller because this is an exit point,
680/// not an entry one: a panic while marshalling would otherwise unwind through
681/// the receive thread and take the client down with it.
682macro_rules! forward {
683    ($self:ident.$field:ident( $($arg:expr),* $(,)? )) => {
684        if let Some(f) = $self.cb.$field {
685            guard((), || f($self.ud() $(, $arg)*));
686        }
687    };
688}
689
690/// Calls `body` with `text` as a C string that lives for the call.
691fn with_cstr<R>(text: &str, body: impl FnOnce(*const c_char) -> R) -> R {
692    // A NUL inside would cut the string short in C. Protocol strings are read
693    // up to their first NUL, so this is a fallback, not a case that happens.
694    let owned = CString::new(text).unwrap_or_else(|_| c"".to_owned());
695    body(owned.as_ptr())
696}
697
698/// The identifier a request names, where the protocol's zero stands for
699/// "unaddressed": a broadcast, or a request that addresses only its sender.
700fn uid_or_zero(uid: Option<DeviceUid>) -> mxr_uid_t {
701    uid.unwrap_or(DeviceUid::ZERO).into()
702}
703
704impl EventHandler for Bridge {
705    fn on_device_update(&self, device: DeviceUid) {
706        forward!(self.on_device_update(device.into()));
707    }
708
709    fn on_bay_update(&self, bay: BayUid) {
710        forward!(self.on_bay_update(bay.into()));
711    }
712
713    // ---- device ----
714
715    fn on_device_config_changed(&self, device: DeviceUid) {
716        forward!(self.on_device_config_changed(device.into()));
717    }
718
719    fn on_device_config_complete(&self, device: DeviceUid) {
720        forward!(self.on_device_config_complete(device.into()));
721    }
722
723    fn on_device_online_changed(&self, device: DeviceUid, online: bool) {
724        forward!(self.on_device_online_changed(device.into(), online));
725    }
726
727    fn on_device_temperature_changed(&self, device: DeviceUid, _temperatures: Vec<u8>) {
728        forward!(self.on_device_temperature_changed(device.into()));
729    }
730
731    fn on_firmware_version_changed(&self, device: DeviceUid, _version: mx_remote::FirmwareVersion) {
732        forward!(self.on_firmware_version_changed(device.into()));
733    }
734
735    fn on_system_status_changed(&self, device: DeviceUid, status: u16, message: String) {
736        with_cstr(&message, |m| {
737            forward!(self.on_system_status_changed(device.into(), status, m));
738        });
739    }
740
741    fn on_network_status_changed(&self, device: DeviceUid, _status: mx_remote::NetworkPortStatus) {
742        forward!(self.on_network_status_changed(device.into()));
743    }
744
745    fn on_v2ip_stats_changed(&self, device: DeviceUid, _stats: mx_remote::V2ipDeviceStats) {
746        forward!(self.on_v2ip_stats_changed(device.into()));
747    }
748
749    fn on_v2ip_sources_changed(
750        &self,
751        device: DeviceUid,
752        _sources: Vec<mx_remote::V2ipStreamSources>,
753    ) {
754        forward!(self.on_v2ip_sources_changed(device.into()));
755    }
756
757    fn on_v2ip_details_changed(&self, device: DeviceUid, _details: mx_remote::DeviceV2ipDetails) {
758        forward!(self.on_v2ip_details_changed(device.into()));
759    }
760
761    fn on_v2ip_sink_changed(&self, device: DeviceUid, _sink: mx_remote::DeviceV2ipSink) {
762        forward!(self.on_v2ip_sink_changed(device.into()));
763    }
764
765    fn on_multiviewer_status_changed(
766        &self,
767        device: DeviceUid,
768        _status: mx_remote::MultiviewerStatus,
769    ) {
770        forward!(self.on_multiviewer_status_changed(device.into()));
771    }
772
773    fn on_audio_endpoints_changed(&self, device: DeviceUid, _endpoints: mx_remote::AudioEndpoints) {
774        forward!(self.on_audio_endpoints_changed(device.into()));
775    }
776
777    fn on_mesh_master_changed(&self, device: DeviceUid, master: DeviceUid) {
778        forward!(self.on_mesh_master_changed(device.into(), master.into()));
779    }
780
781    fn on_topology_changed(&self, device: DeviceUid, _topology: Vec<mx_remote::TopologyEntry>) {
782        forward!(self.on_topology_changed(device.into()));
783    }
784
785    fn on_amp_dolby_settings_changed(
786        &self,
787        device: DeviceUid,
788        _settings: mx_remote::AmpDolbySettings,
789    ) {
790        forward!(self.on_amp_dolby_settings_changed(device.into()));
791    }
792
793    fn on_setup_status_changed(&self, device: DeviceUid, completed: bool) {
794        forward!(self.on_setup_status_changed(device.into(), completed));
795    }
796
797    fn on_installer_id_changed(&self, device: DeviceUid, installer_id: u16) {
798        forward!(self.on_installer_id_changed(device.into(), installer_id));
799    }
800
801    fn on_tiling_changed(&self, device: DeviceUid, _tiling: mx_remote::V2ipTilingConfig) {
802        forward!(self.on_tiling_changed(device.into()));
803    }
804
805    fn on_v2ip_features_changed(&self, device: DeviceUid, _features: mx_remote::V2ipFpgaFeature) {
806        forward!(self.on_v2ip_features_changed(device.into()));
807    }
808
809    fn on_rc_settings_changed(&self, device: DeviceUid, _settings: mx_remote::RcSettings) {
810        forward!(self.on_rc_settings_changed(device.into()));
811    }
812
813    fn on_v2ip_link_changed(&self, device: DeviceUid, target: DeviceUid) {
814        forward!(self.on_v2ip_link_changed(device.into(), target.into()));
815    }
816
817    fn on_multiviewer_command(&self, device: DeviceUid, command: MultiviewerCommand) {
818        let payload = mxr_multiviewer_command_t {
819            target: command.target.into(),
820            op: command.op,
821            params: command.params.as_ptr(),
822            params_len: command.params.len(),
823        };
824        forward!(self.on_multiviewer_command(device.into(), &payload));
825    }
826
827    fn on_audio_select_input(&self, device: DeviceUid, change: AudioChangeSource) {
828        let payload = mxr_audio_change_source_t {
829            source_uid: change.source_uid.into(),
830            source_id: change.source_id,
831            target_uid: change.target_uid.into(),
832            target_id: change.target_id,
833        };
834        forward!(self.on_audio_select_input(device.into(), &payload));
835    }
836
837    fn on_audio_endpoint_mute(&self, device: DeviceUid, endpoint: u16, muted: bool) {
838        forward!(self.on_audio_endpoint_mute(device.into(), endpoint, muted));
839    }
840
841    fn on_audio_endpoint_trigger(&self, device: DeviceUid, endpoint: u16, active: bool) {
842        forward!(self.on_audio_endpoint_trigger(device.into(), endpoint, active));
843    }
844
845    fn on_audio_endpoint_volume(&self, device: DeviceUid, endpoint: u16, volume: u32) {
846        forward!(self.on_audio_endpoint_volume(device.into(), endpoint, volume));
847    }
848
849    fn on_discover_request(&self, device: DeviceUid) {
850        forward!(self.on_discover_request(device.into()));
851    }
852
853    fn on_set_route_requested(&self, device: DeviceUid, request: SetRouteRequest) {
854        with_cstr(&request.serial, |serial| {
855            let payload = mxr_set_route_request_t {
856                serial,
857                sink_bay: request.sink_bay,
858                source_bay: request.source_bay,
859                no_power_on: request.no_power_on,
860                audio_only: request.audio_only,
861            };
862            forward!(self.on_set_route_requested(device.into(), &payload));
863        });
864    }
865
866    fn on_edid_requested(&self, device: DeviceUid, request: EdidRequest) {
867        let payload = mxr_edid_request_t {
868            target: request.target.into(),
869            output: request.output,
870        };
871        forward!(self.on_edid_requested(device.into(), &payload));
872    }
873
874    fn on_edid_received(&self, device: DeviceUid, edid: EdidRecord) {
875        let payload = mxr_edid_record_t {
876            output: edid.output,
877            data: edid.data.as_ptr(),
878            data_len: edid.data.len(),
879        };
880        forward!(self.on_edid_received(device.into(), &payload));
881    }
882
883    fn on_bay_name_change_requested(&self, device: DeviceUid, change: BayNameChange) {
884        with_cstr(&change.name, |name| {
885            let payload = mxr_bay_name_change_t {
886                target: change.target.into(),
887                port: change.port,
888                name,
889            };
890            forward!(self.on_bay_name_change_requested(device.into(), &payload));
891        });
892    }
893
894    fn on_edid_profile_change_requested(&self, device: DeviceUid, change: EdidProfileChange) {
895        let payload = mxr_edid_profile_change_t {
896            target: change.target.into(),
897            profile: change.profile.to_wire(),
898        };
899        forward!(self.on_edid_profile_change_requested(device.into(), &payload));
900    }
901
902    fn on_reboot_requested(&self, device: DeviceUid, request: RebootRequest) {
903        forward!(self.on_reboot_requested(device.into(), request.target.into()));
904    }
905
906    fn on_factory_reset_requested(&self, device: DeviceUid, request: FactoryResetRequest) {
907        let payload = mxr_factory_reset_request_t {
908            all: request.all,
909            target: uid_or_zero(request.target),
910        };
911        forward!(self.on_factory_reset_requested(device.into(), &payload));
912    }
913
914    fn on_monitoring_pulse(&self, device: DeviceUid) {
915        forward!(self.on_monitoring_pulse(device.into()));
916    }
917
918    fn on_upgrade_fpga_requested(&self, device: DeviceUid) {
919        forward!(self.on_upgrade_fpga_requested(device.into()));
920    }
921
922    fn on_detect_bays_requested(&self, device: DeviceUid) {
923        forward!(self.on_detect_bays_requested(device.into()));
924    }
925
926    fn on_power_save_requested(&self, device: DeviceUid, request: V2ipPowerSaveRequest) {
927        let payload = mxr_power_save_request_t {
928            target: uid_or_zero(request.target),
929            enabled: request.enabled,
930        };
931        forward!(self.on_power_save_requested(device.into(), &payload));
932    }
933
934    fn on_key_transmit_requested(&self, device: DeviceUid, request: KeyTransmitRequest) {
935        let payload = mxr_key_transmit_request_t {
936            target: request.target.into(),
937            local_bay: request.local_bay,
938            key: request.key.to_wire(),
939        };
940        forward!(self.on_key_transmit_requested(device.into(), &payload));
941    }
942
943    fn on_action_transmit_requested(&self, device: DeviceUid, request: ActionTransmitRequest) {
944        let payload = mxr_action_transmit_request_t {
945            target: request.target.into(),
946            local_bay: request.local_bay,
947            action: request.action.to_wire(),
948        };
949        forward!(self.on_action_transmit_requested(device.into(), &payload));
950    }
951
952    fn on_ir_transmit_requested(&self, device: DeviceUid, request: IrTransmitRequest) {
953        let payload = mxr_ir_transmit_request_t {
954            target: request.target.into(),
955            local_mode: request.local_mode,
956            local_bay: request.local_bay,
957            timestamp: request.timestamp,
958            meta: request.meta.into(),
959            timings: request.timings.as_ptr(),
960            timings_len: request.timings.len(),
961        };
962        forward!(self.on_ir_transmit_requested(device.into(), &payload));
963    }
964
965    fn on_blacklist_changed(&self, device: DeviceUid, change: V2ipBlacklistChange) {
966        let payload = mxr_blacklist_change_t {
967            target: change.target.into(),
968            registered: change.registered,
969        };
970        forward!(self.on_blacklist_changed(device.into(), &payload));
971    }
972
973    fn on_video_wall_command(&self, device: DeviceUid, command: VideoWallCommand) {
974        let payload = mxr_video_wall_command_t {
975            target: command.target.into(),
976            pos_x: command.pos_x,
977            pos_y: command.pos_y,
978            width: command.width,
979            height: command.height,
980            raster_w: command.raster_w,
981            raster_h: command.raster_h,
982            op: command.op.to_wire(),
983        };
984        forward!(self.on_video_wall_command(device.into(), &payload));
985    }
986
987    // ---- bay ----
988
989    fn on_bay_registered(&self, bay: BayUid) {
990        forward!(self.on_bay_registered(bay.into()));
991    }
992
993    fn on_video_source_changed(&self, bay: BayUid, source: Option<BayUid>) {
994        forward!(self.on_video_source_changed(bay.into(), bay_or_zero(source)));
995    }
996
997    fn on_audio_source_changed(&self, bay: BayUid, source: Option<BayUid>) {
998        forward!(self.on_audio_source_changed(bay.into(), bay_or_zero(source)));
999    }
1000
1001    fn on_volume_changed(&self, bay: BayUid, volume: VolumeMuteStatus) {
1002        forward!(self.on_volume_changed(bay.into(), volume.volume(), volume.muted().into()));
1003    }
1004
1005    fn on_power_changed(&self, bay: BayUid, power: PowerStatus) {
1006        forward!(self.on_power_changed(bay.into(), Some(power).into()));
1007    }
1008
1009    fn on_name_changed(&self, bay: BayUid, name: String) {
1010        with_cstr(&name, |n| forward!(self.on_name_changed(bay.into(), n)));
1011    }
1012
1013    fn on_signal_detected_changed(&self, bay: BayUid, detected: bool) {
1014        forward!(self.on_signal_detected_changed(bay.into(), detected));
1015    }
1016
1017    fn on_faulty_changed(&self, bay: BayUid, faulty: bool) {
1018        forward!(self.on_faulty_changed(bay.into(), faulty));
1019    }
1020
1021    fn on_hidden_changed(&self, bay: BayUid, hidden: bool) {
1022        forward!(self.on_hidden_changed(bay.into(), hidden));
1023    }
1024
1025    fn on_poe_powered_changed(&self, bay: BayUid, powered: bool) {
1026        forward!(self.on_poe_powered_changed(bay.into(), powered));
1027    }
1028
1029    fn on_hdbt_connected_changed(&self, bay: BayUid, connected: bool) {
1030        forward!(self.on_hdbt_connected_changed(bay.into(), connected));
1031    }
1032
1033    fn on_signal_type_changed(&self, bay: BayUid, signal_type: String) {
1034        with_cstr(&signal_type, |s| {
1035            forward!(self.on_signal_type_changed(bay.into(), s))
1036        });
1037    }
1038
1039    fn on_hpd_detected_changed(&self, bay: BayUid, detected: bool) {
1040        forward!(self.on_hpd_detected_changed(bay.into(), detected));
1041    }
1042
1043    fn on_cec_detected_changed(&self, bay: BayUid, detected: bool) {
1044        forward!(self.on_cec_detected_changed(bay.into(), detected));
1045    }
1046
1047    fn on_arc_changed(&self, bay: BayUid, arc: ArcStatus) {
1048        forward!(self.on_arc_changed(bay.into(), arc.into()));
1049    }
1050
1051    fn on_edid_profile_changed(&self, bay: BayUid, profile: mx_remote::EdidProfile) {
1052        forward!(self.on_edid_profile_changed(bay.into(), profile.to_wire()));
1053    }
1054
1055    fn on_rc_type_changed(&self, bay: BayUid, rc_type: mx_remote::RcType) {
1056        forward!(self.on_rc_type_changed(bay.into(), rc_type.to_wire()));
1057    }
1058
1059    fn on_key_pressed(&self, bay: BayUid, key: RcKey) {
1060        forward!(self.on_key_pressed(bay.into(), key.to_wire()));
1061    }
1062
1063    fn on_action_received(&self, bay: BayUid, action: RcAction) {
1064        forward!(self.on_action_received(bay.into(), action.to_wire()));
1065    }
1066
1067    fn on_mirror_status_changed(&self, bay: BayUid, mirror: mx_remote::BayMirrorStatus) {
1068        forward!(self.on_mirror_status_changed(bay.into(), bay_or_zero(mirror.target)));
1069    }
1070
1071    fn on_amp_zone_settings_changed(&self, bay: BayUid, _settings: mx_remote::AmpZoneSettings) {
1072        forward!(self.on_amp_zone_settings_changed(bay.into()));
1073    }
1074
1075    fn on_volume_step(&self, bay: BayUid, up: bool) {
1076        forward!(self.on_volume_step(bay.into(), up));
1077    }
1078
1079    fn on_audio_clip(&self, bay: BayUid, clip: AudioClip) {
1080        forward!(self.on_audio_clip(bay.into(), clip.clip));
1081    }
1082
1083    fn on_ir_captured(&self, bay: BayUid, capture: IrCapture) {
1084        let payload = mxr_ir_capture_t {
1085            timestamp: capture.timestamp,
1086            last_change: capture.last_change,
1087            meta: capture.meta.into(),
1088            timings: capture.timings.as_ptr(),
1089            timings_len: capture.timings.len(),
1090        };
1091        forward!(self.on_ir_captured(bay.into(), &payload));
1092    }
1093
1094    fn on_filtered_devices_changed(&self, bay: BayUid, _filtered: Vec<DeviceUid>) {
1095        forward!(self.on_filtered_devices_changed(bay.into()));
1096    }
1097
1098    fn on_audio_endpoint_changed(&self, bay: BayUid, endpoint: u8) {
1099        forward!(self.on_audio_endpoint_changed(bay.into(), endpoint));
1100    }
1101
1102    fn on_encoder_disabled_changed(&self, bay: BayUid, disabled: bool) {
1103        forward!(self.on_encoder_disabled_changed(bay.into(), disabled));
1104    }
1105
1106    fn on_decoder_disabled_changed(&self, bay: BayUid, disabled: bool) {
1107        forward!(self.on_decoder_disabled_changed(bay.into(), disabled));
1108    }
1109
1110    // ---- both ----
1111
1112    fn on_bay_linked(
1113        &self,
1114        bay: BayUid,
1115        linked_serial: String,
1116        bay_name: String,
1117        features: LinkFeature,
1118    ) {
1119        with_cstr(&linked_serial, |serial| {
1120            with_cstr(&bay_name, |name| {
1121                forward!(self.on_bay_linked(bay.into(), serial, name, features.bits()));
1122            });
1123        });
1124    }
1125
1126    fn on_bay_unlinked(&self, bay: BayUid, linked_serial: String, bay_name: String) {
1127        with_cstr(&linked_serial, |serial| {
1128            with_cstr(&bay_name, |name| {
1129                forward!(self.on_bay_unlinked(bay.into(), serial, name));
1130            });
1131        });
1132    }
1133}