mod player;
use alloc::borrow::Cow;
use alloc::collections::TryReserveError;
use alloc::vec::Vec;
use core::{error, fmt};
pub use player::{YawPlayer, YawSetpoint};
use crate::formats::binary::{BinaryBlockType, BinaryFile, BinaryFileError};
use crate::parsing::read_i16;
const HEADER_LENGTH: usize = 3;
const DELTA_LENGTH: usize = 4;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum YawControlError {
Corrupted,
File(BinaryFileError),
OutOfMemory,
}
impl fmt::Display for YawControlError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Corrupted => f.write_str("the yaw control block is malformed"),
Self::File(_) => f.write_str("the show file could not be read"),
Self::OutOfMemory => f.write_str("out of memory"),
}
}
}
impl error::Error for YawControlError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::File(err) => Some(err),
Self::Corrupted | Self::OutOfMemory => None,
}
}
}
impl From<BinaryFileError> for YawControlError {
fn from(err: BinaryFileError) -> Self {
Self::File(err)
}
}
impl From<TryReserveError> for YawControlError {
fn from(_: TryReserveError) -> Self {
Self::OutOfMemory
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct YawControl<'a> {
bytes: Cow<'a, [u8]>,
header_length: usize,
auto_yaw: bool,
yaw_offset_ddeg: i16,
}
impl Default for YawControl<'static> {
fn default() -> Self {
Self::new()
}
}
impl YawControl<'static> {
#[must_use]
pub const fn new() -> Self {
Self {
bytes: Cow::Borrowed(&[]),
header_length: 0,
auto_yaw: false,
yaw_offset_ddeg: 0,
}
}
pub fn from_vec(bytes: Vec<u8>) -> Result<Self, YawControlError> {
Self::from_cow(Cow::Owned(bytes))
}
}
impl<'a> YawControl<'a> {
pub fn from_buffer(bytes: &'a [u8]) -> Result<Self, YawControlError> {
Self::from_cow(Cow::Borrowed(bytes))
}
pub fn from_binary_file(file: &BinaryFile<'a>) -> Result<Option<Self>, YawControlError> {
file.find_first_block_by_type(BinaryBlockType::YAW_CONTROL)?
.map(|block| Self::from_buffer(block.body))
.transpose()
}
fn from_cow(bytes: Cow<'a, [u8]>) -> Result<Self, YawControlError> {
let Some(deltas) = bytes.len().checked_sub(HEADER_LENGTH) else {
return Err(YawControlError::Corrupted);
};
if !deltas.is_multiple_of(DELTA_LENGTH) {
return Err(YawControlError::Corrupted);
}
let auto_yaw = bytes.first().is_some_and(|&flags| flags & 0x01 != 0);
let yaw_offset_ddeg = read_i16(&bytes, 1).unwrap_or_default();
Ok(Self {
bytes,
header_length: HEADER_LENGTH,
auto_yaw,
yaw_offset_ddeg,
})
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
pub const fn auto_yaw(&self) -> bool {
self.auto_yaw
}
#[must_use]
pub const fn yaw_offset_ddeg(&self) -> i16 {
self.yaw_offset_ddeg
}
#[must_use]
pub fn num_deltas(&self) -> usize {
self.deltas().len() / DELTA_LENGTH
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.num_deltas() == 0
}
#[must_use]
pub fn total_duration_msec(&self) -> u32 {
YawPlayer::new(self).total_duration_msec()
}
pub fn set_constant_yaw(&mut self, yaw_deg: f32) -> Result<(), YawControlError> {
#[expect(
clippy::cast_possible_truncation,
reason = "the float-to-integer cast saturates, and the result is clamped"
)]
let yaw_ddeg = libm::roundf(yaw_deg * 10.0) as i32;
let yaw_ddeg =
i16::try_from(yaw_ddeg).unwrap_or(if yaw_ddeg < 0 { i16::MIN } else { i16::MAX });
let [low, high] = yaw_ddeg.to_le_bytes();
let mut bytes = Vec::new();
bytes.try_reserve_exact(HEADER_LENGTH)?;
bytes.extend_from_slice(&[0, low, high]);
*self = YawControl::from_vec(bytes)?;
Ok(())
}
fn deltas(&self) -> &[u8] {
self.bytes.get(self.header_length..).unwrap_or_default()
}
}