Skip to main content

srt_runtime/
damage.rs

1//! Turning the delivery engine's drops into the workspace's one damage report.
2//!
3//! SRT delivers payloads, not a byte stream with positions, so a loss is
4//! reported against the packet sequence the reader counts
5//! ([`DamageLocation::ordinal`](broadcast_core::damage::DamageLocation))
6//! and, when the scheduler knew it, the play time the packet was due at
7//! ([`MediaTimeRange`]).
8//!
9//! # Coalescing rule
10//!
11//! One report per contiguous run of dropped sequence numbers that share a
12//! reason. A run ends when a sequence number is delivered, when the next
13//! dropped number is not the successor of the previous one, or when the
14//! reason changes. A stream that loses every other packet therefore reports
15//! once per single-packet run, and one that loses a run of 200 consecutive
16//! packets reports that run once — never one report per packet.
17
18use alloc::vec::Vec;
19
20use broadcast_core::damage::{Damage, DamageKind, MediaTimeRange, Severity};
21use broadcast_core::timescale::Timescale;
22
23use crate::arq::seq;
24use crate::tsbpd::{DropReason, DroppedPacket};
25
26/// The time base of an SRT timestamp: the wire carries microseconds
27/// (`draft-sharabayko-srt-01` §3.1).
28pub const DAMAGE_TIMESCALE: Timescale = broadcast_core::timescale!(1_000_000);
29
30/// The structure name a report about a dropped data packet uses, in SRT's own
31/// terms.
32#[must_use]
33pub const fn what(reason: DropReason) -> &'static str {
34    match reason {
35        DropReason::TooLate => "SRT data packet (too late)",
36        DropReason::GapSkipped => "SRT data packet (unrecoverable gap)",
37        DropReason::DropRequested => "SRT data packet (peer drop request)",
38    }
39}
40
41/// One report per contiguous run of `dropped` that shares a reason.
42///
43/// `dropped` is in the order the scheduler reported it (increasing sequence
44/// numbers within a release pass).
45#[must_use]
46pub fn reports(dropped: &[DroppedPacket]) -> Vec<Damage> {
47    let mut out = Vec::new();
48    let mut run: Option<(DroppedPacket, DroppedPacket)> = None;
49    for &packet in dropped {
50        match run {
51            Some((first, last))
52                if first.reason == packet.reason
53                    && packet.seq_number == seq::seq_next(last.seq_number) =>
54            {
55                run = Some((first, packet));
56            }
57            Some((first, last)) => {
58                out.push(report(first, last));
59                run = Some((packet, packet));
60            }
61            None => run = Some((packet, packet)),
62        }
63    }
64    if let Some((first, last)) = run {
65        out.push(report(first, last));
66    }
67    out
68}
69
70/// One run's report: the first sequence number as the ordinal, and the play
71/// time span the run was due at when the scheduler recorded it.
72fn report(first: DroppedPacket, last: DroppedPacket) -> Damage {
73    let mut damage = Damage::new(
74        DamageKind::MediaUnitDropped,
75        Severity::Degraded,
76        what(first.reason),
77    )
78    .with_ordinal(u64::from(first.seq_number));
79    if let Some(start) = first.due_us {
80        let end = last.due_us.unwrap_or(start);
81        damage = damage.with_media_time(MediaTimeRange::new(
82            DAMAGE_TIMESCALE,
83            i64::try_from(start).unwrap_or(i64::MAX),
84            i64::try_from(end).unwrap_or(i64::MAX),
85        ));
86    }
87    damage
88}
89
90/// A report for content this adapter dropped before the scheduler saw it:
91/// a datagram over the configured size, an inbound datagram the bounded
92/// channel had no room for, or a payload the application read too slowly.
93///
94/// Coalesced by cause: the caller emits the first occurrence of each cause
95/// once, `count` times the channel capacity, rather than one report per
96/// datagram (a flood of them would say nothing more).
97#[must_use]
98pub fn dropped_before_delivery(what: &'static str, count: u64) -> Damage {
99    Damage::new(DamageKind::MediaUnitDropped, Severity::Degraded, what).with_ordinal(count)
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn p(seq_number: u32, reason: DropReason, due_us: Option<u64>) -> DroppedPacket {
107        DroppedPacket::new(seq_number, reason, due_us)
108    }
109
110    #[test]
111    fn one_run_is_one_report() {
112        let dropped = [
113            p(10, DropReason::GapSkipped, None),
114            p(11, DropReason::GapSkipped, None),
115            p(12, DropReason::GapSkipped, None),
116        ];
117        let reports = reports(&dropped);
118        assert_eq!(reports.len(), 1);
119        assert_eq!(reports[0].location().ordinal(), Some(10));
120        assert_eq!(reports[0].kind(), DamageKind::MediaUnitDropped);
121        assert_eq!(reports[0].severity(), Severity::Degraded);
122        assert_eq!(reports[0].what(), what(DropReason::GapSkipped));
123    }
124
125    #[test]
126    fn a_non_adjacent_drop_starts_a_new_report() {
127        let dropped = [
128            p(10, DropReason::TooLate, None),
129            p(11, DropReason::TooLate, None),
130            p(20, DropReason::TooLate, None),
131        ];
132        let reports = reports(&dropped);
133        assert_eq!(reports.len(), 2);
134        assert_eq!(reports[0].location().ordinal(), Some(10));
135        assert_eq!(reports[1].location().ordinal(), Some(20));
136    }
137
138    #[test]
139    fn a_reason_change_starts_a_new_report() {
140        let dropped = [
141            p(10, DropReason::TooLate, None),
142            p(11, DropReason::DropRequested, None),
143        ];
144        let reports = reports(&dropped);
145        assert_eq!(reports.len(), 2);
146        assert_eq!(reports[1].what(), what(DropReason::DropRequested));
147    }
148
149    #[test]
150    fn the_run_carries_its_play_time_span_when_known() {
151        let dropped = [
152            p(4, DropReason::TooLate, Some(1_000)),
153            p(5, DropReason::TooLate, Some(3_000)),
154        ];
155        let reports = reports(&dropped);
156        assert_eq!(reports.len(), 1);
157        let time = reports[0].location().media_time().expect("media time");
158        assert_eq!(time.timescale().get(), 1_000_000);
159        assert_eq!((time.start(), time.end()), (1_000, 3_000));
160    }
161
162    #[test]
163    fn a_wrapped_sequence_run_stays_one_report() {
164        let dropped = [
165            p(u32::MAX, DropReason::GapSkipped, None),
166            p(0, DropReason::GapSkipped, None),
167        ];
168        assert_eq!(reports(&dropped).len(), 1);
169    }
170
171    #[test]
172    fn no_drops_no_reports() {
173        assert!(reports(&[]).is_empty());
174    }
175}