twsnap-compat 0.1.0

Compatibility with DDNet formats via libtw2
Documentation
use libtw2_demo::{ddnet, ChunkType};
use libtw2_gamenet_ddnet::Protocol as DDNet;
use libtw2_warn::Ignore;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::io;
use std::str::from_utf8;
use twsnap::time::Instant;
use twsnap::Snap;

#[derive(Debug)]
pub struct ReadError(ReadErrorInner);

#[derive(Debug)]
pub enum ReadErrorInner {
    DDNet(ddnet::ReadError),
    InnerReader,
    SnapshotWithoutTick,
}

impl Display for ReadErrorInner {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ReadErrorInner::DDNet(read_error) => read_error.fmt(f),
            ReadErrorInner::InnerReader => write!(f, "Inner reader API inconsistency"),
            ReadErrorInner::SnapshotWithoutTick => write!(f, "Snapshot with no tick in front"),
        }
    }
}
impl From<ReadErrorInner> for ReadError {
    fn from(value: ReadErrorInner) -> Self {
        ReadError(value)
    }
}
impl Display for ReadError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}
impl Error for ReadError {}

impl From<ddnet::ReadError> for ReadError {
    fn from(value: ddnet::ReadError) -> Self {
        Self(ReadErrorInner::DDNet(value))
    }
}
impl From<io::Error> for ReadError {
    fn from(value: io::Error) -> Self {
        Self(ReadErrorInner::DDNet(ddnet::ReadError::Inner(value.into())))
    }
}

pub struct DemoReader<'a> {
    reader: ddnet::DemoReader<'a, DDNet>,
}

pub enum DemoChunk {
    Tick {
        /// Strictly monotonically increasing.
        tick: Instant,
        /// If true, the demo can be safely seeked to this chunk.
        keyframe: bool,
        /// Indicates that a snapshot has been read.
        /// If not, the previous snapshot is still valid.
        snapshot: bool,
    },
    NetMsg,
}

impl<'a> DemoReader<'a> {
    pub fn new<R: io::Read + io::Seek + 'a>(file: R) -> Result<Self, ReadError> {
        let reader = ddnet::DemoReader::new(file, &mut Ignore)?;
        Ok(Self { reader })
    }

    pub fn next_chunk(&mut self, snap: &mut Snap) -> Result<Option<DemoChunk>, ReadError> {
        loop {
            match self.reader.next_chunk(&mut Ignore)? {
                None => break Ok(None),
                Some(ddnet::Chunk::Tick { tick, keyframe }) => {
                    let snapshot = self.reader.next_chunk_type()? == Some(ChunkType::Snapshot);
                    if snapshot {
                        let Some(ddnet::Chunk::Snapshot(items)) =
                            self.reader.next_chunk(&mut Ignore)?
                        else {
                            todo!()
                        };
                        crate::ddnet::from_ddnet::snap_process_next(snap, items);
                    }
                    break Ok(Some(DemoChunk::Tick {
                        tick: Instant::from_snap_tick(tick),
                        keyframe,
                        snapshot,
                    }));
                }
                Some(ddnet::Chunk::Snapshot(_)) => {
                    break Err(ReadErrorInner::SnapshotWithoutTick.into())
                }
                Some(ddnet::Chunk::Message(_)) => break Ok(Some(DemoChunk::NetMsg)),
                Some(ddnet::Chunk::Invalid) => continue,
            }
        }
    }
    pub fn stream_position(&mut self) -> Result<u64, ReadError> {
        Ok(self.reader.stream_position()?)
    }
    /// Moves the underlying reader to the specified position.
    /// Note that demos hold a lot of state.
    /// Seeking to chunks that are not keyframe ticks will cause errors.
    pub fn seek(&mut self, pos: u64) -> Result<(), ReadError> {
        Ok(self.reader.seek(pos)?)
    }
    /// Seeks forwards to the keyframe that contains the target tick.
    /// This methods returns Some with the tick and stream position, if such a keyframe is found.
    /// It returns None in one of three cases:
    ///  - the keyframe would be before the current stream position
    ///  - the demo ends before the keyframe is found
    ///  - the demo throws an error before the keyframe is found
    /// As long as the method doesn't return an error, the stream position and demo state is unchanged.
    /// If this method returns an error, the stream position is unspecified.
    pub fn next_keyframe_position_for_tick(
        &mut self,
        target_tick: i32,
    ) -> Result<Option<(Instant, u64)>, ReadError> {
        let out = self
            .reader
            .next_keyframe_position_for_tick(target_tick, &mut Ignore)?
            .map(|(tick, position)| (Instant::from_snap_tick(tick), position));
        Ok(out)
    }

    pub fn map_data(&self) -> Option<&[u8]> {
        match self.reader.map_data() {
            &[] => None,
            data => Some(data),
        }
    }

    pub fn map_name(&self) -> &str {
        lossy_str(self.reader.map_name())
    }

    pub fn map_hash(&self) -> DemoMapHash {
        match self.reader.map_sha256() {
            Some(sha) => DemoMapHash::Sha256(sha.0),
            None => DemoMapHash::Crc(self.reader.map_crc()),
        }
    }

    pub fn kind(&self) -> DemoKind {
        match self.reader.kind() {
            libtw2_demo::DemoKind::Client => DemoKind::Client,
            libtw2_demo::DemoKind::Server => DemoKind::Server,
        }
    }

    pub fn net_version(&self) -> &str {
        lossy_str(self.reader.net_version())
    }

    pub fn length(&self) -> i32 {
        self.reader.length()
    }

    pub fn timestamp(&self) -> &str {
        lossy_str(self.reader.timestamp())
    }

    pub fn timeline_markers(&self) -> &[i32] {
        self.reader.timeline_markers()
    }
}

pub enum DemoKind {
    Client,
    Server,
}

pub enum DemoMapHash {
    Crc(u32),
    Sha256([u8; 32]),
}

fn lossy_str(bytes: &[u8]) -> &str {
    match from_utf8(bytes) {
        Ok(s) => s,
        Err(err) => from_utf8(&bytes[..err.valid_up_to()]).unwrap(),
    }
}