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