use alloc::boxed::Box;
use alloc::vec::Vec;
use crate::error::WireError;
use crate::ids::TrackId;
use crate::range::ByteRange;
use crate::timescale::Timescale;
use crate::wire::FOURCC_LEN;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct MediaTimeRange {
timescale: Timescale,
start: i64,
end: i64,
}
impl MediaTimeRange {
#[must_use]
pub const fn new(timescale: Timescale, start: i64, end: i64) -> Self {
Self {
timescale,
start,
end,
}
}
#[must_use]
pub const fn at(timescale: Timescale, tick: i64) -> Self {
Self::new(timescale, tick, tick)
}
#[must_use]
pub const fn timescale(self) -> Timescale {
self.timescale
}
#[must_use]
pub const fn start(self) -> i64 {
self.start
}
#[must_use]
pub const fn end(self) -> i64 {
self.end
}
}
impl core::fmt::Display for MediaTimeRange {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}..{} @ {} Hz", self.start, self.end, self.timescale)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DamageLocation {
byte_range: Option<ByteRange>,
track: Option<TrackId>,
media_time: Option<MediaTimeRange>,
ordinal: Option<u64>,
}
impl DamageLocation {
#[must_use]
pub const fn new() -> Self {
Self {
byte_range: None,
track: None,
media_time: None,
ordinal: None,
}
}
#[must_use]
pub const fn byte_range(&self) -> Option<ByteRange> {
self.byte_range
}
#[must_use]
pub const fn track(&self) -> Option<TrackId> {
self.track
}
#[must_use]
pub const fn media_time(&self) -> Option<MediaTimeRange> {
self.media_time
}
#[must_use]
pub const fn ordinal(&self) -> Option<u64> {
self.ordinal
}
#[must_use]
pub const fn with_byte_range(mut self, range: ByteRange) -> Self {
self.byte_range = Some(range);
self
}
#[must_use]
pub const fn with_track(mut self, track: TrackId) -> Self {
self.track = Some(track);
self
}
#[must_use]
pub const fn with_media_time(mut self, range: MediaTimeRange) -> Self {
self.media_time = Some(range);
self
}
#[must_use]
pub const fn with_ordinal(mut self, ordinal: u64) -> Self {
self.ordinal = Some(ordinal);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum DamageKind {
MetadataSkipped,
MetadataUninterpreted,
MediaUnitDropped,
MediaUnitDamaged,
Resynchronised,
InputTruncated,
TimelineRepaired,
TrackDropped,
LimitReached,
}
impl DamageKind {
#[must_use]
pub const fn name(&self) -> &'static str {
match self {
DamageKind::MetadataSkipped => "metadata skipped",
DamageKind::MetadataUninterpreted => "metadata uninterpreted",
DamageKind::MediaUnitDropped => "media unit dropped",
DamageKind::MediaUnitDamaged => "media unit damaged",
DamageKind::Resynchronised => "resynchronised",
DamageKind::InputTruncated => "input truncated",
DamageKind::TimelineRepaired => "timeline repaired",
DamageKind::TrackDropped => "track dropped",
DamageKind::LimitReached => "limit reached",
}
}
}
crate::impl_spec_display!(DamageKind);
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Severity {
Informational,
Degraded,
}
impl Severity {
#[must_use]
pub const fn name(&self) -> &'static str {
match self {
Severity::Informational => "informational",
Severity::Degraded => "degraded",
}
}
}
crate::impl_spec_display!(Severity);
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Damage {
kind: DamageKind,
severity: Severity,
location: DamageLocation,
what: &'static str,
fourcc: Option<[u8; FOURCC_LEN]>,
cause: Option<WireError>,
recoverable_bytes: bool,
}
impl Damage {
#[must_use]
pub const fn new(kind: DamageKind, severity: Severity, what: &'static str) -> Self {
Self {
kind,
severity,
location: DamageLocation::new(),
what,
fourcc: None,
cause: None,
recoverable_bytes: false,
}
}
#[must_use]
pub const fn kind(&self) -> DamageKind {
self.kind
}
#[must_use]
pub const fn severity(&self) -> Severity {
self.severity
}
#[must_use]
pub const fn location(&self) -> DamageLocation {
self.location
}
#[must_use]
pub const fn what(&self) -> &'static str {
self.what
}
#[must_use]
pub const fn fourcc(&self) -> Option<[u8; FOURCC_LEN]> {
self.fourcc
}
#[must_use]
pub const fn cause(&self) -> Option<WireError> {
self.cause
}
#[must_use]
pub const fn recoverable_bytes(&self) -> bool {
self.recoverable_bytes
}
#[must_use]
pub const fn with_location(mut self, location: DamageLocation) -> Self {
self.location = location;
self
}
#[must_use]
pub const fn with_byte_range(mut self, range: ByteRange) -> Self {
self.location = self.location.with_byte_range(range);
self
}
#[must_use]
pub const fn with_track(mut self, track: TrackId) -> Self {
self.location = self.location.with_track(track);
self
}
#[must_use]
pub const fn with_media_time(mut self, range: MediaTimeRange) -> Self {
self.location = self.location.with_media_time(range);
self
}
#[must_use]
pub const fn with_ordinal(mut self, ordinal: u64) -> Self {
self.location = self.location.with_ordinal(ordinal);
self
}
#[must_use]
pub const fn with_fourcc(mut self, fourcc: [u8; FOURCC_LEN]) -> Self {
self.fourcc = Some(fourcc);
self
}
#[must_use]
pub const fn with_cause(mut self, cause: WireError) -> Self {
self.cause = Some(cause);
self
}
#[must_use]
pub const fn with_recoverable_bytes(mut self, recoverable: bool) -> Self {
self.recoverable_bytes = recoverable;
self
}
}
impl core::fmt::Display for Damage {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{} {} in {}", self.severity, self.kind, self.what)?;
if let Some(range) = self.location.byte_range() {
write!(f, " at {range}")?;
}
if let Some(track) = self.location.track() {
write!(f, " (track {track})")?;
}
if let Some(time) = self.location.media_time() {
write!(f, " at media time {time}")?;
}
if let Some(ordinal) = self.location.ordinal() {
write!(f, " #{ordinal}")?;
}
if let Some(fourcc) = self.fourcc {
f.write_str(" [")?;
for byte in fourcc {
if byte.is_ascii_graphic() || byte == b' ' {
write!(f, "{}", char::from(byte))?;
} else {
write!(f, "\\x{byte:02X}")?;
}
}
f.write_str("]")?;
}
if let Some(cause) = self.cause {
write!(f, ": {cause}")?;
}
Ok(())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Disposition {
#[default]
Report,
Fail,
}
impl Disposition {
#[must_use]
pub const fn name(&self) -> &'static str {
match self {
Disposition::Report => "report",
Disposition::Fail => "fail",
}
}
}
crate::impl_spec_display!(Disposition);
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DamagePolicy {
informational: Disposition,
degraded: Disposition,
kinds: Vec<(DamageKind, Disposition)>,
}
impl Default for DamagePolicy {
fn default() -> Self {
Self {
informational: Disposition::Report,
degraded: Disposition::Report,
kinds: Vec::new(),
}
}
}
impl DamagePolicy {
#[must_use]
pub fn with_severity(mut self, severity: Severity, disposition: Disposition) -> Self {
match severity {
Severity::Informational => self.informational = disposition,
Severity::Degraded => self.degraded = disposition,
}
self
}
#[must_use]
pub fn fail_on(self, severity: Severity) -> Self {
self.with_severity(severity, Disposition::Fail)
}
#[must_use]
pub fn with_kind(mut self, kind: DamageKind, disposition: Disposition) -> Self {
self.kinds.retain(|(k, _)| *k != kind);
self.kinds.push((kind, disposition));
self
}
#[must_use]
pub fn decision(&self, damage: &Damage) -> Disposition {
if let Some((_, disposition)) = self.kinds.iter().find(|(kind, _)| *kind == damage.kind()) {
return *disposition;
}
match damage.severity() {
Severity::Informational => self.informational,
Severity::Degraded => self.degraded,
}
}
pub fn admit(&self, damage: Damage) -> Result<Damage, DamageError> {
match self.decision(&damage) {
Disposition::Report => Ok(damage),
Disposition::Fail => Err(DamageError::new(damage)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DamageError {
damage: Box<Damage>,
}
impl DamageError {
#[must_use]
pub fn new(damage: Damage) -> Self {
Self {
damage: Box::new(damage),
}
}
#[must_use]
pub fn damage(&self) -> &Damage {
&self.damage
}
#[must_use]
pub fn into_damage(self) -> Damage {
*self.damage
}
}
impl core::fmt::Display for DamageError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "damage policy refused: {}", *self.damage)
}
}
impl core::error::Error for DamageError {}
#[cfg(test)]
mod tests {
extern crate alloc;
use super::*;
use crate::error;
use alloc::string::ToString;
fn dropped() -> Damage {
Damage::new(
DamageKind::MediaUnitDropped,
Severity::Degraded,
"PES packet",
)
.with_byte_range(ByteRange::new(1_880, 188))
.with_track(TrackId::new(3))
.with_media_time(MediaTimeRange::new(crate::timescale!(90_000), 900, 1_800))
.with_ordinal(7)
}
#[test]
fn builders_compose_and_accessors_read_back() {
let damage = dropped()
.with_fourcc(*b"trun")
.with_cause(WireError::InvalidSync(error::InvalidSync {
what: "PES start code",
expected: 1,
found: 9,
}))
.with_recoverable_bytes(true);
assert_eq!(damage.kind(), DamageKind::MediaUnitDropped);
assert_eq!(damage.severity(), Severity::Degraded);
assert_eq!(damage.what(), "PES packet");
assert_eq!(damage.fourcc(), Some(*b"trun"));
assert!(damage.recoverable_bytes());
assert!(damage.cause().is_some());
let location = damage.location();
assert_eq!(location.byte_range(), Some(ByteRange::new(1_880, 188)));
assert_eq!(location.track(), Some(TrackId::new(3)));
assert_eq!(location.ordinal(), Some(7));
let time = location.media_time().expect("media time");
assert_eq!(time.timescale().get(), 90_000);
assert_eq!((time.start(), time.end()), (900, 1_800));
}
#[test]
fn a_location_defaults_to_empty_never_fabricated() {
let damage = Damage::new(DamageKind::MetadataSkipped, Severity::Informational, "tag");
let location = damage.location();
assert_eq!(location.byte_range(), None);
assert_eq!(location.track(), None);
assert_eq!(location.media_time(), None);
assert_eq!(location.ordinal(), None);
assert_eq!(damage.cause(), None);
assert_eq!(damage.fourcc(), None);
assert!(!damage.recoverable_bytes());
}
#[test]
fn a_zero_length_range_marks_absent_bytes() {
let range = ByteRange::new(752, 0);
assert!(range.is_empty());
assert_eq!(range.offset(), 752);
assert_eq!(range.end(), Some(752));
assert_eq!(ByteRange::new(2, 3).end(), Some(5));
}
#[test]
fn the_default_policy_reports_everything() {
let policy = DamagePolicy::default();
for severity in [Severity::Informational, Severity::Degraded] {
let damage = Damage::new(DamageKind::MediaUnitDropped, severity, "unit");
assert_eq!(policy.decision(&damage), Disposition::Report);
assert!(policy.admit(damage).is_ok());
}
}
#[test]
fn failing_on_a_severity_stops_with_the_same_report() {
let policy = DamagePolicy::default().fail_on(Severity::Degraded);
let damage = dropped();
let error = policy.admit(damage.clone()).expect_err("degraded fails");
assert_eq!(error.damage(), &damage);
assert_eq!(error.into_damage(), damage);
}
#[test]
fn a_kind_override_beats_the_severity_setting() {
let policy = DamagePolicy::default()
.fail_on(Severity::Degraded)
.with_kind(DamageKind::MediaUnitDropped, Disposition::Report);
let damage = dropped();
assert_eq!(policy.decision(&damage), Disposition::Report);
assert!(policy.admit(damage).is_ok());
let reverse =
DamagePolicy::default().with_kind(DamageKind::MetadataSkipped, Disposition::Fail);
let quiet = Damage::new(DamageKind::MetadataSkipped, Severity::Informational, "tag");
assert!(reverse.admit(quiet).is_err());
}
#[test]
fn every_shared_error_kind_converts_to_a_cause() {
let cases = [
WireError::from(error::BufferTooShort {
need: 4,
have: 1,
what: "unit",
}),
WireError::from(error::LengthMismatch {
what: "unit",
declared: 9,
actual: 7,
}),
WireError::from(error::InvalidSync {
what: "sync",
expected: 1,
found: 0,
}),
WireError::from(error::CrcMismatch {
what: "section",
computed: 1,
expected: 2,
}),
WireError::from(error::ReservedBits {
field: "r",
expected: 1,
found: 0,
}),
WireError::from(error::InvalidValue {
field: "v",
value: 9,
reason: "out of range",
}),
WireError::from(error::InvalidField {
field: "f",
reason: "missing",
}),
WireError::from(error::UnsupportedVersion {
what: "RTP",
found: 9,
}),
WireError::from(error::FieldOverflow {
field: "l",
value: 9,
max: 1,
}),
];
for cause in cases {
assert!(!cause.to_string().is_empty());
assert!(!cause.name().is_empty());
}
}
#[test]
fn display_names_the_content_the_place_and_the_cause() {
let damage = dropped().with_cause(WireError::InvalidSync(error::InvalidSync {
what: "PES start code",
expected: 1,
found: 9,
}));
let text = damage.to_string();
assert!(text.contains("degraded media unit dropped in PES packet"));
assert!(text.contains("bytes 1880..2068"));
assert!(text.contains("track 3"));
assert!(text.contains("media time 900..1800 @ 90000 Hz"));
assert!(text.contains("invalid PES start code"));
assert_eq!(
DamageError::new(damage).to_string(),
alloc::format!("damage policy refused: {text}")
);
}
#[test]
fn display_carries_the_ordinal_and_the_fourcc() {
let text = dropped()
.with_ordinal(4711)
.with_fourcc(*b"trun")
.to_string();
assert!(text.contains(" #4711"), "{text}");
assert!(text.contains(" [trun]"), "{text}");
let raw = dropped().with_fourcc([0, b'a', b' ', 0xFF]).to_string();
assert!(raw.contains(" [\\x00a \\xFF]"), "{raw}");
}
#[test]
fn kind_severity_and_disposition_labels() {
assert_eq!(DamageKind::MediaUnitDropped.name(), "media unit dropped");
assert_eq!(DamageKind::TrackDropped.to_string(), "track dropped");
assert_eq!(Severity::Degraded.name(), "degraded");
assert_eq!(Severity::Informational.to_string(), "informational");
assert_eq!(Disposition::Report.name(), "report");
assert_eq!(Disposition::Fail.to_string(), "fail");
assert_eq!(Disposition::default(), Disposition::Report);
}
#[test]
fn damage_and_policy_are_cloneable_plain_data() {
let policy = DamagePolicy::default().fail_on(Severity::Degraded);
assert_eq!(policy.clone(), policy);
let damage = dropped();
assert_eq!(damage.clone(), damage);
assert_ne!(
dropped(),
Damage::new(DamageKind::TrackDropped, Severity::Degraded, "track")
);
}
}