moq_mux/container/ts/stats.rs
1//! The counters [`Import::stats`](super::Import::stats) and
2//! [`Export::stats`](super::Export::stats) return, and reporting on them.
3//!
4//! [`Report`] carries them in a media report, as the `mpegts` and `release` sections beside
5//! `transport` and `renditions`. Counters are cumulative and omitted at zero.
6
7use std::collections::{BTreeMap, BTreeSet};
8
9use serde::{Deserialize, Serialize};
10
11fn is_zero(value: &u64) -> bool {
12 *value == 0
13}
14
15/// The sections an MPEG-TS import or export adds to its media report: the `E` of
16/// [`hang::stats::Snapshot`] or [`hang::echo::Snapshot`], flattened beside `transport` and
17/// `renditions`.
18#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
19#[serde(default)]
20#[non_exhaustive]
21pub struct Report {
22 /// What each elementary stream delivered and the transport stream's errors: an import's
23 /// [`Snapshot`], or the rows of an [`Export`]. A passthrough has none.
24 #[serde(skip_serializing_if = "Option::is_none")]
25 pub mpegts: Option<Snapshot>,
26 /// How an export's release clock keeps up with the source. An import has none.
27 #[serde(skip_serializing_if = "Option::is_none")]
28 pub release: Option<Release>,
29}
30
31/// What each demuxed elementary stream delivered, and the audio frame sync it lost or could
32/// not verify, keyed by elementary stream PID; the PSI sections the stream as a whole lost to
33/// corruption; and its TR 101 290 errors.
34///
35/// Take one with [`Import::stats`](super::Import::stats). Every count is cumulative for the
36/// life of the importer, so what an operator alarms on is the rate: a feed that resyncs once an
37/// hour is healthy, one that resyncs every second is losing audio, and one whose access units
38/// stop advancing while the mux keeps flowing has lost that stream.
39///
40/// The fields named for ETSI TR 101 290 (V1.4.1) checks count them at that standard's fixed
41/// limits. They grade the stream as the importer received it, not the wire a receiver sees
42/// downstream. TR 101 290's `PID_error` is covered, more strictly, by each row's `units` and
43/// `quiet`: a dead video path behind a live mux still sends PCR-only packets on its PID, which
44/// a packet count reads as live. `PCR_accuracy_error` is not measured.
45///
46/// [`Export`] carries the same rows for the streams an exporter writes, so one schema reads
47/// both edges.
48#[serde_with::serde_as]
49#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(default, rename_all = "camelCase")]
51#[non_exhaustive]
52pub struct Snapshot {
53 /// One row per PID, ordered by PID: each elementary stream the PMT lists, carried or
54 /// refused, and each PID no table claims that the importer dropped packets on. A dropped
55 /// PID's row names no track, is [`Class::Data`], and counts its packets in
56 /// [`Stream::refused`]. A PID keeps one row for its life: a PMT that claims it, releases it,
57 /// or claims it again moves the row with its counters, and while dropped it names no track.
58 /// Packets before every listed PMT has arrived are acquisition and not counted; so are null
59 /// packets. An import of one program from a multiplex that lists
60 /// others counts no PID no table claims, since another program's PMT may. An SI PID has a
61 /// `.si` row only once it counts [`Stream::unplaced`] sections.
62 // Keys read from strings: a flattened section loses JSON's integer-key parsing.
63 #[serde_as(as = "BTreeMap<serde_with::DisplayFromStr, _>")]
64 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
65 pub streams: BTreeMap<u16, Stream>,
66 /// PAT and PMT sections dropped because their CRC-32 did not match. Each one left the
67 /// table already in force standing, or, before any, delayed the program's start to the
68 /// next good repetition. Counted for the stream rather than per elementary stream, since
69 /// the PSI PIDs have no row of their own. TR 101 290 2.2 `CRC_error`, on the PAT and PMT
70 /// only: the reduced-SI set of its table 5.1b. Captured SI is not CRC-checked.
71 #[serde(skip_serializing_if = "is_zero")]
72 pub crc_error: u64,
73 /// 1.1 `TS_sync_loss`: sync lost after two consecutive corrupt sync bytes on the packet
74 /// grid, and acquired again after five correct ones (ISO/IEC 13818-1 G.1).
75 #[serde(skip_serializing_if = "is_zero")]
76 pub ts_sync_loss: u64,
77 /// 1.2 `Sync_byte_error`: a byte other than 0x47 where the grid expects a sync byte, while
78 /// in sync.
79 #[serde(skip_serializing_if = "is_zero")]
80 pub sync_byte_error: u64,
81 /// 1.3 `PAT_error_2`: each 0.5 s of health clock without a PAT section on PID 0, and each
82 /// packet on PID 0 that is scrambled or starts a section other than a PAT.
83 #[serde(skip_serializing_if = "is_zero")]
84 pub pat_error: u64,
85 /// 1.4 `Continuity_count_error`, on every PID but the null PID: a counter gap, or a third
86 /// copy of a packet. A gap declared by `discontinuity_indicator`, the one duplicate ISO/IEC
87 /// 13818-1 2.4.3.3 permits, and a payload-less packet repeating its counter are not errors.
88 /// A loss of exactly 16 packets leaves the counter in step, and only a byte comparison
89 /// tells a loss of 15 from a duplicate, so the count is a floor.
90 #[serde(skip_serializing_if = "is_zero")]
91 pub continuity_count_error: u64,
92 /// 1.5 `PMT_error_2`: each 0.5 s of health clock without a PMT section on a PMT PID the
93 /// PAT names for the imported program, and each scrambled packet on one.
94 #[serde(skip_serializing_if = "is_zero")]
95 pub pmt_error: u64,
96 /// 2.1 `Transport_error`: packets with `transport_error_indicator` set, on any PID. Such a
97 /// packet counts nothing else.
98 #[serde(skip_serializing_if = "is_zero")]
99 pub transport_error: u64,
100 /// 2.3a `PCR_repetition_error`: consecutive PCR values more than 100 ms apart, or no
101 /// advancing PCR for over 100 ms of health clock, counted once until the PCR advances.
102 /// The health clock follows the PCR and, across a stall, the packets the multiplex carries
103 /// at the constant rate the PCR measured, so it grades the encoder's insertion however the
104 /// input is batched. Without a measured rate it falls back to arrival, read once per input
105 /// chunk, which includes upstream delays. A PCR-bearing signalled discontinuity resets the
106 /// outage, and its PCR value difference is not graded.
107 #[serde(skip_serializing_if = "is_zero")]
108 pub pcr_repetition_error: u64,
109 /// 2.3b `PCR_discontinuity_indicator_error`: consecutive PCR values outside 0 to 100 ms
110 /// apart, backwards included, without `discontinuity_indicator`. On values a run of missing
111 /// PCRs and an unsignalled jump are the same difference, so a forward step over 100 ms
112 /// counts here and as a repetition error both.
113 #[serde(skip_serializing_if = "is_zero")]
114 pub pcr_discontinuity_indicator_error: u64,
115 /// 2.5 `PTS_error`: each 700 ms of health clock without a PTS on an elementary stream
116 /// that has carried one. Verbatim streams are not graded: SCTE-35 and subtitles have no
117 /// cadence to hold.
118 #[serde(skip_serializing_if = "is_zero")]
119 pub pts_error: u64,
120}
121
122impl Snapshot {
123 /// Whether no elementary stream has been registered yet and nothing has been lost.
124 pub fn is_empty(&self) -> bool {
125 self.streams.is_empty() && self.crc_error == 0 && self.health() == [0; 9]
126 }
127}
128
129/// What one elementary stream delivered, lost, or could not verify. See [`Snapshot`].
130#[serde_with::serde_as]
131#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
132#[serde(default, rename_all = "camelCase")]
133#[non_exhaustive]
134pub struct Stream {
135 /// The current or most recent MoQ track suffix for this PID (`.avc3`, `.mp2`, `.ts`, ...),
136 /// or empty for a PID that publishes no track: one dropped, or MPEG-1/2 video refused and
137 /// read only for its clock. At export, the suffix an import of the output would give the PID.
138 #[serde(skip_serializing_if = "String::is_empty")]
139 pub track: String,
140 /// How this PID was classified. See [`Class`].
141 pub class: Class,
142 /// Access units the stream delivered: frames published for decoded media, whole PES or
143 /// sections carried verbatim, and PES read on MPEG-1/2 video. At export, the PES or
144 /// sections written for each frame.
145 #[serde(skip_serializing_if = "is_zero")]
146 pub units: u64,
147 /// Transport time since the stream last delivered an access unit, or since the PMT
148 /// declared it, measured on the program clock (PCR): the one read at import, the one
149 /// written at export. `None` until the first PCR. Whole milliseconds in a report.
150 ///
151 /// No threshold applies: a sparse stream such as SCTE-35 is legitimately quiet for
152 /// seconds, so how long is too long is for whoever alarms to decide.
153 #[serde_as(as = "Option<serde_with::DurationMilliSeconds<u64>>")]
154 #[serde(skip_serializing_if = "Option::is_none")]
155 pub quiet: Option<std::time::Duration>,
156 /// Completed resyncs: the stream lost frame sync and locked onto a confirmed frame
157 /// again. Each one is a gap in the audio.
158 #[serde(skip_serializing_if = "is_zero")]
159 pub resyncs: u64,
160 /// Bytes thrown away scanning for sync, across every resync and any scan still in
161 /// progress.
162 #[serde(skip_serializing_if = "is_zero")]
163 pub discarded: u64,
164 /// Frames published that nothing vouched for: the offset came from a scan, or the bytes
165 /// were joined onto a tail carried across a PES boundary, and no successor frame could
166 /// confirm it. That substitutes audio rather than leaving a gap, which is why it is
167 /// counted separately from a resync.
168 #[serde(skip_serializing_if = "is_zero")]
169 pub unconfirmed: u64,
170 /// Damaged packets or PES refused whole on this PID. Export stays zero.
171 #[serde(skip_serializing_if = "is_zero")]
172 pub damaged: u64,
173 /// Whole PES or sections, SI included, dropped because the program clock could not place
174 /// them: before the first PCR, after the last with no interval to extrapolate from, or
175 /// before the broadcast clock's zero. Any PES lands before that zero while its stream is
176 /// still behind a wrap the import's first PTS already crossed. Export stays zero.
177 #[serde(skip_serializing_if = "is_zero")]
178 pub unplaced: u64,
179 /// What this PID lost to a route the import does not carry. Once for each time its stream
180 /// was refused: a listed stream the import cannot carry (an ambiguous 0x86 without a CUEI
181 /// registration, an Opus configuration it cannot map, any undecoded stream without the
182 /// `mpegts` catalog section or in a program with no PCR to place it by), or a whole-PES
183 /// stream with a clock field only the PTS and DTS of are rebased (ESCR, a
184 /// `pack_header_field`, a TREF), an unbounded non-video PES, or a header export refuses,
185 /// whose track ends and leaves the catalog. Once for each TS-scrambled packet on a carried
186 /// stream, which the raw lane could carry, and each PES-scrambled PES on one; the stream
187 /// resumes once it is clear. And once for
188 /// each packet on a PID no table claims ([`Snapshot::streams`]). Export stays zero.
189 #[serde(skip_serializing_if = "is_zero")]
190 pub refused: u64,
191 /// This PID's share of [`Snapshot::continuity_count_error`].
192 #[serde(skip_serializing_if = "is_zero")]
193 pub continuity_count_error: u64,
194 /// This PID's share of [`Snapshot::transport_error`].
195 #[serde(skip_serializing_if = "is_zero")]
196 pub transport_error: u64,
197 /// This PID's share of [`Snapshot::pts_error`].
198 #[serde(skip_serializing_if = "is_zero")]
199 pub pts_error: u64,
200}
201
202impl Stream {
203 pub(super) fn new(track: &str, class: Class) -> Self {
204 Self {
205 track: track.to_string(),
206 class,
207 ..Default::default()
208 }
209 }
210
211 /// Add a newer route's frame-sync counters while naming the route that is active now.
212 /// Delivery and damage are kept per PID rather than per route, so they need no merging.
213 pub(super) fn merge(&mut self, current: &Self) {
214 self.track.clone_from(¤t.track);
215 self.class = current.class;
216 self.resyncs += current.resyncs;
217 self.discarded += current.discarded;
218 self.unconfirmed += current.unconfirmed;
219 }
220
221 /// Set each delivery, damage and frame-sync count to `f` of it and `other`'s, keeping this
222 /// row's track, class and quiet. The TR 101 290 shares are left alone: they are written
223 /// from the merged checks.
224 pub(super) fn combine(&mut self, other: &Self, f: impl Fn(u64, u64) -> u64) {
225 for (ours, theirs) in [
226 (&mut self.units, other.units),
227 (&mut self.resyncs, other.resyncs),
228 (&mut self.discarded, other.discarded),
229 (&mut self.unconfirmed, other.unconfirmed),
230 (&mut self.damaged, other.damaged),
231 (&mut self.unplaced, other.unplaced),
232 (&mut self.refused, other.refused),
233 ] {
234 *ours = f(*ours, theirs);
235 }
236 }
237}
238
239/// Audio, video, or other data, as import or export already resolved the PID.
240///
241/// Not the PMT `stream_type`. `0x86` is DTS audio or, with a CUEI registration, an SCTE-35
242/// section, and those take different routes. The stopped-stream log grades audio and video
243/// only; a sparse data PID stays counted.
244#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
245#[serde(rename_all = "lowercase")]
246pub enum Class {
247 /// Continuous audio.
248 Audio = 1,
249 /// Continuous video, including MPEG-1/2 video carried whole or read only for its clock.
250 Video = 2,
251 /// Undecoded or sparse data (SCTE-35, ID3, private sections, private PES), a PCR PID that
252 /// carries no elementary stream, or a dropped PID. A quiet second is not a stall. A class a later
253 /// version adds reads as data. It must stay last for `#[serde(other)]`; the explicit
254 /// discriminants keep every variant's `as` value.
255 #[default]
256 #[serde(other)]
257 Data = 0,
258}
259
260impl Class {
261 /// Audio and video have a cadence. Data does not, so a quiet second is not a stall.
262 pub(super) fn graded(self) -> bool {
263 matches!(self, Self::Audio | Self::Video)
264 }
265}
266
267/// What each elementary stream an [`Export`](super::Export) writes has delivered, keyed by
268/// PID, and how the release clock is keeping up with the source.
269///
270/// Take one with [`Export::stats`](super::Export::stats). Its rows are an import's, but only
271/// `units` and `quiet` move: the exporter builds every frame header itself, so it has no frame
272/// sync to lose and it runs no TR 101 290 checks. [`Log`] still grades an audio or video row
273/// whose `units` stay still.
274#[derive(Clone, Debug, Default, PartialEq)]
275#[non_exhaustive]
276pub struct Export {
277 /// One row per elementary stream PID the exporter writes, ordered by PID.
278 pub streams: BTreeMap<u16, Stream>,
279 /// How the release clock is keeping up with the source.
280 pub release: Release,
281}
282
283/// How an export keeps up with the source: the frames it drops, trims, and never receives,
284/// and how its release clock tracks the source's. What [`Export::stats`](super::Export::stats)
285/// reports beside its rows, and [`Release::stats`](super::Release::stats) on its own.
286#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
287#[serde(default, rename_all = "camelCase")]
288#[non_exhaustive]
289pub struct Release {
290 /// Frames dropped after their stream's first went out: for arriving after their deadline,
291 /// for falling due before a new timeline's clock was acquired, and the frames a video track
292 /// then dropped waiting for its next keyframe or leading the keyframe it resumed at, late
293 /// or after a hole upstream once the output held frames ahead of the hole.
294 #[serde(skip_serializing_if = "is_zero")]
295 pub dropped: u64,
296 /// Frames dropped before their stream's first went out, so the output starts on a whole
297 /// group led by the video keyframe: what a joiner is handed older than the delay, a start
298 /// group cut short upstream, the first keyframe's leading pictures, and what precedes the
299 /// first keyframe or the codec config.
300 /// Nothing is missing from the output for these.
301 #[serde(skip_serializing_if = "is_zero")]
302 pub trimmed: u64,
303 /// Times a source skipped media it will never deliver: a group lost or expired upstream,
304 /// or a resubscription. A declared break is not one. Each is logged with the span it
305 /// skipped.
306 #[serde(skip_serializing_if = "is_zero")]
307 pub gaps: u64,
308 /// The least time any frame arrived before its deadline over the last whole second, in
309 /// milliseconds: how much more latency the path could take before frames drop. Negative
310 /// when a frame missed its deadline. `None` until a second has passed, and without a delay.
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub margin: Option<i64>,
313 /// How far the output clock sits from the source's plus the delay, in milliseconds, as last
314 /// measured: positive holds frames longer than the delay, negative shorter. The clock pulls
315 /// it shut over ten minutes. `None` until there is a measurement.
316 #[serde(skip_serializing_if = "Option::is_none")]
317 pub offset: Option<i64>,
318 /// How fast the source's clock runs against ours, in parts per million (positive runs
319 /// fast), as last measured. `None` until there is a measurement.
320 #[serde(skip_serializing_if = "Option::is_none")]
321 pub drift: Option<f64>,
322 /// How many measurements found the source's clock further off ours than the 30 ppm an
323 /// MPEG-TS system clock may be (ISO/IEC 13818-1 2.4.2.1), which the output cannot follow.
324 #[serde(skip_serializing_if = "is_zero")]
325 pub out_of_tolerance: u64,
326}
327
328impl Release {
329 pub(crate) fn of<K: Ord + Clone, T>(jitter: &crate::jitter::Buffer<K, T>) -> Self {
330 let jitter = jitter.reporting();
331 let millis = |seconds: f64| (seconds * 1e3).round() as i64;
332 Self {
333 dropped: jitter.dropped(),
334 trimmed: jitter.trimmed(),
335 gaps: 0,
336 margin: jitter.margin().map(millis),
337 offset: jitter.offset().map(millis),
338 drift: jitter.drift().map(|drift| drift * 1e6),
339 out_of_tolerance: jitter.out_of_tolerance(),
340 }
341 }
342}
343
344/// An export's rows with every stream-wide counter zero, so one [`Log`] reads either edge.
345impl From<Export> for Snapshot {
346 fn from(export: Export) -> Self {
347 Self {
348 streams: export.streams,
349 ..Default::default()
350 }
351 }
352}
353
354/// Logs what moved in an importer's [`Snapshot`], or an exporter's [`Export`] converted into
355/// one, from one sample to the next, so every front door that runs one reports the same lines.
356///
357/// Feed it a snapshot every [`INTERVAL`](Self::INTERVAL) of wall time. The caller owns the
358/// timer, since what counts as "now" differs between a CLI, a server, and a test.
359#[derive(Default)]
360pub struct Log {
361 previous: Option<Snapshot>,
362 /// Streams already reported quiet, so a silence is logged when it starts and not again
363 /// until the stream has delivered.
364 quiet: BTreeSet<u16>,
365}
366
367impl Log {
368 /// How often to [`sample`](Self::sample).
369 ///
370 /// Long enough that every continuous stream delivers many access units in between, so a
371 /// count that did not move is a stream that stopped rather than one between frames.
372 pub const INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
373
374 /// Compare a snapshot taken [`INTERVAL`](Self::INTERVAL) after the last.
375 ///
376 /// Logs an audio or video stream whose access units did not advance since the last
377 /// sample, once per silence. Sparse data (SCTE-35, ID3, other verbatim PIDs) is counted
378 /// and not graded. Also logs any stream whose loss counters moved, and PSI sections
379 /// dropped since.
380 pub fn sample(&mut self, latest: Snapshot) {
381 self.sync(&latest);
382 for (pid, stream) in &latest.streams {
383 let previous = self.previous.as_ref().and_then(|previous| previous.streams.get(pid));
384 if previous.is_none_or(|previous| previous.units != stream.units) {
385 self.quiet.remove(pid);
386 } else if stream.class.graded() && self.quiet.insert(*pid) {
387 tracing::info!(
388 pid = *pid,
389 track = stream.track,
390 units = stream.units,
391 quiet = ?stream.quiet,
392 "elementary stream stopped delivering access units"
393 );
394 }
395 }
396 self.previous = Some(latest);
397 }
398
399 /// Compare the snapshot taken after [`Import::finish`](super::Import::finish).
400 ///
401 /// It covers less than an interval, so only the losses are compared: the drain at end of
402 /// input can publish a frame nothing vouched for.
403 pub fn finish(&self, latest: &Snapshot) {
404 self.sync(latest);
405 }
406
407 /// Report the streams whose damage or frame-sync counters moved, one line each, the PSI
408 /// sections dropped for a bad CRC if that count moved, and the TR 101 290 counters if any
409 /// moved.
410 ///
411 /// The importer already warns on each individual resync and dropped section; this is the
412 /// running total, which is what an operator turns into a rate.
413 fn sync(&self, latest: &Snapshot) {
414 if self.previous.as_ref().map_or(0, |previous| previous.crc_error) != latest.crc_error {
415 tracing::info!(
416 crc_error = latest.crc_error,
417 "PAT or PMT sections dropped for a bad CRC"
418 );
419 }
420 if self.previous.as_ref().map_or([0; 9], Snapshot::health) != latest.health() {
421 tracing::info!(
422 ts_sync_loss = latest.ts_sync_loss,
423 sync_byte_error = latest.sync_byte_error,
424 pat_error = latest.pat_error,
425 continuity_count_error = latest.continuity_count_error,
426 pmt_error = latest.pmt_error,
427 transport_error = latest.transport_error,
428 crc_error = latest.crc_error,
429 pcr_repetition_error = latest.pcr_repetition_error,
430 pcr_discontinuity_indicator_error = latest.pcr_discontinuity_indicator_error,
431 pts_error = latest.pts_error,
432 "TR 101 290 errors in the received transport stream"
433 );
434 }
435 let lost = |stream: &Stream| (stream.resyncs, stream.discarded, stream.unconfirmed);
436 for (pid, stream) in &latest.streams {
437 let previous = self.previous.as_ref().and_then(|previous| previous.streams.get(pid));
438 if previous.map_or(0, |previous| previous.damaged) != stream.damaged {
439 tracing::info!(
440 pid = *pid,
441 track = stream.track,
442 damaged = stream.damaged,
443 "damaged TS units refused"
444 );
445 }
446 let dropped = |stream: &Stream| (stream.unplaced, stream.refused);
447 if previous.map_or((0, 0), dropped) != dropped(stream) {
448 tracing::info!(
449 pid = *pid,
450 track = stream.track,
451 unplaced = stream.unplaced,
452 refused = stream.refused,
453 "private PES not carried"
454 );
455 }
456 if previous.map_or((0, 0, 0), lost) == lost(stream) {
457 continue;
458 }
459 tracing::info!(
460 pid = *pid,
461 track = stream.track,
462 resyncs = stream.resyncs,
463 discarded = stream.discarded,
464 unconfirmed = stream.unconfirmed,
465 "audio frame sync lost"
466 );
467 }
468 }
469}
470
471#[cfg(test)]
472mod test {
473 use super::*;
474
475 /// A class a later version adds reads as data.
476 #[test]
477 fn an_unknown_class_reads_as_data() {
478 let class: Class = serde_json::from_str(r#""subtitle""#).unwrap();
479 assert_eq!(class, Class::Data);
480 }
481
482 /// A stream whose count stops across a sample is logged once, with its silence, and again
483 /// only after it has delivered in between; a stream that keeps counting never is, and
484 /// neither reports frame sync it never lost.
485 #[test]
486 #[tracing_test::traced_test]
487 fn reports_a_stream_that_stopped() {
488 const VIDEO: u16 = 0x100;
489 const AUDIO: u16 = 0x101;
490 let sample = |video: u64, audio: u64| {
491 let mut stats = Snapshot::default();
492 for (pid, track, class, units) in [
493 (VIDEO, ".avc3", Class::Video, video),
494 (AUDIO, ".mp2", Class::Audio, audio),
495 ] {
496 let stream = Stream {
497 track: track.to_string(),
498 class,
499 units,
500 quiet: Some(std::time::Duration::from_millis(40)),
501 ..Default::default()
502 };
503 stats.streams.insert(pid, stream);
504 }
505 stats
506 };
507
508 let mut log = Log::default();
509 for (video, audio) in [(10, 10), (10, 20), (10, 30), (11, 40), (11, 50)] {
510 log.sample(sample(video, audio));
511 }
512
513 logs_assert(|lines: &[&str]| {
514 let stopped: Vec<_> = lines
515 .iter()
516 .filter(|line| line.contains("stopped delivering access units"))
517 .collect();
518 match stopped.as_slice() {
519 [first, second] if [first, second].iter().all(|line| line.contains("pid=256")) => Ok(()),
520 _ => Err(format!("expected two lines for the video PID, got {stopped:?}")),
521 }
522 });
523 assert!(!logs_contain("audio frame sync lost"), "nothing lost frame sync");
524 }
525
526 /// A CUEI-marked 0x86 section is sparse data. A second without a section is not a stall,
527 /// even beside a video PID whose access units stopped.
528 #[test]
529 #[tracing_test::traced_test]
530 fn sparse_data_pid_beside_a_stalled_video_is_not_logged() {
531 const VIDEO: u16 = 0x100;
532 const CUE: u16 = 0x21;
533 let sample = |video: u64, cue: u64| {
534 let mut stats = Snapshot::default();
535 stats.streams.insert(
536 VIDEO,
537 Stream {
538 track: ".avc3".to_string(),
539 class: Class::Video,
540 units: video,
541 quiet: Some(std::time::Duration::from_secs(1)),
542 ..Default::default()
543 },
544 );
545 stats.streams.insert(
546 CUE,
547 Stream {
548 track: ".ts".to_string(),
549 class: Class::Data,
550 units: cue,
551 quiet: Some(std::time::Duration::from_secs(1)),
552 ..Default::default()
553 },
554 );
555 stats
556 };
557
558 let mut log = Log::default();
559 log.sample(sample(4, 1));
560 log.sample(sample(4, 1));
561 log.sample(sample(4, 2));
562 log.sample(sample(4, 2));
563
564 logs_assert(|lines: &[&str]| {
565 let stopped: Vec<_> = lines
566 .iter()
567 .filter(|line| line.contains("stopped delivering access units"))
568 .collect();
569 match stopped.as_slice() {
570 [line] if line.contains("pid=256") && !line.contains("pid=33") => Ok(()),
571 _ => Err(format!("expected only the stalled video PID, got {stopped:?}")),
572 }
573 });
574 }
575
576 /// A resync is reported on the sample that saw it, and the end of input still reports one
577 /// the last partial interval found.
578 #[test]
579 #[tracing_test::traced_test]
580 fn reports_frame_sync_lost_at_the_end() {
581 let sample = |resyncs: u64, units: u64| {
582 let stream = Stream {
583 track: ".mp2".to_string(),
584 class: Class::Audio,
585 units,
586 resyncs,
587 ..Default::default()
588 };
589 let mut stats = Snapshot::default();
590 stats.streams.insert(0x101, stream);
591 stats
592 };
593
594 let mut log = Log::default();
595 log.sample(sample(0, 10));
596 log.sample(sample(0, 20));
597 log.finish(&sample(1, 21));
598
599 logs_assert(|lines: &[&str]| {
600 match lines
601 .iter()
602 .filter(|line| line.contains("audio frame sync lost"))
603 .count()
604 {
605 1 => Ok(()),
606 n => Err(format!("expected one frame-sync line, got {n}")),
607 }
608 });
609 assert!(!logs_contain("stopped delivering"), "the stream kept counting");
610 }
611
612 /// Dropped PSI sections are reported when the count moves, with the running total, and
613 /// not again while it holds.
614 #[test]
615 #[tracing_test::traced_test]
616 fn reports_crc_errors_when_they_move() {
617 let sample = |crc_error: u64| Snapshot {
618 crc_error,
619 ..Default::default()
620 };
621
622 let mut log = Log::default();
623 log.sample(sample(0));
624 log.sample(sample(2));
625 log.sample(sample(2));
626 log.finish(&sample(3));
627
628 logs_assert(|lines: &[&str]| {
629 let dropped: Vec<_> = lines.iter().filter(|line| line.contains("bad CRC")).collect();
630 match dropped.as_slice() {
631 [first, second] if first.contains("crc_error=2") && second.contains("crc_error=3") => Ok(()),
632 _ => Err(format!("expected one line per move, got {dropped:?}")),
633 }
634 });
635 assert!(!logs_contain("TR 101 290"), "a CRC error is reported on its own line");
636 }
637
638 /// The TR 101 290 counters are reported together, with their totals, when any of them
639 /// moves, and not while they hold.
640 #[test]
641 #[tracing_test::traced_test]
642 fn reports_tr_101_290_errors_when_they_move() {
643 let sample = |transport_error: u64, pcr_repetition_error: u64| Snapshot {
644 transport_error,
645 pcr_repetition_error,
646 ..Default::default()
647 };
648
649 let mut log = Log::default();
650 log.sample(sample(0, 0));
651 log.sample(sample(1, 0));
652 log.sample(sample(1, 0));
653 log.sample(sample(1, 2));
654 log.finish(&sample(1, 2));
655
656 logs_assert(|lines: &[&str]| {
657 let moved: Vec<_> = lines.iter().filter(|line| line.contains("TR 101 290")).collect();
658 match moved.as_slice() {
659 [first, second]
660 if [first, second].iter().all(|line| line.contains(" transport_error=1"))
661 && first.contains(" pcr_repetition_error=0")
662 && second.contains(" pcr_repetition_error=2") =>
663 {
664 Ok(())
665 }
666 _ => Err(format!("expected one line per move, got {moved:?}")),
667 }
668 });
669 }
670
671 /// A report carries the counters beside `transport` and `renditions`, camelCase, keyed by
672 /// PID, `quiet` in milliseconds, and zero counters omitted; it reads back whole, and a class
673 /// a later version adds reads as data.
674 #[test]
675 fn a_report_flattens_beside_the_media_counters() {
676 let mut mpegts = Snapshot {
677 continuity_count_error: 2,
678 ..Default::default()
679 };
680 mpegts.streams.insert(
681 256,
682 Stream {
683 track: ".avc3".to_string(),
684 class: Class::Video,
685 units: 120,
686 quiet: Some(std::time::Duration::from_micros(40_400)),
687 continuity_count_error: 2,
688 ..Default::default()
689 },
690 );
691 let release = Release {
692 margin: Some(-12),
693 offset: Some(3),
694 drift: Some(1.5),
695 ..Default::default()
696 };
697 let mut snapshot = hang::stats::Snapshot::<Report>::default();
698 snapshot.ext.mpegts = Some(mpegts);
699 snapshot.ext.release = Some(release);
700
701 let json = serde_json::to_value(&snapshot).unwrap();
702 assert_eq!(
703 json,
704 serde_json::json!({
705 "mpegts": {
706 "streams": {
707 "256": { "track": ".avc3", "class": "video", "units": 120, "quiet": 40, "continuityCountError": 2 }
708 },
709 "continuityCountError": 2
710 },
711 "release": { "margin": -12, "offset": 3, "drift": 1.5 }
712 })
713 );
714 let mut read: hang::stats::Snapshot<Report> = serde_json::from_value(json).unwrap();
715 let quiet = &mut read.ext.mpegts.as_mut().unwrap().streams.get_mut(&256).unwrap().quiet;
716 assert_eq!(*quiet, Some(std::time::Duration::from_millis(40)));
717 *quiet = snapshot.ext.mpegts.as_ref().unwrap().streams[&256].quiet;
718 assert_eq!(read, snapshot);
719
720 let row: Stream = serde_json::from_value(serde_json::json!({ "class": "subtitle", "later": 1 })).unwrap();
721 assert_eq!(row.class, Class::Data);
722 }
723
724 /// Damage is reported per PID when its cumulative count moves, including the final sample.
725 #[test]
726 #[tracing_test::traced_test]
727 fn reports_damaged_units_when_they_move() {
728 let sample = |damaged| {
729 let mut stats = Snapshot::default();
730 stats.streams.insert(
731 256,
732 Stream {
733 track: ".avc3".to_string(),
734 damaged,
735 ..Default::default()
736 },
737 );
738 stats.streams.insert(
739 257,
740 Stream {
741 track: ".mp2".to_string(),
742 ..Default::default()
743 },
744 );
745 stats
746 };
747 let mut log = Log::default();
748 log.sample(sample(0));
749 log.sample(sample(1));
750 log.sample(sample(1));
751 log.finish(&sample(2));
752 logs_assert(|lines: &[&str]| {
753 let refused: Vec<_> = lines
754 .iter()
755 .filter(|line| line.contains("damaged TS units refused"))
756 .collect();
757 match refused.as_slice() {
758 [first, second]
759 if first.contains("pid=256")
760 && first.contains("damaged=1")
761 && second.contains("pid=256")
762 && second.contains("damaged=2") =>
763 {
764 Ok(())
765 }
766 _ => Err(format!("expected damage increases on the video PID, got {refused:?}")),
767 }
768 });
769 }
770}