Skip to main content

cec_linux/
sys.rs

1//https://www.avsforum.com/attachments/hdmi-cec-v1-3a-specifications-pdf.2579760/
2
3use bitflags::bitflags;
4use nix::{ioctl_read, ioctl_readwrite, ioctl_write_ptr};
5use num_enum::{IntoPrimitive, TryFromPrimitive, TryFromPrimitiveError};
6
7//#define CEC_ADAP_G_CAPS         _IOWR('a',  0, struct cec_caps)
8ioctl_readwrite! {
9    /// Query device capabilities
10    /// Filled by the driver.
11    capabilities, b'a',  0, CecCaps
12}
13
14/// information about the CEC adapter
15
16#[derive(Debug)]
17#[repr(C)]
18pub struct CecCaps {
19    /// name of the CEC device driver
20    driver: OSDStr<32>,
21    /// name of the CEC device. @driver + @name must be unique
22    name: OSDStr<32>,
23    /// number of available logical addresses
24    available_log_addrs: u32,
25    /// capabilities of the CEC adapter
26    capabilities: Capabilities,
27    /// version of the CEC adapter framework
28    version: u32,
29}
30impl CecCaps {
31    /// name of the CEC device driver
32    #[inline]
33    pub fn driver(&self) -> &str {
34        self.driver.as_ref()
35    }
36    /// name of the CEC device
37    #[inline]
38    pub fn name(&self) -> &str {
39        self.name.as_ref()
40    }
41    /// number of available logical addresses
42    #[inline]
43    pub fn available_log_addrs(&self) -> u32 {
44        self.available_log_addrs
45    }
46    /// capabilities of the CEC adapter
47    #[inline]
48    pub fn capabilities(&self) -> Capabilities {
49        self.capabilities
50    }
51    /// version of the CEC adapter framework
52    #[inline]
53    pub fn version(&self) -> u32 {
54        self.version
55    }
56}
57impl Default for CecCaps {
58    fn default() -> Self {
59        Self {
60            driver: Default::default(),
61            name: Default::default(),
62            available_log_addrs: Default::default(),
63            capabilities: Capabilities::empty(),
64            version: Default::default(),
65        }
66    }
67}
68
69bitflags! {
70    /// capabilities of the CEC adapter
71    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72    pub struct Capabilities: u32 {
73        /// Userspace has to configure the physical address. Do so via [CecDevice::set_phys](super::CecDevice::set_phys)
74        const PHYS_ADDR = (1 << 0);
75        /// Userspace has to configure the logical addresses. Do so via [CecDevice::set_log](super::CecDevice::set_log)
76        const LOG_ADDRS = (1 << 1);
77        /// Userspace can transmit messages (and thus become [follower](CecModeFollower) as well)
78        const TRANSMIT = (1 << 2);
79        /// Passthrough all messages instead of processing them.
80        const PASSTHROUGH = (1 << 3);
81        /// Supports remote control
82        const RC = (1 << 4);
83        /// Hardware can monitor all messages, not just directed and broadcast.
84        /// Needed for [CecModeFollower::MonitorAll]
85        const MONITOR_ALL = (1 << 5);
86        /// Hardware can use CEC only if the HDMI Hotplug Detect pin is high. New in v4.13.
87        const NEEDS_HPD = (1 << 6);
88        /// Hardware can monitor CEC pin transitions. New in v4.14.
89        /// When in pin monitoring mode the application will receive CEC_EVENT_PIN_CEC_LOW and CEC_EVENT_PIN_CEC_HIGH events.
90        const MONITOR_PIN =	(1 << 7);
91        /// CEC_ADAP_G_CONNECTOR_INFO is available. New in v5.5.
92        const CONNECTOR_INFO = (1 << 8);
93        /// CEC_MSG_FL_REPLY_VENDOR_ID is available. New in v6.12.
94        const REPLY_VENDOR_ID =	(1 << 9);
95    }
96}
97//TODO add ioctrl https://www.kernel.org/doc/html/v6.12/userspace-api/media/cec/cec-ioc-adap-g-conn-info.html#cec-adap-g-connector-info
98
99// CEC_ADAP_S_LOG_ADDRS
100ioctl_readwrite! {
101    /// The ioctl CEC_ADAP_S_LOG_ADDRS is only available if CEC_CAP_LOG_ADDRS is set (the ENOTTY error code is returned otherwise). The ioctl CEC_ADAP_S_LOG_ADDRS can only be called by a file descriptor in initiator mode (see ioctls CEC_G_MODE and CEC_S_MODE), if not the EBUSY error code will be returned.
102    /// To clear existing logical addresses set num_log_addrs to 0. All other fields will be ignored in that case. The adapter will go to the unconfigured state.
103    /// If the physical address is valid (see ioctl CEC_ADAP_S_PHYS_ADDR), then this ioctl will block until all requested logical addresses have been claimed. If the file descriptor is in non-blocking mode then it will not wait for the logical addresses to be claimed, instead it just returns 0.
104    /// A CEC_EVENT_STATE_CHANGE event is sent when the logical addresses are claimed or cleared.
105    /// Attempting to call ioctl CEC_ADAP_S_LOG_ADDRS when logical address types are already defined will return with error EBUSY.
106    set_log, b'a',  4, CecLogAddrs
107}
108
109// CEC_ADAP_G_LOG_ADDRS
110ioctl_read! {
111    /// Query logical addresses
112    /// Filled by the driver.
113    get_log, b'a',  3, CecLogAddrs
114}
115
116/// CEC logical addresses structure used by [CecDevice::set_log](super::CecDevice::set_log) and [CecDevice::get_log](super::CecDevice::get_log)
117#[derive(Debug)]
118#[repr(C)]
119pub struct CecLogAddrs {
120    /// the claimed logical addresses. Set by the driver.
121    log_addr: [u8; Self::CEC_MAX_LOG_ADDRS],
122    /// current logical address mask. Set by the driver.
123    log_addr_mask: CecLogAddrMask,
124
125    /// the CEC version that the adapter should implement. Set by the caller.
126    /// Used to implement the [CecOpcode::CecVersion] and [CecOpcode::ReportFeatures] messages.
127    pub cec_version: Version,
128    /// how many logical addresses should be claimed. Set by the caller.
129    ///
130    /// Must be ≤ [CecCaps::available_log_addrs].
131    /// All arrays in this structure are only filled up to index available_log_addrs-1. The remaining array elements will be ignored.
132    ///
133    /// The driver will return the actual number of logical addresses it could claim, which may be less than what was requested.
134    ///
135    /// If this field is set to 0, then the CEC adapter shall clear all claimed logical addresses and all other fields will be ignored.
136    num_log_addrs: u8,
137    /// the vendor ID of the device. Set by the caller.
138    pub vendor_id: u32,
139    pub flags: CecLogAddrFlags,
140    /// the OSD name of the device. Set by the caller
141    /// Used for [CecOpcode::SetOsdName]
142    pub osd_name: OSDStr<15>,
143    /// the primary device type for each logical address. Set by the caller.
144    primary_device_type: [CecPrimDevType; Self::CEC_MAX_LOG_ADDRS],
145    /// the logical address types. Set by the caller.
146    log_addr_type: [CecLogAddrType; Self::CEC_MAX_LOG_ADDRS],
147
148    /// CEC 2.0: all device types represented by the logical address. Set by the caller. Used in [CecOpcode::ReportFeatures].
149    pub all_device_types: [u8; Self::CEC_MAX_LOG_ADDRS],
150    /// CEC 2.0: The logical address features. Set by the caller. Used in [CecOpcode::ReportFeatures].
151    pub features: [[u8; Self::CEC_MAX_LOG_ADDRS]; 12],
152}
153impl Default for CecLogAddrs {
154    fn default() -> Self {
155        unsafe { core::mem::MaybeUninit::zeroed().assume_init() }
156    }
157}
158impl CecLogAddrs {
159    /**
160     * The maximum number of logical addresses one device can be assigned to.
161     * The CEC 2.0 spec allows for only 2 logical addresses at the moment. The
162     * Analog Devices CEC hardware supports 3. So let's go wild and go for 4.
163     */
164    const CEC_MAX_LOG_ADDRS: usize = 4;
165
166    const CEC_LOG_ADDR_INVALID: u8 = 0xff;
167    pub fn addresses(&self) -> &[CecLogicalAddress] {
168        //If no logical address could be claimed, then it is set to CEC_LOG_ADDR_INVALID.
169        if self.log_addr[0] == Self::CEC_LOG_ADDR_INVALID {
170            return &[];
171        }
172        //If this adapter is Unregistered, then log_addr[0] is set to 0xf and all others to CEC_LOG_ADDR_INVALID.
173        let s = if self.log_addr[0] == 0xf {
174            1
175        } else {
176            self.num_log_addrs as usize
177        };
178        // u8 to repr(u8)
179        unsafe { core::mem::transmute(&self.log_addr[..s]) }
180    }
181    pub fn mask(&self) -> CecLogAddrMask {
182        self.log_addr_mask
183    }
184    /// Request certain address type on the CEC Bus.
185    ///
186    /// The claimed [CecLogicalAddress]es will also depend on the other devices on the bus.
187    ///
188    /// The length of the Type slices must be ≤ [CecCaps::available_log_addrs].
189    /// Note that the CEC 2.0 standard allows for a maximum of 2 logical addresses, although some hardware has support for more.
190    /// The driver will return the actual number of logical addresses it could claim, which may be less than what was requested.
191    ///
192    /// The provided values are also used by responses sent from the core (see [CecModeFollower::ExclusivePassthru]):
193    ///
194    /// |Param           | used as reply to                | Info                                      |
195    /// |----------------|---------------------------------|-------------------------------------------|
196    /// | `vendor_id`    | [CecOpcode::GiveDeviceVendorId] | Use VendorID::NONE to disable the feature |
197    /// | `cec_version`  | [CecOpcode::GetCecVersion]      |                                           |
198    /// | `osd_name`     | [CecOpcode::GiveOsdName]        |                                           |
199    ///
200    pub fn new(
201        vendor_id: u32,
202        cec_version: Version,
203        osd_name: OSDStr<15>,
204        primary_type: &[CecPrimDevType],
205        addr_type: &[CecLogAddrType],
206    ) -> CecLogAddrs {
207        assert!(primary_type.len() <= Self::CEC_MAX_LOG_ADDRS);
208        assert_eq!(primary_type.len(), addr_type.len());
209        
210        let mut log = CecLogAddrs {
211            num_log_addrs: primary_type.len() as u8,
212            cec_version,
213            vendor_id,
214            osd_name,
215            ..Default::default()
216        };
217        log.primary_device_type[..primary_type.len()].copy_from_slice(primary_type);
218        log.log_addr_type[..addr_type.len()].copy_from_slice(addr_type);
219        log
220    }
221}
222#[cfg(test)]
223mod test_cec_log_addrs {
224    use super::*;
225    #[test]
226    fn default_len_zero() {
227        assert_eq!(CecLogAddrs::default().num_log_addrs, 0);
228    }
229    #[test]
230    fn new() {
231        let a = CecLogAddrs::new(
232            VendorID::NONE,
233            Version::V1_4,
234            "test".to_string().try_into().unwrap(),
235            &[CecPrimDevType::PLAYBACK],
236            &[CecLogAddrType::PLAYBACK],
237        );
238        assert_eq!(a.num_log_addrs, 1);
239        assert_eq!(a.vendor_id, VendorID::NONE);
240        assert_eq!(a.cec_version, Version::V1_4);
241        assert_eq!(a.flags, CecLogAddrFlags::empty());
242        assert_eq!(a.log_addr_type[0], CecLogAddrType::PLAYBACK);
243        assert_eq!(a.primary_device_type[0], CecPrimDevType::PLAYBACK);
244    }
245    #[test]
246    fn default_fields() {
247        let a = CecLogAddrs::new(
248            VendorID::NONE,
249            Version::V1_4,
250            "test".to_string().try_into().unwrap(),
251            &[CecPrimDevType::PLAYBACK],
252            &[CecLogAddrType::PLAYBACK],
253        );
254        assert_eq!(a.all_device_types, [0; 4]);
255        assert_eq!(a.features, [[0; 4]; 12]);
256    }
257}
258
259bitflags! {
260    /// Flags for [CecLogAddrs]
261    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
262    pub struct CecLogAddrFlags : u32 {
263        /// By default if no logical address of the requested type can be claimed, then it will go back to the unconfigured state. If this flag is set, then it will fallback to the Unregistered logical address. Note that if the Unregistered logical address was explicitly requested, then this flag has no effect.
264        const ALLOW_UNREG_FALLBACK = (1 << 0);
265    }
266}
267/// CEC Version Operand for [CecOpcode::CecVersion]
268#[repr(u8)]
269#[non_exhaustive]
270#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Copy, Clone)]
271pub enum Version {
272    V1_3A = 4,
273    V1_4 = 5,
274    V2_0 = 6,
275}
276
277/// Primary Device Type Operand (prim_devtype)
278#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Copy, Clone)]
279#[repr(u8)]
280pub enum CecPrimDevType {
281    TV = 0,
282    RECORD = 1,
283    TUNER = 3,
284    PLAYBACK = 4,
285    AUDIOSYSTEM = 5,
286    SWITCH = 6,
287    PROCESSOR = 7,
288}
289/// The logical address types that the CEC device wants to claim
290#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Copy, Clone)]
291#[repr(u8)]
292pub enum CecLogAddrType {
293    TV = 0,
294    RECORD = 1,
295    TUNER = 2,
296    PLAYBACK = 3,
297    AUDIOSYSTEM = 4,
298    SPECIFIC = 5,
299    UNREGISTERED = 6,
300}
301/*// All Device Types Operand (all_device_types)
302const CEC_OP_ALL_DEVTYPE_TV: u8 = 0x80;
303const CEC_OP_ALL_DEVTYPE_RECORD: u8 = 0x40;
304const CEC_OP_ALL_DEVTYPE_TUNER: u8 = 0x20;
305const CEC_OP_ALL_DEVTYPE_PLAYBACK: u8 = 0x10;
306const CEC_OP_ALL_DEVTYPE_AUDIOSYSTEM: u8 = 0x08;
307const CEC_OP_ALL_DEVTYPE_SWITCH: u8 = 0x04;
308 */
309
310//#define CEC_ADAP_G_PHYS_ADDR    _IOR('a',  1, __u16)
311ioctl_read! {
312    /// Query physical addresses
313    /// Filled by the driver.
314    get_phys, b'a',  1, CecPhysicalAddress
315}
316
317/**
318 * CEC physical address
319 *
320 * It is a 16-bit number where each group of 4 bits represent a digit of the physical address a.b.c.d where the most significant 4 bits represent ‘a’. The CEC root device (usually the TV) has address 0.0.0.0. Every device that is hooked up to an input of the TV has address a.0.0.0 (where ‘a’ is ≥ 1), devices hooked up to those in turn have addresses a.b.0.0, etc. So a topology of up to 5 devices deep is supported. The physical address a device shall use is stored in the EDID of the sink.  
321 * For example, the EDID for each HDMI input of the TV will have a different physical address of the form a.0.0.0 that the sources will read out and use as their physical address.  
322 *
323 * phys_addr is either 0 (if this is the CEC root device)
324 * or a valid physical address obtained from the sink's EDID
325 * as read by this CEC device (if this is a source device)
326 * or a physical address obtained and modified from a sink
327 * EDID and used for a sink CEC device.
328 *
329 * If nothing is connected, then phys_addr is [CecPhysicalAddress::INVALID].
330 * See HDMI 1.4b, section 8.7 (Physical Address).
331 */
332#[repr(transparent)]
333#[derive(Clone, Copy, PartialEq, Eq)]
334pub struct CecPhysicalAddress(u16);
335impl CecPhysicalAddress {
336    pub const INVALID: CecPhysicalAddress = CecPhysicalAddress::from_num(0xffff);
337    pub const fn from_bytes(bytes: [u8; 2]) -> CecPhysicalAddress {
338        CecPhysicalAddress(u16::from_be_bytes(bytes))
339    }
340    pub const fn from_num(num: u16) -> CecPhysicalAddress {
341        CecPhysicalAddress(num)
342    }
343    pub const fn to_bytes(&self) -> [u8; 2] {
344        self.0.to_be_bytes()
345    }
346    pub const fn to_num(&self) -> u16 {
347        self.0
348    }
349}
350impl From<u16> for CecPhysicalAddress {
351    fn from(value: u16) -> Self {
352        CecPhysicalAddress::from_num(value)
353    }
354}
355impl From<[u8; 2]> for CecPhysicalAddress {
356    fn from(value: [u8; 2]) -> Self {
357        CecPhysicalAddress::from_bytes(value)
358    }
359}
360impl PartialEq<u16> for CecPhysicalAddress {
361    fn eq(&self, other: &u16) -> bool {
362        self.0 == *other
363    }
364}
365impl PartialEq<[u8; 2]> for CecPhysicalAddress {
366    fn eq(&self, other: &[u8; 2]) -> bool {
367        self.0 == CecPhysicalAddress::from_bytes(*other).0
368    }
369}
370impl PartialEq<&[u8]> for CecPhysicalAddress {
371    fn eq(&self, other: &&[u8]) -> bool {
372        let bytes = match (*other).try_into() {
373            Ok(b) => b,
374            Err(_) => return false,
375        };
376        self.0 == CecPhysicalAddress::from_bytes(bytes).0
377    }
378}
379impl std::fmt::Debug for CecPhysicalAddress {
380    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381        f.write_fmt(format_args!(
382            "{:x}.{:x}.{:x}.{:x}",
383            (self.0 & 0xf000) >> 12,
384            (self.0 & 0xf00) >> 8,
385            (self.0 & 0xf0) >> 4,
386            self.0 & 0xf
387        ))
388    }
389}
390#[test]
391fn phys() {
392    assert_eq!(
393        "3.3.0.0",
394        format!("{:?}", CecPhysicalAddress::from_num(0x3300))
395    );
396    assert_eq!(CecPhysicalAddress::from_num(0x3300), 0x3300);
397    assert_eq!(CecPhysicalAddress::from_bytes([0x33, 0]), 0x3300);
398    assert_eq!(CecPhysicalAddress::from_num(0x3300), &b"\x33\x00"[..]);
399    assert_eq!(CecPhysicalAddress::from_num(0x3300), [0x33, 0]);
400}
401
402//#define CEC_ADAP_S_PHYS_ADDR    _IOW('a',  2, __u16)
403ioctl_write_ptr! {
404    set_phys, b'a',  2, CecPhysicalAddress
405}
406
407//#define CEC_G_MODE              _IOR('a',  8, __u32)
408ioctl_read! {
409    /// Query mode
410    /// Filled by the driver.
411    get_mode, b'a',  8, u32
412}
413//#define CEC_S_MODE              _IOW('a',  9, __u32)
414ioctl_write_ptr! {
415    /// When a CEC message is received, then the CEC framework will decide how it will be processed.
416    /// If the message is a reply to an earlier transmitted message, then the reply is sent back to the filehandle that is waiting for it. In addition the CEC framework will process it.
417    /// If the message is not a reply, then the CEC framework will process it first.
418    /// If there is no follower, then the message is just discarded and a feature abort is sent back to the initiator if the framework couldn’t process it.
419    /// The framework expects the follower to make the right decisions.
420    /// See Core Message Processing for details.
421    /// If there is no initiator, then any CEC filehandle can use ioctl CEC_TRANSMIT.
422    /// If there is an exclusive initiator then only that initiator can call ioctls CEC_RECEIVE and CEC_TRANSMIT.
423    /// The follower can of course always call ioctl CEC_TRANSMIT.
424    set_mode, b'a',  9, u32
425}
426// ---  The message handling modes  ---
427/// Modes for initiator
428#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
429#[repr(u32)]
430pub enum CecModeInitiator {
431    /// Transmiting not possible (but others can)
432    None = 0,
433    /// **Default** Shared access
434    Send = 1,
435    /// Do not allow other senders
436    Exclusive = 2,
437}
438pub const CEC_MODE_INITIATOR_MSK: u32 = 0x0f;
439/// Modes for follower
440#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
441#[repr(u32)]
442pub enum CecModeFollower {
443    /// **Default**: Only retrieve replies to own (this handles) messages
444    RepliesOnly = 0x0 << 4,
445    /// Retrieve all messages for this device.  
446    /// __Not__ possible with [CecModeInitiator::None]. Needs [Capabilities::TRANSMIT].
447    All = 0x1 << 4,
448    /// Retrieve all messages and lock this device.  
449    /// __Not__ possible with [CecModeInitiator::None]. Needs [Capabilities::TRANSMIT].
450    Exclusive = 0x2 << 4,
451    /// Passthrough mode. The CEC framework will pass on most core messages without processing them and the follower will have to implement those messages.
452    /// There are some messages that the core will always process, regardless of the passthrough mode.  
453    /// __Not__ possible with [CecModeInitiator::None]. Needs [Capabilities::TRANSMIT].
454    ///
455    /// Core messgages:
456    ///  - [CecOpcode::GetCecVersion]
457    ///  - [CecOpcode::GiveDeviceVendorId]
458    ///  - [CecOpcode::Abort]
459    ///  - [CecOpcode::GivePhysicalAddr]
460    ///  - [CecOpcode::GiveOsdName]
461    ///  - [CecOpcode::GiveFeatures]
462    ///  - [CecOpcode::UserControlPressed]
463    ///  - [CecOpcode::UserControlReleased]
464    ///  - [CecOpcode::ReportPhysicalAddr]
465    ExclusivePassthru = 0x3 << 4,
466    /// Get all messages sent or received (directed or brodcasted) by this device.
467    /// Only possible with [CecModeInitiator::None]. Needs `CAP_NET_ADMIN`.
468    Monitor = 0xe << 4,
469    /// As above but for all messages on the bus.  
470    /// Additionally needs [Capabilities::MONITOR_ALL].
471    MonitorAll = 0xf << 4,
472}
473pub const CEC_MODE_FOLLOWER_MSK: u32 = 0xf0;
474// ---  Transmit/receive a CEC command  ---
475//#define CEC_TRANSMIT            _IOWR('a',  5, struct cec_msg)
476ioctl_readwrite! {
477    /// To send a CEC message the application has to fill in the struct :c:type:` cec_msg` and pass it to ioctl CEC_TRANSMIT. The ioctl CEC_TRANSMIT is only available if CEC_CAP_TRANSMIT is set. If there is no more room in the transmit queue, then it will return -1 and set errno to the EBUSY error code. The transmit queue has enough room for 18 messages (about 1 second worth of 2-byte messages). Note that the CEC kernel framework will also reply to core messages (see :ref:cec-core-processing), so it is not a good idea to fully fill up the transmit queue.
478    /// If the file descriptor is in non-blocking mode then the transmit will return 0 and the result of the transmit will be available via ioctl CEC_RECEIVE once the transmit has finished (including waiting for a reply, if requested).
479    /// The sequence field is filled in for every transmit and this can be checked against the received messages to find the corresponding transmit result.
480    transmit, b'a',  5, CecMsg
481}
482//#define CEC_RECEIVE             _IOWR('a',  6, struct cec_msg)
483ioctl_readwrite! {
484    /// To receive a CEC message the application has to fill in the timeout field of struct cec_msg and pass it to ioctl CEC_RECEIVE. If the file descriptor is in non-blocking mode and there are no received messages pending, then it will return -1 and set errno to the EAGAIN error code. If the file descriptor is in blocking mode and timeout is non-zero and no message arrived within timeout milliseconds, then it will return -1 and set errno to the ETIMEDOUT error code.
485    /// A received message can be:
486    /// - a message received from another CEC device (the sequence field will be 0).
487    /// - the result of an earlier non-blocking transmit (the sequence field will be non-zero).
488    receive, b'a',  6, CecMsg
489}
490
491const CEC_MAX_MSG_SIZE: usize = 16;
492
493/// CEC message returned from [CecDevice::rec](super::CecDevice::rec) and  [CecDevice::rec_for](super::CecDevice::rec_for)
494#[derive(Debug)]
495#[repr(C)]
496pub struct CecMsg {
497    /// Timestamp in nanoseconds using CLOCK_MONOTONIC. Set by the driver when the message transmission has finished.
498    tx_ts: u64,
499    /// Timestamp in nanoseconds using CLOCK_MONOTONIC. Set by the driver when the message was received.
500    rx_ts: u64,
501    /// Length in bytes of the message.
502    pub(crate) len: u32,
503    /// The timeout (in ms) that is used to timeout CEC_RECEIVE.
504    /// Set to 0 if you want to wait forever. This timeout can also be
505    /// used with CEC_TRANSMIT as the timeout for waiting for a reply.
506    /// If 0, then it will use a 1 second timeout instead of waiting
507    /// forever as is done with CEC_RECEIVE.
508    pub timeout: u32,
509    /// The framework assigns a sequence number to messages that are sent. This can be used to track replies to previously sent messages.
510    pub sequence: u32,
511    /// No flags are defined yet, so set this to 0.
512    flags: u32,
513    /// The message payload.  
514    /// Includes initiator, destination and opcode.
515    pub(crate) msg: [u8; CEC_MAX_MSG_SIZE],
516    /// This field is ignored with CEC_RECEIVE and is only used by CEC_TRANSMIT.
517    /// If non-zero, then wait for a reply with this opcode.
518    /// Set to CEC_MSG_FEATURE_ABORT if you want to wait for a possible ABORT reply.
519    ///
520    /// If there was an error when sending the
521    /// msg or FeatureAbort was returned, then reply is set to 0.
522    ///
523    /// If reply is non-zero upon return, then len/msg are set to
524    /// the received message.
525    /// If reply is zero upon return and status has the
526    /// CEC_TX_STATUS_FEATURE_ABORT bit set, then len/msg are set to
527    /// the received feature abort message.
528    /// If reply is zero upon return and status has the
529    /// CEC_TX_STATUS_MAX_RETRIES bit set, then no reply was seen at all.
530    /// If reply is non-zero for CEC_TRANSMIT and the message is a
531    /// broadcast, then -EINVAL is returned.
532    /// if reply is non-zero, then timeout is set to 1000 (the required
533    /// maximum response time).
534    pub reply: CecOpcode,
535    /// The message receive status bits. Set by the driver.
536    pub rx_status: RxStatus,
537    /// The message transmit status bits. Set by the driver.
538    pub tx_status: TxStatus,
539    /// The number of 'Arbitration Lost' events. Set by the driver.
540    tx_arb_lost_cnt: u8,
541    /// The number of 'Not Acknowledged' events. Set by the driver.
542    tx_nack_cnt: u8,
543    /// The number of 'Low Drive Detected' events. Set by the driver.
544    tx_low_drive_cnt: u8,
545    /// The number of 'Error' events. Set by the driver.
546    tx_error_cnt: u8,
547}
548impl CecMsg {
549    /// return the initiator's logical address
550    pub fn initiator(&self) -> CecLogicalAddress {
551        (self.msg[0] >> 4).try_into().unwrap() // all values have a variant
552    }
553    /// return the destination's logical address
554    pub fn destination(&self) -> CecLogicalAddress {
555        (self.msg[0] & 0xf).try_into().unwrap() // all values have a variant
556    }
557    /// return the opcode of the message, None for poll
558    pub fn opcode(&self) -> Option<Result<CecOpcode, TryFromPrimitiveError<CecOpcode>>> {
559        if self.len > 1 {
560            Some(self.msg[1].try_into())
561        } else {
562            None
563        }
564    }
565    pub fn parameters(&self) -> &[u8] {
566        if self.len > 2 {
567            &self.msg[2..self.len as usize]
568        } else {
569            &[]
570        }
571    }
572    /// return true if this is a broadcast message
573    pub fn is_broadcast(&self) -> bool {
574        (self.msg[0] & 0xf) == 0xf
575    }
576    pub fn is_ok(&self) -> bool {
577        //(msg->tx_status && !(msg->tx_status & CEC_TX_STATUS_OK))
578        if !self.tx_status.is_empty() && !self.tx_status.contains(TxStatus::OK) {
579            return false;
580        }
581        //(msg->rx_status && !(msg->rx_status & CEC_RX_STATUS_OK))
582        if !self.rx_status.is_empty() && !self.rx_status.contains(RxStatus::OK) {
583            return false;
584        }
585        //(!msg->tx_status && !msg->rx_status)
586        if self.rx_status.is_empty() && self.tx_status.is_empty() {
587            return false;
588        }
589        // !(msg->rx_status & CEC_RX_STATUS_FEATURE_ABORT)
590        !self.rx_status.contains(RxStatus::FEATURE_ABORT)
591    }
592    pub fn init(from: CecLogicalAddress, to: CecLogicalAddress) -> CecMsg {
593        let mut m = Self {
594            tx_ts: 0,
595            rx_ts: 0,
596            len: 1,
597            timeout: 0,
598            sequence: 0,
599            flags: 0,
600            msg: [0; 16],
601            reply: CecOpcode::FeatureAbort,
602            rx_status: RxStatus::empty(),
603            tx_status: TxStatus::empty(),
604            tx_arb_lost_cnt: 0,
605            tx_nack_cnt: 0,
606            tx_low_drive_cnt: 0,
607            tx_error_cnt: 0,
608        };
609        let f: u8 = from.into();
610        let t: u8 = to.into();
611        m.msg[0] = f << 4 | t;
612        m
613    }
614}
615
616/*
617 * cec_msg_set_reply_to - fill in destination/initiator in a reply message.
618 * @msg:        the message structure for the reply
619 * @orig:       the original message structure
620 *
621 * Set the msg destination to the orig initiator and the msg initiator to the
622 * orig destination. Note that msg and orig may be the same pointer, in which
623 * case the change is done in place.
624static inline void cec_msg_set_reply_to(struct cec_msg *msg,
625                                        struct cec_msg *orig)
626{
627        /* The destination becomes the initiator and vice versa */
628        msg->msg[0] = (cec_msg_destination(orig) << 4) |
629                      cec_msg_initiator(orig);
630        msg->reply = msg->timeout = 0;
631}
632 */
633// ---  cec status field  ---
634bitflags! {
635    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
636    pub struct TxStatus: u8 {
637        const OK          = (1 << 0);
638        /// CEC line arbitration was lost.
639        const ARB_LOST    = (1 << 1);
640        /// Message was not acknowledged.
641        const NACK        = (1 << 2);
642        /// Low drive was detected on the CEC bus. This indicates that a follower detected an error on the bus and requests a retransmission.
643        const LOW_DRIVE   = (1 << 3);
644        const ERROR       = (1 << 4);
645        /// The transmit failed after one or more retries. This status bit is mutually exclusive with [TxStatus::OK].
646        /// Other bits can still be set to explain which failures were seen.
647        const MAX_RETRIES = (1 << 5);
648    }
649}
650bitflags! {
651    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
652    pub struct RxStatus: u8 {
653        const OK            = (1 << 0);
654        /// The reply to an earlier transmitted message timed out.
655        const TIMEOUT       = (1 << 1);
656        /// This status is only set if this message was the reply to an earlier transmitted message
657        /// that received [CecOpcode::FeatureAbort]
658        const FEATURE_ABORT = (1 << 2);
659    }
660}
661#[derive(Debug)]
662pub struct CecTxError {
663    status: TxStatus,
664    tx_arb_lost_cnt: u8,
665    tx_nack_cnt: u8,
666    tx_low_drive_cnt: u8,
667    tx_error_cnt: u8,
668}
669impl From<CecMsg> for CecTxError {
670    fn from(msg: CecMsg) -> Self {
671        Self {
672            status: msg.tx_status,
673            tx_arb_lost_cnt: msg.tx_arb_lost_cnt,
674            tx_nack_cnt: msg.tx_nack_cnt,
675            tx_low_drive_cnt: msg.tx_low_drive_cnt,
676            tx_error_cnt: msg.tx_error_cnt,
677        }
678    }
679}
680impl std::error::Error for CecTxError {}
681impl std::fmt::Display for CecTxError {
682    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
683        if self.status.contains(TxStatus::ARB_LOST) {
684            f.write_fmt(format_args!("ArbLost: {} ", self.tx_arb_lost_cnt))?;
685        }
686        if self.status.contains(TxStatus::NACK) {
687            f.write_fmt(format_args!("NAck: {} ", self.tx_nack_cnt))?;
688        }
689        if self.status.contains(TxStatus::LOW_DRIVE) {
690            f.write_fmt(format_args!("LowDrive: {} ", self.tx_low_drive_cnt))?;
691        }
692        if self.status.contains(TxStatus::ERROR) {
693            f.write_fmt(format_args!("Errors: {} ", self.tx_error_cnt))?;
694        }
695        Ok(())
696    }
697}
698
699/**
700 * The logical addresses defined by CEC 2.0
701 *
702 * Switches should use UNREGISTERED.
703 * Processors should use SPECIFIC.
704 */
705#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
706#[repr(u8)]
707pub enum CecLogicalAddress {
708    Tv = 0,
709    Record1 = 1,
710    Record2 = 2,
711    Tuner1 = 3,
712    Playback1 = 4,
713    Audiosystem = 5,
714    Tuner2 = 6,
715    Tuner3 = 7,
716    Playback2 = 8,
717    Record3 = 9,
718    Tuner4 = 10,
719    Playback3 = 11,
720    Backup1 = 12,
721    Backup2 = 13,
722    Specific = 14,
723    ///as initiator address
724    UnregisteredBroadcast = 15,
725}
726
727bitflags! {
728    /// The bitmask of all logical addresses this adapter has claimed.
729    ///
730    /// If this adapter is not configured at all, then log_addr_mask is set to 0.
731    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
732    pub struct CecLogAddrMask: u16 {
733        const Tv            = (1 << 0);
734        const Record1       = (1 << 1);
735        const Record2       = (1 << 2);
736        const Record3       = (1 << 9);
737        const Tuner1        = (1 << 3);
738        const Tuner2        = (1 << 6);
739        const Tuner3        = (1 << 7);
740        const Tuner4        = (1 << 10);
741        const Playback1     = (1 << 4);
742        const Playback2     = (1 << 8);
743        const Playback3     = (1 << 11);
744        const Audiosystem   = (1 << 5);
745        const Backup1       = (1 << 12);
746        const Backup2       = (1 << 13);
747        const Specific      = (1 << 14);
748        /// adapter is Unregistered
749        const Unregistered  = (1 << 15);
750    }
751}
752impl CecLogAddrMask {
753    #[inline]
754    pub fn is_playback(&self) -> bool {
755        self.intersects(Self::Playback1 | Self::Playback2 | Self::Playback3)
756    }
757    #[inline]
758    pub fn is_record(&self) -> bool {
759        self.intersects(Self::Record1 | Self::Record2 | Self::Record3)
760    }
761    #[inline]
762    pub fn is_tuner(&self) -> bool {
763        self.intersects(Self::Tuner1 | Self::Tuner2 | Self::Tuner3 | Self::Tuner4)
764    }
765    #[inline]
766    pub fn is_backup(&self) -> bool {
767        self.intersects(Self::Backup1 | Self::Backup2)
768    }
769}
770
771// ---  Events  ---
772#[repr(u32)]
773#[allow(dead_code)] // this enum is used in ffi
774#[non_exhaustive]
775pub enum CecEventType {
776    /// Event that occurs when the adapter state changes
777    StateChange = 1,
778    /// This event is sent when messages are lost because the application
779    /// didn't empty the message queue in time
780    LostMsgs = 2,
781}
782bitflags! {
783    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
784    pub struct CecEventFlags : u32 {
785        const CEC_EVENT_FL_INITIAL_STATE = (1 << 0);
786    }
787}
788
789///[CecEvent](super::CecEvent) used when the CEC adapter changes state.
790#[derive(Debug, Clone, Copy)]
791#[repr(C)]
792pub struct CecEventStateChange {
793    ///the current physical address
794    pub phys_addr: CecPhysicalAddress,
795    /// The current set of claimed logical addresses.
796    /// This is 0 if no logical addresses are claimed or if `phys_addr`` is CEC_PHYS_ADDR_INVALID.
797    pub log_addr_mask: CecLogAddrMask,
798}
799
800///[CecEvent](super::CecEvent) that tells you how many messages were lost
801#[derive(Debug, Clone, Copy)]
802#[repr(C)]
803pub struct CecEventLostMsgs {
804    ///how many messages were lost.
805    pub lost_msgs: u32,
806}
807#[repr(C)]
808pub union CecEventPayload {
809    ///the event payload for CEC_EVENT_STATE_CHANGE.
810    pub state_change: CecEventStateChange,
811    ///the event payload for CEC_EVENT_LOST_MSGS.
812    pub lost_msgs: CecEventLostMsgs,
813    ///array to pad the union.
814    raw: [u32; 16],
815}
816#[repr(C)]
817pub struct CecEvent {
818    ///the timestamp of when the event was sent.
819    pub ts: u64,
820    pub typ: CecEventType,
821    pub flags: CecEventFlags,
822    pub payload: CecEventPayload,
823}
824impl Default for CecEvent {
825    fn default() -> Self {
826        Self {
827            ts: Default::default(),
828            typ: CecEventType::LostMsgs,
829            flags: CecEventFlags::empty(),
830            payload: CecEventPayload { raw: [0; 16] },
831        }
832    }
833}
834//#define CEC_DQEVENT             _IOWR('a',  7, struct cec_event)
835ioctl_readwrite! {
836    /**
837     * The internal event queues are per-filehandle and per-event type. If there is no more room in a queue then the last event is overwritten with the new one. This means that intermediate results can be thrown away but that the latest event is always available. This also means that is it possible to read two successive events that have the same value (e.g. two CEC_EVENT_STATE_CHANGE events with the same state). In that case the intermediate state changes were lost but it is guaranteed that the state did change in between the two events.
838     */
839    get_event, b'a',  7, CecEvent
840}
841
842/// The opcode of a [CecMsg]
843#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
844#[repr(u8)]
845pub enum CecOpcode {
846    /* One Touch Play Feature */
847    /// Used by a new source to indicate that it has started to transmit a stream OR used in response to a [CecOpcode::RequestActiveSource]  
848    /// __Parameters:__ [CecPhysicalAddress]
849    ActiveSource = 0x82,
850    /// Sent by a source device to the TV whenever it enters the active state (alternatively it may send [CecOpcode::TextViewOn]).
851    /// The TV should then turn on (if not on). If in ‘Text Display’ state then the TV enters ‘Image Display’ state.
852    ImageViewOn = 0x04,
853    /// As [CecOpcode::ImageViewOn], but should also remove any text, menus and PIP windows from the TV’s display.
854    TextViewOn = 0x0d,
855    /* Routing Control Feature */
856
857    /*
858     * Has also:
859     *      ACTIVE_SOURCE
860     */
861    /// Used by the currently active source to inform the TV that it has no video to be presented to the user, or is going into standby as the result of a local user command on the device.  
862    /// __Parameters:__ [CecPhysicalAddress] of active source
863    InactiveSource = 0x9d,
864    /// Used by a new device to discover the status of the system.
865    RequestActiveSource = 0x85,
866    /// Sent by a CEC Switch when it is manually switched to inform all other devices on the network that the active route below the switch has changed.  
867    /// __Parameters:__
868    /// - old [CecPhysicalAddress]
869    /// - new [CecPhysicalAddress]
870    RoutingChange = 0x80,
871    /// Sent by a CEC Switch to indicate the active route below the switch.  
872    /// __Parameters:__ [CecPhysicalAddress]
873    RoutingInformation = 0x81,
874    /// Used by the TV to request a streaming path from the specified physical address.  
875    /// __Parameters:__ [CecPhysicalAddress]
876    SetStreamPath = 0x86,
877
878    /* Standby Feature */
879    /// Turn off remote device. Can be used as a broadcast. No Payload
880    Standby = 0x36,
881
882    /* System Information Feature */
883    /// Used to indicate the supported CEC version, in response to a [CecOpcode::GetCecVersion]  
884    /// __Parameters:__ [Version]
885    CecVersion = 0x9e,
886    /// core message  
887    /// When in passthrough mode this message has to be handled by userspace, otherwise the core will return the CEC version that was set with [CecDevice::set_log](super::CecDevice::set_log).
888    GetCecVersion = 0x9f,
889    /// core message  
890    /// When in passthrough mode this message has to be handled by userspace, otherwise the core will report the current physical address.
891    GivePhysicalAddr = 0x83,
892    GetMenuLanguage = 0x91,
893    /// Used to inform all other devices of the mapping between physical and logical address of the initiator.  
894    /// __Parameters:__
895    /// - [CecPhysicalAddress]
896    /// - [CecLogicalAddress]
897    ReportPhysicalAddr = 0x84,
898    /// Used by a TV or another device to indicate the menu language.  
899    /// __Parameters:__ [Language]
900    SetMenuLanguage = 0x32,
901    /// HDMI 2.0
902    ReportFeatures = 0xa6,
903
904    /* Device Feature Operand (dev_features) */
905    /// HDMI 2.0  
906    /// core message
907    /// When in passthrough mode this message has to be handled by userspace, otherwise the core will report the current features as was set with [CecDevice::set_log](super::CecDevice::set_log) or the message is ignored if the CEC version was older than 2.0.
908    GiveFeatures = 0xa5,
909
910    /* Deck Control Feature */
911    /// Used to control a device’s media functions.  
912    /// __Parameters:__ [DeckControlMode]
913    DeckControl = 0x42,
914    /// Used to provide a deck’s status to the initiator of the [CecOpcode::GiveDeckStatus] message.  
915    /// __Parameters:__ [DeckInfo]
916    DeckStatus = 0x1b,
917    /// Used to request the status of a device, regardless of whether or not it is the current active source.  
918    /// __Parameters:__ [StatusRequest]
919    GiveDeckStatus = 0x1a,
920    /// Used to control the playback behaviour of a source device.  
921    /// __Parameters:__ [PlayMode]
922    Play = 0x41,
923
924    /* Vendor Specific Commands Feature */
925
926    /*
927     * Has also:
928     *      CEC_VERSION
929     *      GET_CEC_VERSION
930     */
931    /// Reports the vendor ID of this device.  
932    /// __Parameters:__ [VendorID]
933    DeviceVendorId = 0x87,
934    /// core message
935    /// When in passthrough mode this message has to be handled by userspace, otherwise the core will return the vendor ID that was set with [CecDevice::set_log](super::CecDevice::set_log).
936    GiveDeviceVendorId = 0x8c,
937    /// Allows vendor specific commands to be sent between two devices.  
938    /// __Parameters:__ vendor specific
939    VendorCommand = 0x89,
940    /// Allows vendor specific commands to be sent between two devices.  
941    /// __Parameters:__
942    /// - [VendorID]
943    /// - vendor specific
944    VendorCommandWithId = 0xa0,
945    /// Indicates that a remote control button has been depressed.
946    /// __Parameters:__ Vendor Specific RC Code
947    VendorRemoteButtonDown = 0x8a,
948    /// The last button pressed indicated by the [CecOpcode::VendorRemoteButtonDown] message has been released.
949    VendorRemoteButtonUp = 0x8b,
950
951    /* OSD Display Feature */
952    /// Used to send a text message to output on a TV.  
953    /// __Parameters:__
954    /// - [DisplayControl]
955    /// - [OSDStr<13>] String not terminated or prefixed by anything
956    SetOsdString = 0x64,
957    /* Device OSD Transfer Feature */
958    /// core message
959    /// When in passthrough mode this message has to be handled by userspace, otherwise the core will report the current OSD name as was set with [CecDevice::set_log](super::CecDevice::set_log).
960    /// No payload. Requests a [CecOpcode::SetOsdName]
961    GiveOsdName = 0x46,
962    /// answer to [CecOpcode::GiveOsdName].  
963    /// __Parameters:__
964    /// [OSDStr<14>] the name of the device (used in menus). not terminated or prefixed by anything
965    SetOsdName = 0x47,
966
967    /* Device Menu Control Feature */
968    /// A request from the TV for a device to show/remove a menu or to query if a device is currently showing a menu.  
969    /// __Parameters:__ [MenuRequestType]
970    MenuRequest = 0x8d,
971    /// Used to indicate to the TV that the device is showing/has removed a menu and requests the remote control keys to be passed though.  
972    /// __Parameters:__ 1 byte Activated(0)/Deactivated(1)
973    MenuStatus = 0x8e,
974    /* Menu State Operand (menu_state) */
975    /// Used to indicate that the user pressed a remote control button or switched from one remote control button to another.  
976    /// __Parameters:__ 1 byte [CecUserControlCode]
977    UserControlPressed = 0x44,
978    /// The last button pressed indicated by the [CecOpcode::UserControlPressed] message has been released.
979    UserControlReleased = 0x45,
980
981    /* Remote Control Passthrough Feature */
982
983    /*
984     * Has also:
985     *      USER_CONTROL_PRESSED
986     *      USER_CONTROL_RELEASED
987     */
988
989    /* Power Status Feature */
990    /// request [CecOpcode::ReportPowerStatus]
991    GiveDevicePowerStatus = 0x8f,
992    /// Answer to [CecOpcode::GiveDevicePowerStatus]
993    ///
994    /// __Parameters:__ 1 byte [CecPowerStatus]
995    ReportPowerStatus = 0x90,
996    /* General Protocol Messages */
997    /**
998     * It is used to allow devices to indicate if they do not
999     * support an opcode that has been directly sent to them, if it is unable to deal with the message at present, or if there
1000     * was something wrong with the transmitted frame at the high-level protocol layer.
1001     *
1002     * __Parameters:__
1003     * - [CecOpcode]
1004     * - [CecAbortReason]
1005     */
1006    FeatureAbort = 0x00,
1007    /// A device shall always respond with a [CecOpcode::FeatureAbort] message containing any valid value for [CecAbortReason].
1008    /// CEC switches shall not respond to this message.  
1009    /// When in [CecModeFollower::ExclusivePassthru] this message has to be handled by userspace, otherwise the core will return a feature refused message as per the specification.
1010    Abort = 0xff,
1011
1012    /* System Audio Control Feature */
1013
1014    /*
1015     * Has also:
1016     *      USER_CONTROL_PRESSED
1017     *      USER_CONTROL_RELEASED
1018     */
1019    /// Requests an amplifier to send its volume and mute status via [CecOpcode::ReportAudioStatus]
1020    GiveAudioStatus = 0x71,
1021    /// Requests the status of the [System Audio Mode](CecOpcode::SystemAudioModeStatus)
1022    GiveSystemAudioModeStatus = 0x7d,
1023    /**
1024     * Used to indicate the current audio volume status of a device.  
1025     * __Parameters:__ 1 byte
1026     *
1027     * Payload indicates audio playback volume, expressed as a percentage
1028     * (0% - 100%). N=0 is no sound; N=100 is maximum volume
1029     * sound level.
1030     * The linearity of the sound level is device dependent.
1031     * This value is mainly used for displaying a volume status bar on
1032     * a TV screen.
1033     *
1034     * The payload's highest bit (`&0x80`) indicates mute
1035     */
1036    ReportAudioStatus = 0x7a,
1037    ReportShortAudioDescriptor = 0xa3,
1038    RequestShortAudioDescriptor = 0xa4,
1039    /// Turns the System Audio Mode On or Off.  
1040    /// __Parameters:__ 1 byte On(1)/Off(0)
1041    /// If set to On, the TV mutes its speakers. The TV or STB sends relevant [CecOpcode::UserControlPressed] or [CecOpcode::UserControlReleased] as necessary.
1042    SetSystemAudioMode = 0x72,
1043
1044    /**
1045     * Requests to use [System Audio Mode](CecOpcode::SystemAudioModeStatus) to the amplifier
1046     *
1047     * __Parameters:__
1048     * [CecPhysicalAddress] of device to be used as source of the audio stream.
1049     * **OR**:  
1050     * no payload
1051     *
1052     *
1053     * The amplifier comes out of standby (if necessary) and switches to the relevant connector for device specified by Physical Address.
1054     * It then sends a [CecOpcode::SetSystemAudioMode] `On` message.
1055     *
1056     * ...  the device requesting this information can send the volume-related [CecOpcode::UserControlPressed] or [CecOpcode::UserControlReleased] messages.
1057     *
1058     * [CecOpcode::SystemAudioModeRequest] sent without a Physical Address parameter requests termination of the feature.
1059     * In this case, the amplifier sends a [CecOpcode::SetSystemAudioMode] `Off` message.
1060     */
1061    SystemAudioModeRequest = 0x70,
1062
1063    /**
1064     *  Reports the current status of the System Audio Mode
1065     *
1066     * __Parameters:__ 1 byte On(1)/Off(0)
1067     *
1068     * The feature can be initiated from a device (eg TV or STB) or the amplifier. In the case of initiation by a device
1069     * other than the amplifier, that device sends an [CecOpcode::SystemAudioModeRequest] to the amplifier, with the
1070     * physical address of the device that it wants to use as a source as an operand. Note that the Physical Address
1071     * may be the TV or STB itself.
1072     *
1073     */
1074    SystemAudioModeStatus = 0x7e,
1075    /* Audio Rate Control Feature */
1076    /// Used to control audio rate from Source Device.  
1077    /// __Parameters:__ [Audio Rate]
1078    SetAudioRate = 0x9a,
1079
1080    /* One Touch Record Feature */
1081    /// Requests a device to stop a recording.
1082    RecordOff = 0x0b,
1083    /// Attempt to record the specified source.  
1084    /// __Parameters:__ [RecordSource]
1085    RecordOn = 0x09,
1086    /// Used by a Recording Device to inform the initiator of the message [CecOpcode::RecordOn] about its status.  
1087    /// __Parameters:__ [RecordStatusInfo]
1088    RecordStatus = 0x0a,
1089    /// Request by the Recording Device to record the presently displayed source.
1090    RecordTvScreen = 0x0f,
1091
1092    /* Timer Programming Feature */
1093    /// Used to clear an Analogue timer block of a device.  
1094    /// __Parameters:__ See [CecOpcode::SetAnalogueTimer]
1095    ClearAnalogueTimer = 0x33,
1096    /// Used to clear an Digital timer block of a device.  
1097    /// __Parameters:__ See [CecOpcode::SetDigitalTimer]
1098    ClearDigitalTimer = 0x99,
1099    /// Used to clear an External timer block of a device.  
1100    /// __Parameters:__ See [CecOpcode::SetExtTimer]
1101    ClearExtTimer = 0xa1,
1102    /// Used to set a single timer block on an Analogue Recording Device.  
1103    /// __Parameters:__
1104    /// - [CecTimer]
1105    /// - [RecordingSequence]
1106    /// - [Analogue Broadcast Type]
1107    /// - [Analogue Frequency]
1108    /// - [Broadcast System]
1109    SetAnalogueTimer = 0x34,
1110    /// Used to set a single timer block on a Digital Recording Device.  
1111    /// __Parameters:__
1112    /// - [CecTimer]
1113    /// - [RecordingSequence]
1114    /// - [Digital Service Identification]
1115    SetDigitalTimer = 0x97,
1116    /// Used to set a single timer block to record from an external device.  
1117    /// __Parameters:__
1118    /// - [CecTimer]
1119    /// - [RecordingSequence]
1120    /// - [External Source Specifier]
1121    /// - [External Plug] | [External Physical Address]
1122    SetExtTimer = 0xa2,
1123    /// Used to set the name of a program associated with a timer block.
1124    /// Sent directly after sending a [CecOpcode::SetAnalogueTimer] or [CecOpcode::SetDigitalTimer] message.
1125    /// The name is then associated with that timer block.  
1126    /// __Parameters:__ [Program Title String]
1127    SetTimerProgramTitle = 0x67,
1128    /// Used to give the status of a [CecOpcode::ClearAnalogueTimer], [CecOpcode::ClearDigitalTimer] or [CecOpcode::ClearExtTimer] message.  
1129    /// __Parameters:__ [TimerClearedStatusData]
1130    TimerClearedStatus = 0x43,
1131    /// Used to send timer status to the initiator of a [CecOpcode::SetAnalogueTimer], [CecOpcode::SetDigitalTimer] or [CecOpcode::SetExtTimer] message.  
1132    /// __Parameters:__ [TimerStatusData]
1133    TimerStatus = 0x35,
1134
1135    /* Tuner Control Feature */
1136    /// Used to request the status of a tuner device.  
1137    /// __Parameters:__ [StatusRequest]
1138    GiveTunerDeviceStatus = 0x08,
1139    SelectAnalogueService = 0x92,
1140    SelectDigitalService = 0x93,
1141    TunerDeviceStatus = 0x07,
1142    TunerStepDecrement = 0x06,
1143    TunerStepIncrement = 0x05,
1144
1145    /* Audio Return Channel Control Feature */
1146    InitiateArc = 0xc0,
1147    ReportArcInitiated = 0xc1,
1148    ReportArcTerminated = 0xc2,
1149    RequestArcInitiation = 0xc3,
1150    RequestArcTermination = 0xc4,
1151    TerminateArc = 0xc5,
1152
1153    /* Dynamic Audio Lipsync Feature */
1154    /* Only for CEC 2.0 and up */
1155    RequestCurrentLatency = 0xa7,
1156    ReportCurrentLatency = 0xa8,
1157    /* Capability Discovery and Control Feature */
1158    CdcMessage = 0xf8,
1159}
1160/// parameter for [CecOpcode::UserControlPressed]
1161#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1162#[repr(u8)]
1163pub enum CecUserControlCode {
1164    Select = 0x00,
1165    Up = 0x01,
1166    Down = 0x02,
1167    Left = 0x03,
1168    Right = 0x04,
1169    RightUp = 0x05,
1170    RightDown = 0x06,
1171    LeftUp = 0x07,
1172    LeftDown = 0x08,
1173    RootMenu = 0x09,
1174    SetupMenu = 0x0a,
1175    ContentsMenu = 0x0b,
1176    FavoriteMenu = 0x0c,
1177    Exit = 0x0d,
1178    // reserved: 0x0E, 0x0F
1179    TopMenu = 0x10,
1180    DvdMenu = 0x11, // reserved: 0x12 ... 0x1C
1181    NumberEntryMode = 0x1d,
1182    Number11 = 0x1e,
1183    Number12 = 0x1f,
1184    Number0 = 0x20,
1185    Number1 = 0x21,
1186    Number2 = 0x22,
1187    Number3 = 0x23,
1188    Number4 = 0x24,
1189    Number5 = 0x25,
1190    Number6 = 0x26,
1191    Number7 = 0x27,
1192    Number8 = 0x28,
1193    Number9 = 0x29,
1194    Dot = 0x2a,
1195    Enter = 0x2b,
1196    Clear = 0x2c,
1197    NextFavorite = 0x2f,
1198    ChannelUp = 0x30,
1199    ChannelDown = 0x31,
1200    PreviousChannel = 0x32,
1201    SoundSelect = 0x33,
1202    InputSelect = 0x34,
1203    DisplayInformation = 0x35,
1204    Help = 0x36,
1205    PageUp = 0x37,
1206    PageDown = 0x38,
1207    // reserved: 0x39 ... 0x3F
1208    Power = 0x40,
1209    VolumeUp = 0x41,
1210    VolumeDown = 0x42,
1211    Mute = 0x43,
1212    Play = 0x44,
1213    Stop = 0x45,
1214    Pause = 0x46,
1215    Record = 0x47,
1216    Rewind = 0x48,
1217    FastForward = 0x49,
1218    Eject = 0x4a,
1219    Forward = 0x4b,
1220    Backward = 0x4c,
1221    StopRecord = 0x4d,
1222    PauseRecord = 0x4e,
1223    // reserved: 0x4F
1224    Angle = 0x50,
1225    SubPicture = 0x51,
1226    VideoOnDemand = 0x52,
1227    ElectronicProgramGuide = 0x53,
1228    TimerProgramming = 0x54,
1229    InitialConfiguration = 0x55,
1230    SelectBroadcastType = 0x56,
1231    SelectSoundPresentation = 0x57,
1232    // reserved: 0x58 ... 0x5F
1233    /// Additional Operands: [Play Mode]
1234    PlayFunction = 0x60,
1235    PausePlayFunction = 0x61,
1236    RecordFunction = 0x62,
1237    PauseRecordFunction = 0x63,
1238    StopFunction = 0x64,
1239    MuteFunction = 0x65,
1240    RestoreVolumeFunction = 0x66,
1241    /// Additional Operands: [Channel Identifier]
1242    TuneFunction = 0x67,
1243    /// Additional Operands: [UI Function Media]
1244    SelectMediaFunction = 0x68,
1245    /// Additional Operands: [UI Function Select A/V input]
1246    SelectAvInputFunction = 0x69,
1247    /// Additional Operands: [UI Function Select Audio input]
1248    SelectAudioInputFunction = 0x6a,
1249    PowerToggleFunction = 0x6b,
1250    PowerOffFunction = 0x6c,
1251    PowerOnFunction = 0x6d,
1252    // reserved: 0x6E ... 0x70
1253    F1Blue = 0x71,
1254    F2Red = 0x72,
1255    F3Green = 0x73,
1256    F4Yellow = 0x74,
1257    F5 = 0x75,
1258    Data = 0x76,
1259    // reserved: 0x77 ... 0xFF
1260}
1261/// used by [CecOpcode::FeatureAbort]
1262#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1263#[repr(u8)]
1264pub enum CecAbortReason {
1265    /// Unrecognized opcode
1266    Unrecognized = 0,
1267    /// Not in correct mode to respond
1268    WrongMode = 1,
1269    /// Cannot provide source
1270    NoSource = 2,
1271    /// Invalid operand
1272    InvalidOp = 3,
1273    Refused = 4,
1274    Other = 5,
1275}
1276/// used by [CecOpcode::DeckControl]
1277#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1278#[repr(u8)]
1279pub enum DeckControlMode {
1280    Skip = 1,
1281    Rewind = 2,
1282    Stop = 3,
1283    Eject = 4,
1284}
1285/// used by [CecOpcode::DeckStatus]
1286#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1287#[repr(u8)]
1288pub enum DeckInfo {
1289    Play = 0x11,
1290    Record = 0x12,
1291    PlayRev = 0x13,
1292    Still = 0x14,
1293    Slow = 0x15,
1294    SlowRev = 0x16,
1295    FastFwd = 0x17,
1296    FastRev = 0x18,
1297    NoMedia = 0x19,
1298    Stop = 0x1a,
1299    SkipFwd = 0x1b,
1300    SkipRev = 0x1c,
1301    IndexSearchFwd = 0x1d,
1302    IndexSearchRev = 0x1e,
1303    Other = 0x1f,
1304}
1305/// used by [CecOpcode::SetOsdString]
1306#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1307#[repr(u8)]
1308pub enum DisplayControl {
1309    Default = 0x00,
1310    UntilCleared = 0x40,
1311    Clear = 0x80,
1312}
1313/// used by [CecOpcode::MenuRequest]
1314#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1315#[repr(u8)]
1316pub enum MenuRequestType {
1317    Activate = 0x00,
1318    Deactivate = 0x01,
1319    Query = 0x02,
1320}
1321/// used by [CecOpcode::Play]
1322#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1323#[repr(u8)]
1324pub enum PlayMode {
1325    Fwd = 0x24,
1326    Rev = 0x20,
1327    Still = 0x25,
1328    FastFwdMin = 0x05,
1329    FastFwdMed = 0x06,
1330    FastFwdMax = 0x07,
1331    FastRevMin = 0x09,
1332    FastRevMed = 0x0a,
1333    FastRevMax = 0x0b,
1334    SlowFwdMin = 0x15,
1335    SlowFwdMed = 0x16,
1336    SlowFwdMax = 0x17,
1337    SlowRevMin = 0x19,
1338    SlowRevMed = 0x1a,
1339    SlowRevMax = 0x1b,
1340}
1341/// used by [CecOpcode::GiveDeckStatus] and [CecOpcode::GiveTunerDeviceStatus]
1342#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1343#[repr(u8)]
1344pub enum StatusRequest {
1345    On = 1,
1346    Off = 2,
1347    Once = 3,
1348}
1349/*
1350#[repr(transparent)]
1351pub struct Volume(u8);
1352impl Volume {
1353    pub fn vol(&self) -> Option<u8> {
1354        let v = self.0 & 0x7f;
1355        //0x65 ..= 0x7E Reserved
1356        if v == 0x7f {
1357            return None;
1358        }
1359        Some(v)
1360    }
1361    pub fn is_mute(&self) -> bool {
1362        self.0 & 0x80 == 0x80
1363    }
1364}
1365*/
1366
1367/// Payload of [CecOpcode::SetAnalogueTimer], [CecOpcode::SetDigitalTimer] or [CecOpcode::SetExtTimer]
1368#[repr(C)]
1369pub struct CecTimer {
1370    /// Day of Month: 1 byte 1..=31
1371    pub day: u8,
1372    /// Month of Year: 1 byte 1..=12
1373    pub month: u8,
1374    /// Start Hour: 1 byte 0..=23
1375    pub start_h: u8,
1376    /// Start Minute: 1 byte 0..=59
1377    pub start_min: u8,
1378    /// Duration Hours: 1 byte 1..=99
1379    pub duration_h: u8,
1380    /// Duration Minutes: 1 byte 0..=59
1381    pub duration_min: u8,
1382}
1383
1384#[repr(transparent)]
1385pub struct VendorID(pub [u8; 3]);
1386impl VendorID {
1387    /**
1388     * Use this if there is no vendor ID (CEC_G_VENDOR_ID) or if the vendor ID
1389     * should be disabled (CEC_S_VENDOR_ID)
1390     */
1391    pub const NONE: u32 = 0xffffffff;
1392    /**
1393     * Use this neutral ID (assigned to HDMI Licensing, LLC.) when a valid vendor ID
1394     * is required instead of leaving it disabled.
1395     */
1396    pub const HDMI: u32 = 0x000c03;
1397}
1398
1399bitflags! {
1400    /// Payload of [CecOpcode::SetAnalogueTimer], [CecOpcode::SetDigitalTimer] or [CecOpcode::SetExtTimer]
1401    ///
1402    /// Repeat recording or don't (if zero)
1403    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1404    pub struct RecordingSequence : u8 {
1405        const SUNDAY = 0x01;
1406        const MONDAY = 0x02;
1407        const TUESDAY = 0x04;
1408        const WEDNESDAY = 0x08;
1409        const THURSDAY = 0x10;
1410        const FRIDAY = 0x20;
1411        const SATURDAY = 0x40;
1412    }
1413}
1414
1415// ---  Power Status Operand (pwr_state)  ---
1416/// Payload of [CecOpcode::ReportPowerStatus]
1417#[derive(Debug, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
1418#[repr(u8)]
1419pub enum CecPowerStatus {
1420    On = 0,
1421    Standby = 1,
1422    InTransitionStandbyToOn = 2,
1423    InTransitionOnToStandby = 3,
1424}
1425
1426//use std::ffi::c_char;
1427#[allow(non_camel_case_types)]
1428type c_char = u8; //its actually i8, but that sucks
1429
1430/**
1431 * Payload of [CecOpcode::SetOsdString] and [CecOpcode::SetOsdName]
1432 *
1433 * Create it from a String (String has to be ascii)
1434 * ```
1435 * # use cec_linux::OSDStr;
1436 * let name: OSDStr::<15> = "pi4".to_string().try_into().unwrap();
1437 * ```
1438 *
1439 * and use it as `&str`
1440 * ```
1441 * # use cec_linux::OSDStr;
1442 * let str: &str = OSDStr::<14>::default().as_ref();
1443 * ```
1444 */
1445#[repr(transparent)]
1446#[derive(Clone)]
1447pub struct OSDStr<const MAX: usize>([c_char; MAX]);
1448
1449// from CecMsg to OSDStr
1450impl<const MAX: usize> From<&[u8]> for OSDStr<MAX> {
1451    fn from(value: &[u8]) -> Self {
1452        let mut osd = OSDStr::default();
1453        let len = MAX.min(value.len());
1454        osd.0[..len].clone_from_slice(value);
1455        osd
1456    }
1457}
1458
1459// from String to OSDStr
1460impl<const MAX: usize> TryFrom<String> for OSDStr<MAX> {
1461    type Error = ();
1462    fn try_from(value: String) -> Result<Self, Self::Error> {
1463        if value.is_ascii() {
1464            let mut v = value.into_bytes();
1465            v.resize(MAX, 0);
1466            let a = v.try_into().unwrap(); //len is ok
1467            return Ok(OSDStr(a));
1468        }
1469        Err(())
1470    }
1471}
1472
1473// from OSDStr to &str
1474impl<const MAX: usize> AsRef<str> for OSDStr<MAX> {
1475    fn as_ref(&self) -> &str {
1476        match std::ffi::CStr::from_bytes_until_nul(&self.0) {
1477            Ok(s) => s.to_str().unwrap_or_default(),
1478            Err(_) => {
1479                //no terminating null
1480                std::str::from_utf8(&self.0).unwrap_or_default()
1481            }
1482        }
1483    }
1484}
1485/*impl<const MAX: usize> std::ops::Deref for OSDStr<MAX> {
1486    type Target = str;
1487    fn deref(&self) -> &Self::Target {
1488        match std::ffi::CStr::from_bytes_until_nul(&self.0) {
1489            Ok(s) => s.to_str().unwrap_or_default(),
1490            Err(_) => {
1491                //no terminating null
1492                std::str::from_utf8(&self.0).unwrap_or_default()
1493            }
1494        }
1495    }
1496}*/
1497impl<const MAX: usize> std::fmt::Display for OSDStr<MAX> {
1498    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1499        f.write_str(self.as_ref())
1500    }
1501}
1502impl<const MAX: usize> std::fmt::Debug for OSDStr<MAX> {
1503    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1504        f.write_str(self.as_ref())
1505    }
1506}
1507
1508impl<const MAX: usize> Default for OSDStr<MAX> {
1509    fn default() -> Self {
1510        Self([0; MAX])
1511    }
1512}
1513
1514/*
1515// --- Ethernet-over-HDMI: nobody ever does this... ---
1516const CEC_MSG_CDC_HEC_INQUIRE_STATE: u8 = 0x00;
1517const CEC_MSG_CDC_HEC_REPORT_STATE: u8 = 0x01;
1518const CEC_MSG_CDC_HEC_SET_STATE_ADJACENT: u8 = 0x02;
1519const CEC_MSG_CDC_HEC_SET_STATE: u8 = 0x03;
1520
1521const CEC_MSG_CDC_HEC_REQUEST_DEACTIVATION: u8 = 0x04;
1522const CEC_MSG_CDC_HEC_NOTIFY_ALIVE: u8 = 0x05;
1523const CEC_MSG_CDC_HEC_DISCOVER: u8 = 0x06;
1524// --- Hotplug Detect messages ---
1525const CEC_MSG_CDC_HPD_SET_STATE: u8 = 0x10;
1526// ---  HPD State Operand (hpd_state)  ---
1527const CEC_MSG_CDC_HPD_REPORT_STATE: u8 = 0x11;
1528
1529// ---  Record Source Type Operand (rec_src_type)  ---
1530const CEC_OP_RECORD_SRC_OWN: u8 = 1;
1531const CEC_OP_RECORD_SRC_DIGITAL: u8 = 2;
1532const CEC_OP_RECORD_SRC_ANALOG: u8 = 3;
1533const CEC_OP_RECORD_SRC_EXT_PLUG: u8 = 4;
1534const CEC_OP_RECORD_SRC_EXT_PHYS_ADDR: u8 = 5;
1535// ---  Service Identification Method Operand (service_id_method)  ---
1536const CEC_OP_SERVICE_ID_METHOD_BY_DIG_ID: u8 = 0;
1537const CEC_OP_SERVICE_ID_METHOD_BY_CHANNEL: u8 = 1;
1538// ---  Digital Service Broadcast System Operand (dig_bcast_system)  ---
1539const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ARIB_GEN: u8 = 0x00;
1540const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_GEN: u8 = 0x01;
1541const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_GEN: u8 = 0x02;
1542const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ARIB_BS: u8 = 0x08;
1543const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ARIB_CS: u8 = 0x09;
1544const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ARIB_T: u8 = 0x0a;
1545const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_CABLE: u8 = 0x10;
1546const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_SAT: u8 = 0x11;
1547const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_ATSC_T: u8 = 0x12;
1548const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_C: u8 = 0x18;
1549const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_S: u8 = 0x19;
1550const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_S2: u8 = 0x1a;
1551const CEC_OP_DIG_SERVICE_BCAST_SYSTEM_DVB_T: u8 = 0x1b;
1552// ---  Analogue Broadcast Type Operand (ana_bcast_type)  ---
1553const CEC_OP_ANA_BCAST_TYPE_CABLE: u8 = 0;
1554const CEC_OP_ANA_BCAST_TYPE_SATELLITE: u8 = 1;
1555const CEC_OP_ANA_BCAST_TYPE_TERRESTRIAL: u8 = 2;
1556// ---  Broadcast System Operand (bcast_system)  ---
1557const CEC_OP_BCAST_SYSTEM_PAL_BG: u8 = 0x00;
1558const CEC_OP_BCAST_SYSTEM_SECAM_LQ: u8 = 0x01; // * SECAM L' *
1559const CEC_OP_BCAST_SYSTEM_PAL_M: u8 = 0x02;
1560const CEC_OP_BCAST_SYSTEM_NTSC_M: u8 = 0x03;
1561const CEC_OP_BCAST_SYSTEM_PAL_I: u8 = 0x04;
1562const CEC_OP_BCAST_SYSTEM_SECAM_DK: u8 = 0x05;
1563const CEC_OP_BCAST_SYSTEM_SECAM_BG: u8 = 0x06;
1564const CEC_OP_BCAST_SYSTEM_SECAM_L: u8 = 0x07;
1565const CEC_OP_BCAST_SYSTEM_PAL_DK: u8 = 0x08;
1566const CEC_OP_BCAST_SYSTEM_OTHER: u8 = 0x1f;
1567// ---  Channel Number Format Operand (channel_number_fmt)  ---
1568const CEC_OP_CHANNEL_NUMBER_FMT_1_PART: u8 = 0x01;
1569const CEC_OP_CHANNEL_NUMBER_FMT_2_PART: u8 = 0x02;
1570
1571// ---  Record Status Operand (rec_status)  ---
1572const CEC_OP_RECORD_STATUS_CUR_SRC: u8 = 0x01;
1573const CEC_OP_RECORD_STATUS_DIG_SERVICE: u8 = 0x02;
1574const CEC_OP_RECORD_STATUS_ANA_SERVICE: u8 = 0x03;
1575const CEC_OP_RECORD_STATUS_EXT_INPUT: u8 = 0x04;
1576const CEC_OP_RECORD_STATUS_NO_DIG_SERVICE: u8 = 0x05;
1577const CEC_OP_RECORD_STATUS_NO_ANA_SERVICE: u8 = 0x06;
1578const CEC_OP_RECORD_STATUS_NO_SERVICE: u8 = 0x07;
1579const CEC_OP_RECORD_STATUS_INVALID_EXT_PLUG: u8 = 0x09;
1580const CEC_OP_RECORD_STATUS_INVALID_EXT_PHYS_ADDR: u8 = 0x0a;
1581const CEC_OP_RECORD_STATUS_UNSUP_CA: u8 = 0x0b;
1582const CEC_OP_RECORD_STATUS_NO_CA_ENTITLEMENTS: u8 = 0x0c;
1583const CEC_OP_RECORD_STATUS_CANT_COPY_SRC: u8 = 0x0d;
1584const CEC_OP_RECORD_STATUS_NO_MORE_COPIES: u8 = 0x0e;
1585const CEC_OP_RECORD_STATUS_NO_MEDIA: u8 = 0x10;
1586const CEC_OP_RECORD_STATUS_PLAYING: u8 = 0x11;
1587const CEC_OP_RECORD_STATUS_ALREADY_RECORDING: u8 = 0x12;
1588const CEC_OP_RECORD_STATUS_MEDIA_PROT: u8 = 0x13;
1589const CEC_OP_RECORD_STATUS_NO_SIGNAL: u8 = 0x14;
1590const CEC_OP_RECORD_STATUS_MEDIA_PROBLEM: u8 = 0x15;
1591const CEC_OP_RECORD_STATUS_NO_SPACE: u8 = 0x16;
1592const CEC_OP_RECORD_STATUS_PARENTAL_LOCK: u8 = 0x17;
1593const CEC_OP_RECORD_STATUS_TERMINATED_OK: u8 = 0x1a;
1594const CEC_OP_RECORD_STATUS_ALREADY_TERM: u8 = 0x1b;
1595const CEC_OP_RECORD_STATUS_OTHER: u8 = 0x1f;
1596
1597
1598// ---  External Source Specifier Operand (ext_src_spec)  ---
1599const CEC_OP_EXT_SRC_PLUG: u8 = 0x04;
1600const CEC_OP_EXT_SRC_PHYS_ADDR: u8 = 0x05;
1601
1602// ---  Timer Cleared Status Data Operand (timer_cleared_status)  ---
1603const CEC_OP_TIMER_CLR_STAT_RECORDING: u8 = 0x00;
1604const CEC_OP_TIMER_CLR_STAT_NO_MATCHING: u8 = 0x01;
1605const CEC_OP_TIMER_CLR_STAT_NO_INFO: u8 = 0x02;
1606const CEC_OP_TIMER_CLR_STAT_CLEARED: u8 = 0x80;
1607
1608// ---  Timer Overlap Warning Operand (timer_overlap_warning)  ---
1609const CEC_OP_TIMER_OVERLAP_WARNING_NO_OVERLAP: u8 = 0;
1610const CEC_OP_TIMER_OVERLAP_WARNING_OVERLAP: u8 = 1;
1611// ---  Media Info Operand (media_info)  ---
1612const CEC_OP_MEDIA_INFO_UNPROT_MEDIA: u8 = 0;
1613const CEC_OP_MEDIA_INFO_PROT_MEDIA: u8 = 1;
1614const CEC_OP_MEDIA_INFO_NO_MEDIA: u8 = 2;
1615// ---  Programmed Indicator Operand (prog_indicator)  ---
1616const CEC_OP_PROG_IND_NOT_PROGRAMMED: u8 = 0;
1617const CEC_OP_PROG_IND_PROGRAMMED: u8 = 1;
1618// ---  Programmed Info Operand (prog_info)  ---
1619const CEC_OP_PROG_INFO_ENOUGH_SPACE: u8 = 0x08;
1620const CEC_OP_PROG_INFO_NOT_ENOUGH_SPACE: u8 = 0x09;
1621const CEC_OP_PROG_INFO_MIGHT_NOT_BE_ENOUGH_SPACE: u8 = 0x0b;
1622const CEC_OP_PROG_INFO_NONE_AVAILABLE: u8 = 0x0a;
1623// ---  Not Programmed Error Info Operand (prog_error)  ---
1624const CEC_OP_PROG_ERROR_NO_FREE_TIMER: u8 = 0x01;
1625const CEC_OP_PROG_ERROR_DATE_OUT_OF_RANGE: u8 = 0x02;
1626const CEC_OP_PROG_ERROR_REC_SEQ_ERROR: u8 = 0x03;
1627const CEC_OP_PROG_ERROR_INV_EXT_PLUG: u8 = 0x04;
1628const CEC_OP_PROG_ERROR_INV_EXT_PHYS_ADDR: u8 = 0x05;
1629const CEC_OP_PROG_ERROR_CA_UNSUPP: u8 = 0x06;
1630const CEC_OP_PROG_ERROR_INSUF_CA_ENTITLEMENTS: u8 = 0x07;
1631const CEC_OP_PROG_ERROR_RESOLUTION_UNSUPP: u8 = 0x08;
1632const CEC_OP_PROG_ERROR_PARENTAL_LOCK: u8 = 0x09;
1633const CEC_OP_PROG_ERROR_CLOCK_FAILURE: u8 = 0x0a;
1634const CEC_OP_PROG_ERROR_DUPLICATE: u8 = 0x0e;
1635
1636// ---  Valid for RC Profile and Device Feature operands  ---
1637const CEC_OP_FEAT_EXT: u8 = 0x80; //   / * Extension bit *
1638                                  / * RC Profile Operand (rc_profile) * /
1639const CEC_OP_FEAT_RC_TV_PROFILE_NONE: u8 = 0x00;
1640const CEC_OP_FEAT_RC_TV_PROFILE_1: u8 = 0x02;
1641const CEC_OP_FEAT_RC_TV_PROFILE_2: u8 = 0x06;
1642const CEC_OP_FEAT_RC_TV_PROFILE_3: u8 = 0x0a;
1643const CEC_OP_FEAT_RC_TV_PROFILE_4: u8 = 0x0e;
1644const CEC_OP_FEAT_RC_SRC_HAS_DEV_ROOT_MENU: u8 = 0x50;
1645const CEC_OP_FEAT_RC_SRC_HAS_DEV_SETUP_MENU: u8 = 0x48;
1646const CEC_OP_FEAT_RC_SRC_HAS_CONTENTS_MENU: u8 = 0x44;
1647const CEC_OP_FEAT_RC_SRC_HAS_MEDIA_TOP_MENU: u8 = 0x42;
1648const CEC_OP_FEAT_RC_SRC_HAS_MEDIA_CONTEXT_MENU: u8 = 0x41;
1649// ---  Device Feature Operand (dev_features)  ---
1650const CEC_OP_FEAT_DEV_HAS_RECORD_TV_SCREEN: u8 = 0x40;
1651const CEC_OP_FEAT_DEV_HAS_SET_OSD_STRING: u8 = 0x20;
1652const CEC_OP_FEAT_DEV_HAS_DECK_CONTROL: u8 = 0x10;
1653const CEC_OP_FEAT_DEV_HAS_SET_AUDIO_RATE: u8 = 0x08;
1654const CEC_OP_FEAT_DEV_SINK_HAS_ARC_TX: u8 = 0x04;
1655const CEC_OP_FEAT_DEV_SOURCE_HAS_ARC_RX: u8 = 0x02;
1656
1657
1658// ---  Recording Flag Operand (rec_flag)  ---
1659const CEC_OP_REC_FLAG_USED: u8 = 0;
1660const CEC_OP_REC_FLAG_NOT_USED: u8 = 1;
1661// ---  Tuner Display Info Operand (tuner_display_info)  ---
1662const CEC_OP_TUNER_DISPLAY_INFO_DIGITAL: u8 = 0;
1663const CEC_OP_TUNER_DISPLAY_INFO_NONE: u8 = 1;
1664const CEC_OP_TUNER_DISPLAY_INFO_ANALOGUE: u8 = 2;
1665
1666
1667// ---  UI Broadcast Type Operand (ui_bcast_type)  ---
1668const CEC_OP_UI_BCAST_TYPE_TOGGLE_ALL: u8 = 0x00;
1669const CEC_OP_UI_BCAST_TYPE_TOGGLE_DIG_ANA: u8 = 0x01;
1670const CEC_OP_UI_BCAST_TYPE_ANALOGUE: u8 = 0x10;
1671const CEC_OP_UI_BCAST_TYPE_ANALOGUE_T: u8 = 0x20;
1672const CEC_OP_UI_BCAST_TYPE_ANALOGUE_CABLE: u8 = 0x30;
1673const CEC_OP_UI_BCAST_TYPE_ANALOGUE_SAT: u8 = 0x40;
1674const CEC_OP_UI_BCAST_TYPE_DIGITAL: u8 = 0x50;
1675const CEC_OP_UI_BCAST_TYPE_DIGITAL_T: u8 = 0x60;
1676const CEC_OP_UI_BCAST_TYPE_DIGITAL_CABLE: u8 = 0x70;
1677const CEC_OP_UI_BCAST_TYPE_DIGITAL_SAT: u8 = 0x80;
1678const CEC_OP_UI_BCAST_TYPE_DIGITAL_COM_SAT: u8 = 0x90;
1679const CEC_OP_UI_BCAST_TYPE_DIGITAL_COM_SAT2: u8 = 0x91;
1680const CEC_OP_UI_BCAST_TYPE_IP: u8 = 0xa0;
1681// ---  UI Sound Presentation Control Operand (ui_snd_pres_ctl)  ---
1682const CEC_OP_UI_SND_PRES_CTL_DUAL_MONO: u8 = 0x10;
1683const CEC_OP_UI_SND_PRES_CTL_KARAOKE: u8 = 0x20;
1684const CEC_OP_UI_SND_PRES_CTL_DOWNMIX: u8 = 0x80;
1685const CEC_OP_UI_SND_PRES_CTL_REVERB: u8 = 0x90;
1686const CEC_OP_UI_SND_PRES_CTL_EQUALIZER: u8 = 0xa0;
1687const CEC_OP_UI_SND_PRES_CTL_BASS_UP: u8 = 0xb1;
1688const CEC_OP_UI_SND_PRES_CTL_BASS_NEUTRAL: u8 = 0xb2;
1689const CEC_OP_UI_SND_PRES_CTL_BASS_DOWN: u8 = 0xb3;
1690const CEC_OP_UI_SND_PRES_CTL_TREBLE_UP: u8 = 0xc1;
1691const CEC_OP_UI_SND_PRES_CTL_TREBLE_NEUTRAL: u8 = 0xc2;
1692const CEC_OP_UI_SND_PRES_CTL_TREBLE_DOWN: u8 = 0xc3;
1693
1694// ---  Audio Format ID Operand (audio_format_id)  ---
1695const CEC_OP_AUD_FMT_ID_CEA861: u8 = 0;
1696const CEC_OP_AUD_FMT_ID_CEA861_CXT: u8 = 1;
1697
1698// ---  Audio Rate Operand (audio_rate)  ---
1699const CEC_OP_AUD_RATE_OFF: u8 = 0;
1700const CEC_OP_AUD_RATE_WIDE_STD: u8 = 1;
1701const CEC_OP_AUD_RATE_WIDE_FAST: u8 = 2;
1702const CEC_OP_AUD_RATE_WIDE_SLOW: u8 = 3;
1703const CEC_OP_AUD_RATE_NARROW_STD: u8 = 4;
1704const CEC_OP_AUD_RATE_NARROW_FAST: u8 = 5;
1705const CEC_OP_AUD_RATE_NARROW_SLOW: u8 = 6;
1706
1707// ---  Low Latency Mode Operand (low_latency_mode)  ---
1708const CEC_OP_LOW_LATENCY_MODE_OFF: u8 = 0;
1709const CEC_OP_LOW_LATENCY_MODE_ON: u8 = 1;
1710// ---  Audio Output Compensated Operand (audio_out_compensated)  ---
1711const CEC_OP_AUD_OUT_COMPENSATED_NA: u8 = 0;
1712const CEC_OP_AUD_OUT_COMPENSATED_DELAY: u8 = 1;
1713const CEC_OP_AUD_OUT_COMPENSATED_NO_DELAY: u8 = 2;
1714const CEC_OP_AUD_OUT_COMPENSATED_PARTIAL_DELAY: u8 = 3;
1715
1716// ---  HEC Functionality State Operand (hec_func_state)  ---
1717const CEC_OP_HEC_FUNC_STATE_NOT_SUPPORTED: u8 = 0;
1718const CEC_OP_HEC_FUNC_STATE_INACTIVE: u8 = 1;
1719const CEC_OP_HEC_FUNC_STATE_ACTIVE: u8 = 2;
1720const CEC_OP_HEC_FUNC_STATE_ACTIVATION_FIELD: u8 = 3;
1721// ---  Host Functionality State Operand (host_func_state)  ---
1722const CEC_OP_HOST_FUNC_STATE_NOT_SUPPORTED: u8 = 0;
1723const CEC_OP_HOST_FUNC_STATE_INACTIVE: u8 = 1;
1724const CEC_OP_HOST_FUNC_STATE_ACTIVE: u8 = 2;
1725// ---  ENC Functionality State Operand (enc_func_state)  ---
1726const CEC_OP_ENC_FUNC_STATE_EXT_CON_NOT_SUPPORTED: u8 = 0;
1727const CEC_OP_ENC_FUNC_STATE_EXT_CON_INACTIVE: u8 = 1;
1728const CEC_OP_ENC_FUNC_STATE_EXT_CON_ACTIVE: u8 = 2;
1729// ---  CDC Error Code Operand (cdc_errcode)  ---
1730const CEC_OP_CDC_ERROR_CODE_NONE: u8 = 0;
1731const CEC_OP_CDC_ERROR_CODE_CAP_UNSUPPORTED: u8 = 1;
1732const CEC_OP_CDC_ERROR_CODE_WRONG_STATE: u8 = 2;
1733const CEC_OP_CDC_ERROR_CODE_OTHER: u8 = 3;
1734// ---  HEC Support Operand (hec_support)  ---
1735const CEC_OP_HEC_SUPPORT_NO: u8 = 0;
1736const CEC_OP_HEC_SUPPORT_YES: u8 = 1;
1737// ---  HEC Activation Operand (hec_activation)  ---
1738const CEC_OP_HEC_ACTIVATION_ON: u8 = 0;
1739const CEC_OP_HEC_ACTIVATION_OFF: u8 = 1;
1740
1741// ---  HEC Set State Operand (hec_set_state)  ---
1742const CEC_OP_HEC_SET_STATE_DEACTIVATE: u8 = 0;
1743const CEC_OP_HEC_SET_STATE_ACTIVATE: u8 = 1;
1744const CEC_OP_HPD_STATE_CP_EDID_DISABLE: u8 = 0;
1745const CEC_OP_HPD_STATE_CP_EDID_ENABLE: u8 = 1;
1746const CEC_OP_HPD_STATE_CP_EDID_DISABLE_ENABLE: u8 = 2;
1747const CEC_OP_HPD_STATE_EDID_DISABLE: u8 = 3;
1748const CEC_OP_HPD_STATE_EDID_ENABLE: u8 = 4;
1749const CEC_OP_HPD_STATE_EDID_DISABLE_ENABLE: u8 = 5;
1750// ---  HPD Error Code Operand (hpd_error)  ---
1751const CEC_OP_HPD_ERROR_NONE: u8 = 0;
1752const CEC_OP_HPD_ERROR_INITIATOR_NOT_CAPABLE: u8 = 1;
1753const CEC_OP_HPD_ERROR_INITIATOR_WRONG_STATE: u8 = 2;
1754const CEC_OP_HPD_ERROR_OTHER: u8 = 3;
1755const CEC_OP_HPD_ERROR_NONE_NO_VIDEO: u8 = 4;
1756*/