//! Control messages inside the encrypted frame (`docs/PROTOCOL.md` 3.3): `type u16 LE`, `length u16 LE`, body. use crate::Result; use crate::input::InputEvent; use crate::util::{byte, cap, malformed, need, u16_le, u32_be}; /// Length of the message header (type + length). pub const MESSAGE_HEADER_LEN: usize = 4; /// Maximum size of one decrypted message, in bytes. pub const MAX_MESSAGE_BYTES: usize = super::frame::MAX_FRAME_BYTES - super::frame::FRAME_HEADER_LEN; /// Length of the HDR metadata block in `HDR_MODE` (15 × u16). pub const HDR_METADATA_LEN: usize = 30; /// Known message type codes. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(u16)] pub enum MessageType { /// Start, part A (client → host). StartA = 0x0305, /// Start, part B (client → host); the host starts video and audio on it. StartB = 0x0307, /// Reference frame invalidation request (client → host). InvalidateRefFrames = 0x0301, /// IDR frame request (client → host). IdrFrame = 0x0302, /// Loss statistics (client → host). LossStats = 0x0201, /// Frame statistics (client → host). FrameStats = 0x0204, /// Input (client → host). InputData = 0x0206, /// Keep-alive (client → host). PeriodicPing = 0x0200, /// Termination (host → client). Termination = 0x0100, /// Termination with a 32-bit error code (host → client). TerminationExtended = 0x0109, /// HDR mode change (host → client). HdrMode = 0x010e, /// Rumble (host → client). RumbleData = 0x010b, /// Trigger rumble (host → client). RumbleTriggers = 0x5500, /// Start or stop motion events (host → client). MotionEvent = 0x5501, /// Controller LED colour (host → client). RgbLed = 0x5502, /// Adaptive trigger effect (host → client), layout UNKNOWN. TriggerEffect = 0x5503, } impl MessageType { const ALL: [Self; 16] = [ Self::StartA, Self::StartB, Self::InvalidateRefFrames, Self::IdrFrame, Self::LossStats, Self::FrameStats, Self::InputData, Self::PeriodicPing, Self::Termination, Self::TerminationExtended, Self::HdrMode, Self::RumbleData, Self::RumbleTriggers, Self::MotionEvent, Self::RgbLed, Self::TriggerEffect, ]; } impl TryFrom for MessageType { type Error = crate::Error; /// # Errors /// [`crate::Error::UnexpectedValue`] for an unknown code. fn try_from(code: u16) -> Result { Self::ALL .into_iter() .find(|t| *t as u16 == code) .ok_or(crate::Error::UnexpectedValue { what: "control message type", value: code.into() }) } } /// A message split into type and body, not interpreted. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RawMessage<'a> { /// Type code (possibly unknown). pub message_type: u16, /// Body, exactly `length` bytes. pub body: &'a [u8], } /// Splits a decrypted message. The length field must equal the bytes after the header. /// /// # Errors /// [`crate::Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`crate::Error::Truncated`] under /// [`MESSAGE_HEADER_LEN`], [`crate::Error::Malformed`] for a length that does not match. pub fn parse_message(message: &[u8]) -> Result> { const W: &str = "control message"; cap(W, MAX_MESSAGE_BYTES, message.len())?; need(W, MESSAGE_HEADER_LEN, message.len())?; let message_type = u16_le(W, message, 0)?; if usize::from(u16_le(W, message, 2)?) != message.len() - MESSAGE_HEADER_LEN { return Err(malformed("control message length")); } Ok(RawMessage { message_type, body: message.get(MESSAGE_HEADER_LEN..).unwrap_or(&[]) }) } /// Motion sensor kinds of `MOTION_EVENT`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum MotionKind { /// Accelerometer (1). Accelerometer, /// Gyroscope (2). Gyroscope, } /// HDR mastering metadata as sent in `HDR_MODE` (15 little-endian u16 fields, layout `[M*]`, unconfirmed). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct HdrMetadata { /// Display primaries x/y for R, G, B. pub display_primaries: [(u16, u16); 3], /// White point x/y. pub white_point: (u16, u16), /// Maximum display luminance, nits. pub max_display_luminance: u16, /// Minimum display luminance, 1/10000 nit. pub min_display_luminance: u16, /// Maximum content light level, nits. pub max_content_light_level: u16, /// Maximum frame-average light level, nits. pub max_frame_average_light_level: u16, /// Maximum full-frame luminance, nits. pub max_full_frame_luminance: u16, } /// A message from the host. #[derive(Clone, Debug, PartialEq, Eq)] pub enum HostMessage { /// Rumble a controller. Rumble { /// Controller number. controller: u16, /// Low-frequency motor. low_frequency: u16, /// High-frequency motor. high_frequency: u16, }, /// Rumble the triggers. RumbleTriggers { /// Controller number. controller: u16, /// Left trigger. left: u16, /// Right trigger. right: u16, }, /// Start (rate > 0) or stop (rate 0) sending motion events. MotionEvent { /// Controller number. controller: u16, /// Report rate, Hz. rate_hz: u16, /// Sensor. kind: MotionKind, }, /// Set a controller's LED colour. RgbLed { /// Controller number. controller: u16, /// Red. r: u8, /// Green. g: u8, /// Blue. b: u8, }, /// HDR turned on or off. HdrMode { /// HDR on. enabled: bool, /// Mastering metadata, if the body carries it. metadata: Option, }, /// The host ended the session. Termination { /// Error code (extended form), `None` for the plain form. `0x80030023` = graceful. error_code: Option, }, /// A known or unknown type this client does not interpret; kept for stats and logs. Other { /// Type code. message_type: u16, /// Body length (the body itself is not kept). body_len: usize, }, } fn exact(body: &[u8], len: usize, what: &'static str) -> Result<()> { if body.len() == len { Ok(()) } else { Err(malformed(what)) } } /// Interprets a decrypted message from the host. Bodies are little-endian (UNKNOWN U23), except the extended /// termination code (big-endian). /// /// # Errors /// As [`parse_message`]; [`crate::Error::Malformed`] when a known type's body has the wrong length; /// [`crate::Error::UnexpectedValue`] for an unknown motion kind. pub fn parse_host_message(message: &[u8]) -> Result { const W: &str = "host message"; let raw = parse_message(message)?; let b = raw.body; let u16_at = |at: usize| u16_le(W, b, at); Ok(match raw.message_type { 0x010b => { exact(b, 10, "rumble body")?; HostMessage::Rumble { controller: u16_at(4)?, low_frequency: u16_at(6)?, high_frequency: u16_at(8)? } } 0x5500 => { exact(b, 6, "trigger rumble body")?; HostMessage::RumbleTriggers { controller: u16_at(0)?, left: u16_at(2)?, right: u16_at(4)? } } 0x5501 => { exact(b, 5, "motion event body")?; let kind = match byte(W, b, 4)? { 1 => MotionKind::Accelerometer, 2 => MotionKind::Gyroscope, other => return Err(crate::Error::UnexpectedValue { what: "motion kind", value: other.into() }), }; HostMessage::MotionEvent { controller: u16_at(0)?, rate_hz: u16_at(2)?, kind } } 0x5502 => { exact(b, 5, "rgb led body")?; HostMessage::RgbLed { controller: u16_at(0)?, r: byte(W, b, 2)?, g: byte(W, b, 3)?, b: byte(W, b, 4)? } } 0x0109 => { exact(b, 4, "termination body")?; HostMessage::Termination { error_code: Some(u32_be(W, b, 0)?) } } 0x0100 => HostMessage::Termination { error_code: None }, 0x010e => { let enabled = byte(W, b, 0).map_err(|_| malformed("hdr mode body"))? != 0; let metadata = match b.len() { 1 => None, 31 => { let v = |i: usize| u16_le(W, b, 1 + 2 * i); Some(HdrMetadata { display_primaries: [(v(0)?, v(1)?), (v(2)?, v(3)?), (v(4)?, v(5)?)], white_point: (v(6)?, v(7)?), max_display_luminance: v(8)?, min_display_luminance: v(9)?, max_content_light_level: v(10)?, max_frame_average_light_level: v(11)?, max_full_frame_luminance: v(12)?, }) } _ => return Err(malformed("hdr mode body")), }; HostMessage::HdrMode { enabled, metadata } } other => HostMessage::Other { message_type: other, body_len: b.len() }, }) } /// A message to the host. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ClientMessage { /// `START_A` (body UNKNOWN U10). StartA, /// `START_B` (body UNKNOWN U10): the host starts video and audio. StartB, /// Keep-alive (body UNKNOWN U10). PeriodicPing, /// Ask for an IDR frame (body UNKNOWN U10). RequestIdrFrame, /// Ask the host to stop referencing frames `first..=last`. InvalidateRefFrames { /// First lost frame index. first: u32, /// Last lost frame index. last: u32, }, /// User input. Input(InputEvent), } /// Serializes a message to the host (type, length, body), ready for [`super::ControlCipher::seal`]. /// /// # Errors /// [`crate::Error::Unsupported`] for a message whose body is still UNKNOWN (U10: START_A, START_B, /// PERIODIC_PING, IDR request; refused rather than guessed); input errors as [`crate::input::encode_input`]. pub fn encode_client_message(message: &ClientMessage) -> Result> { match message { ClientMessage::InvalidateRefFrames { first, last } => { let mut m = Vec::with_capacity(28); m.extend_from_slice(&(MessageType::InvalidateRefFrames as u16).to_le_bytes()); m.extend_from_slice(&24u16.to_le_bytes()); m.extend_from_slice(&first.to_le_bytes()); m.extend_from_slice(&[0; 4]); m.extend_from_slice(&last.to_le_bytes()); m.extend_from_slice(&[0; 12]); Ok(m) } ClientMessage::Input(e) => crate::input::encode_input(e), ClientMessage::StartA | ClientMessage::StartB | ClientMessage::PeriodicPing | ClientMessage::RequestIdrFrame => { Err(crate::Error::Unsupported { what: "a control message whose body is still UNKNOWN (U10)" }) } } }