use bytes::Bytes;
use core::fmt;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Clone, Default)]
pub struct DataTrackFrame {
pub(crate) payload: Bytes,
pub(crate) user_timestamp: Option<u64>,
}
impl DataTrackFrame {
pub fn payload(&self) -> Bytes {
self.payload.clone() }
pub fn user_timestamp(&self) -> Option<u64> {
self.user_timestamp
}
pub fn duration_since_timestamp(&self) -> Option<Duration> {
let ts = self.user_timestamp?;
let ts_time = UNIX_EPOCH.checked_add(Duration::from_millis(ts))?;
SystemTime::now()
.duration_since(ts_time)
.inspect_err(|err| log::error!("Failed to calculate duration: {err}"))
.ok()
}
}
impl DataTrackFrame {
pub fn new(payload: impl Into<Bytes>) -> Self {
Self { payload: payload.into(), ..Default::default() }
}
pub fn with_user_timestamp(mut self, value: u64) -> Self {
self.user_timestamp = Some(value);
self
}
pub fn with_user_timestamp_now(mut self) -> Self {
let timestamp = SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.inspect_err(|err| log::error!("Failed to get system time: {err}"))
.ok();
self.user_timestamp = timestamp;
self
}
}
impl fmt::Debug for DataTrackFrame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DataTrackFrame")
.field("payload_len", &self.payload.len())
.field("user_timestamp", &self.user_timestamp)
.finish()
}
}
impl From<Bytes> for DataTrackFrame {
fn from(bytes: Bytes) -> Self {
Self { payload: bytes, ..Default::default() }
}
}
impl From<&'static [u8]> for DataTrackFrame {
fn from(slice: &'static [u8]) -> Self {
Self { payload: slice.into(), ..Default::default() }
}
}
impl From<Vec<u8>> for DataTrackFrame {
fn from(vec: Vec<u8>) -> Self {
Self { payload: vec.into(), ..Default::default() }
}
}
impl From<Box<[u8]>> for DataTrackFrame {
fn from(slice: Box<[u8]>) -> Self {
Self { payload: slice.into(), ..Default::default() }
}
}