mod player;
use alloc::collections::TryReserveError;
use alloc::vec::IntoIter;
use alloc::vec::Vec;
use core::slice::Iter;
use core::{error, fmt};
pub use player::EventListPlayer;
use crate::formats::binary::{BinaryBlockType, BinaryFile, BinaryFileError};
const SIZE_OF_EVENT: usize = 10;
const PYRO_OFF_PAYLOAD: [u8; 4] = [0xff; 4];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct EventType(pub u8);
impl EventType {
pub const NONE: Self = Self(0);
pub const PYRO: Self = Self(1);
pub const LIGHT: Self = Self(2);
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Event {
pub time_msec: u32,
pub event_type: EventType,
pub subtype: u8,
pub payload: [u8; 4],
}
impl Event {
pub const LIGHT_SET_SOURCE: u8 = 0;
pub const LIGHT_SET_PIXEL_X: u8 = 1;
pub const LIGHT_SET_PIXEL_Y: u8 = 2;
#[must_use]
pub const fn payload_u32(&self) -> u32 {
u32::from_le_bytes(self.payload)
}
#[must_use]
pub const fn payload_f32(&self) -> f32 {
f32::from_le_bytes(self.payload)
}
#[must_use]
pub fn is_pyro_on(&self) -> bool {
self.event_type == EventType::PYRO && self.payload != PYRO_OFF_PAYLOAD
}
#[must_use]
pub fn is_pyro_off(&self) -> bool {
self.event_type == EventType::PYRO && self.payload == PYRO_OFF_PAYLOAD
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EventListError {
Corrupted,
OutOfOrder,
File(BinaryFileError),
OutOfMemory,
}
impl fmt::Display for EventListError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Corrupted => f.write_str("the events are not sorted by timestamp"),
Self::OutOfOrder => f.write_str("the event is earlier than the last event"),
Self::File(_) => f.write_str("the show file could not be read"),
Self::OutOfMemory => f.write_str("out of memory"),
}
}
}
impl error::Error for EventListError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::File(err) => Some(err),
_ => None,
}
}
}
impl From<BinaryFileError> for EventListError {
fn from(err: BinaryFileError) -> Self {
Self::File(err)
}
}
impl From<TryReserveError> for EventListError {
fn from(_: TryReserveError) -> Self {
Self::OutOfMemory
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct EventList {
events: Vec<Event>,
}
impl EventList {
#[must_use]
pub const fn new() -> Self {
Self { events: Vec::new() }
}
pub fn from_buffer(body: &[u8]) -> Result<Self, EventListError> {
let (encoded, _trailing) = body.as_chunks::<SIZE_OF_EVENT>();
let mut events = Vec::new();
events.try_reserve_exact(encoded.len())?;
for &[t0, t1, t2, t3, event_type, subtype, p0, p1, p2, p3] in encoded {
let event = Event {
time_msec: u32::from_le_bytes([t0, t1, t2, t3]),
event_type: EventType(event_type),
subtype,
payload: [p0, p1, p2, p3],
};
if events
.last()
.is_some_and(|last: &Event| event.time_msec < last.time_msec)
{
return Err(EventListError::Corrupted);
}
events.push(event);
}
Ok(Self { events })
}
pub fn from_binary_file(file: &BinaryFile<'_>) -> Result<Option<Self>, EventListError> {
file.find_first_block_by_type(BinaryBlockType::EVENT_LIST)?
.map(|block| Self::from_buffer(block.body))
.transpose()
}
#[must_use]
pub const fn len(&self) -> usize {
self.events.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.events.is_empty()
}
#[must_use]
pub const fn capacity(&self) -> usize {
self.events.capacity()
}
#[must_use]
pub fn as_slice(&self) -> &[Event] {
&self.events
}
pub fn iter(&self) -> Iter<'_, Event> {
self.events.iter()
}
#[must_use]
pub fn get(&self, index: usize) -> Option<&Event> {
self.events.get(index)
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut Event> {
self.events.get_mut(index)
}
pub fn clear(&mut self) {
self.events.clear();
}
pub fn append(&mut self, event: Event) -> Result<(), EventListError> {
if self
.events
.last()
.is_some_and(|last| event.time_msec < last.time_msec)
{
return Err(EventListError::OutOfOrder);
}
self.events.try_reserve(1)?;
self.events.push(event);
Ok(())
}
pub fn insert(&mut self, event: Event) -> Result<(), EventListError> {
self.events.try_reserve(1)?;
self.insert_reserved(event);
Ok(())
}
fn insert_reserved(&mut self, event: Event) {
let (mut left, mut right) = (0, self.events.len());
while left < right {
let mid = left + (right - left) / 2;
if self
.events
.get(mid)
.is_some_and(|other| other.time_msec <= event.time_msec)
{
left = mid + 1;
} else {
right = mid;
}
}
self.events.insert(left, event);
}
pub fn remove(&mut self, index: usize) -> Option<Event> {
(index < self.events.len()).then(|| self.events.remove(index))
}
#[must_use]
pub fn is_sorted(&self) -> bool {
self.events.is_sorted_by_key(|event| event.time_msec)
}
pub fn sort(&mut self) {
for i in 1..self.events.len() {
let mut j = i;
while j > 0 && self.time_msec_at(j - 1) > self.time_msec_at(j) {
self.events.swap(j - 1, j);
j -= 1;
}
}
}
fn time_msec_at(&self, index: usize) -> u32 {
self.events.get(index).map_or(0, |event| event.time_msec)
}
pub fn add_pyro_off_events(&mut self, duration_msec: u32) -> Result<(), EventListError> {
let num_on_events = self
.events
.iter()
.filter(|event| event.is_pyro_on())
.count();
self.events.try_reserve(num_on_events)?;
let mut i = 0;
while let Some(&event) = self.events.get(i) {
i += 1;
if !event.is_pyro_on() {
continue;
}
let off_time_msec = event.time_msec.saturating_add(duration_msec);
let off_event = self
.events
.iter()
.enumerate()
.skip(i)
.find(|(_, other)| other.is_pyro_off() && other.subtype == event.subtype)
.map(|(index, other)| (index, other.time_msec));
match off_event {
Some((_, time_msec)) if time_msec <= off_time_msec => {}
found => {
if let Some((index, _)) = found {
self.events.remove(index);
}
self.insert_reserved(Event {
time_msec: off_time_msec,
event_type: EventType::PYRO,
subtype: event.subtype,
payload: PYRO_OFF_PAYLOAD,
});
}
}
}
Ok(())
}
pub fn adjust_timestamps_by_type(&mut self, event_type: EventType, delta_msec: i32) {
for event in &mut self.events {
if event.event_type == event_type {
event.time_msec = event.time_msec.saturating_add_signed(delta_msec);
}
}
self.sort();
}
}
impl<'a> IntoIterator for &'a EventList {
type Item = &'a Event;
type IntoIter = Iter<'a, Event>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl IntoIterator for EventList {
type Item = Event;
type IntoIter = IntoIter<Event>;
fn into_iter(self) -> Self::IntoIter {
self.events.into_iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn pyro(time_msec: u32, channel: u8, on: bool) -> Event {
Event {
time_msec,
event_type: EventType::PYRO,
subtype: channel,
payload: if on { [0; 4] } else { PYRO_OFF_PAYLOAD },
}
}
#[test]
fn sorting_keeps_the_order_of_equal_timestamps() {
let mut list = EventList::new();
for event in [
pyro(3000, 1, true),
pyro(1000, 2, true),
pyro(1000, 3, true),
] {
list.events.push(event);
}
list.sort();
let channels: Vec<u8> = list.iter().map(|event| event.subtype).collect();
assert_eq!(channels, [2, 3, 1]);
}
#[test]
fn removing_a_late_off_event_adds_one_in_its_place() {
let mut list = EventList::new();
for event in [pyro(1000, 1, true), pyro(9000, 1, false)] {
list.insert(event).unwrap_or_default();
}
assert_eq!(list.add_pyro_off_events(500), Ok(()));
assert_eq!(list.as_slice(), [pyro(1000, 1, true), pyro(1500, 1, false)]);
}
}