broadcast-core 0.1.0

Frozen wire-format contract for the rust-broadcast crates: symmetric Parse/Serialize traits, checked field-width helpers, MSB-first bit I/O, reserved-bit fields, media timescales, the shared error kinds and the CENC scheme identity. no_std + alloc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! A report of content a reader skipped, and the caller's policy for it.
//!
//! Best-effort reading is the workspace rule: a reader parses as well as it
//! can and continues, skips broken metadata and broken frames, and refuses
//! only when what is missing makes playback impossible. Whenever it skips
//! something it says so through this module, so the player can choose to log,
//! warn, fail or repair — the library never decides what a skip means.
//!
//! Three pieces:
//!
//! - [`Damage`] — plain data: what happened to the content ([`DamageKind`]),
//!   how bad it is ([`Severity`]), where in the input it happened
//!   ([`DamageLocation`]), which structure it was ([`Damage::what`]), the
//!   typed cause where a shared error kind applies ([`WireError`]), and
//!   whether the skipped bytes are still available verbatim.
//! - [`DamagePolicy`] — the caller's decision per severity and, optionally,
//!   per kind: [`Disposition::Report`] (the default for everything: continue
//!   and report) or [`Disposition::Fail`] (stop with a [`DamageError`]
//!   carrying the same report). There is no silent setting; a report is
//!   always produced.
//! - [`DamagePolicy::admit`] — the one helper a reader calls on a report: it
//!   hands the report back to publish, or the typed error to stop with.
//!
//! A [`Damage`] is content the reader left out or altered and continued past;
//! an `Err` is a failure after which the reader cannot continue, or a caller
//! limit reached (a [`LimitExceeded`](crate::error::LimitExceeded) is always
//! an error, never a report). Strict mode is [`DamagePolicy::fail_on`], which
//! turns the report into a [`DamageError`] carrying the same report.
//!
//! A reader's existing output channel gains one variant carrying a [`Damage`]
//! (`DemuxEvent::Damage`, `SessionEvent::Damage`, `Event::Damage`); it is
//! never a callback stored in the reader, so a reader stays sans-IO.

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;

/// A media time range in a stated time base.
///
/// Both ends are ticks of [`timescale`](Self::timescale), so a consumer can
/// compare the range with a sample's `pts` without guessing a rate. `end` is
/// exclusive; `end == start` marks a point in time.
#[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 {
    /// A range from `start` (inclusive) to `end` (exclusive) in `timescale`.
    #[must_use]
    pub const fn new(timescale: Timescale, start: i64, end: i64) -> Self {
        Self {
            timescale,
            start,
            end,
        }
    }

    /// A single instant in `timescale`.
    #[must_use]
    pub const fn at(timescale: Timescale, tick: i64) -> Self {
        Self::new(timescale, tick, tick)
    }

    /// The time base the two ends are expressed in.
    #[must_use]
    pub const fn timescale(self) -> Timescale {
        self.timescale
    }

    /// First tick covered.
    #[must_use]
    pub const fn start(self) -> i64 {
        self.start
    }

    /// One past the last tick covered.
    #[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)
    }
}

/// Where in the input a [`Damage`] happened, as far as the reader knows.
///
/// Every part is optional: a reader never fabricates a location it did not
/// observe. Build one with the setters and attach it with
/// [`Damage::with_location`], or use [`Damage`]'s own `at_*`/`for_*` builders.
#[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 {
    /// An empty location.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            byte_range: None,
            track: None,
            media_time: None,
            ordinal: None,
        }
    }

    /// The byte range, when the input has byte positions.
    #[must_use]
    pub const fn byte_range(&self) -> Option<ByteRange> {
        self.byte_range
    }

    /// The track the damage belongs to, when it belongs to one.
    #[must_use]
    pub const fn track(&self) -> Option<TrackId> {
        self.track
    }

    /// The media time range, when the damaged content had timing.
    #[must_use]
    pub const fn media_time(&self) -> Option<MediaTimeRange> {
        self.media_time
    }

    /// The ordinal of the affected unit within its stream, when the reader
    /// counts units.
    #[must_use]
    pub const fn ordinal(&self) -> Option<u64> {
        self.ordinal
    }

    /// Record a byte range.
    #[must_use]
    pub const fn with_byte_range(mut self, range: ByteRange) -> Self {
        self.byte_range = Some(range);
        self
    }

    /// Record the owning track.
    #[must_use]
    pub const fn with_track(mut self, track: TrackId) -> Self {
        self.track = Some(track);
        self
    }

    /// Record a media time range.
    #[must_use]
    pub const fn with_media_time(mut self, range: MediaTimeRange) -> Self {
        self.media_time = Some(range);
        self
    }

    /// Record the ordinal of the affected unit.
    #[must_use]
    pub const fn with_ordinal(mut self, ordinal: u64) -> Self {
        self.ordinal = Some(ordinal);
        self
    }
}

/// What a reader did to the content when it found it broken.
///
/// Deliberately format-independent and small: it names the effect on the
/// content, not the box, packet or element that caused it (that is
/// [`Damage::what`]). `#[non_exhaustive]`: a new way to continue past damage
/// adds a variant.
#[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 {
    /// Metadata was skipped: the reader left it out of its output.
    MetadataSkipped,
    /// Metadata was carried uninterpreted: the reader passed it through
    /// without understanding it.
    MetadataUninterpreted,
    /// A media unit was dropped and is not delivered.
    MediaUnitDropped,
    /// A media unit was delivered, but flagged as damaged.
    MediaUnitDamaged,
    /// The reader resynchronised: bytes were skipped to find the next valid
    /// unit.
    Resynchronised,
    /// The input was truncated.
    InputTruncated,
    /// The timeline was repaired: a timestamp was rebased or a gap closed.
    TimelineRepaired,
    /// A whole track could not be established and was dropped.
    TrackDropped,
    /// A caller-supplied limit was reached and the content above it was
    /// dropped.
    LimitReached,
}

impl DamageKind {
    /// A short, stable label for this kind — used by `Display`.
    #[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);

/// How much a [`Damage`] costs the viewer.
///
/// No "fatal" level: a failure the reader cannot continue past is an error,
/// not a report.
#[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 {
    /// Nothing a viewer would notice (an uninterpreted tag, a repaired
    /// timestamp, a skipped reserved field).
    Informational,
    /// Content is missing or altered (a dropped unit, a damaged frame, a
    /// truncated tail).
    Degraded,
}

impl Severity {
    /// A short, stable label for this severity — used by `Display`.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Severity::Informational => "informational",
            Severity::Degraded => "degraded",
        }
    }
}

crate::impl_spec_display!(Severity);

/// One thing a reader skipped, with everything it knows about it.
///
/// Plain data, private fields, builder-style construction:
///
/// ```
/// use broadcast_core::damage::{Damage, DamageKind, Severity};
///
/// let report = Damage::new(DamageKind::MediaUnitDropped, Severity::Degraded, "PES packet")
///     .with_byte_range(broadcast_core::range::ByteRange::new(1_234, 188))
///     .with_track(broadcast_core::ids::TrackId::new(1));
/// assert_eq!(report.kind(), DamageKind::MediaUnitDropped);
/// assert_eq!(report.location().byte_range().map(|r| r.offset()), Some(1_234));
/// ```
#[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 {
    /// A report of `kind` at `severity` about the structure `what`, named in
    /// the format's own terms (`"trun"`, `"PES packet"`, `"onMetaData"`).
    #[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,
        }
    }

    /// What happened to the content.
    #[must_use]
    pub const fn kind(&self) -> DamageKind {
        self.kind
    }

    /// How much it costs the viewer.
    #[must_use]
    pub const fn severity(&self) -> Severity {
        self.severity
    }

    /// Where in the input it happened, as far as the reader knows.
    #[must_use]
    pub const fn location(&self) -> DamageLocation {
        self.location
    }

    /// The structure that was damaged, in the format's own terms.
    #[must_use]
    pub const fn what(&self) -> &'static str {
        self.what
    }

    /// The box/atom type, for a format whose structures are four-character
    /// codes.
    #[must_use]
    pub const fn fourcc(&self) -> Option<[u8; FOURCC_LEN]> {
        self.fourcc
    }

    /// The typed cause, when the reader's failure is one of the workspace's
    /// shared error kinds.
    #[must_use]
    pub const fn cause(&self) -> Option<WireError> {
        self.cause
    }

    /// Whether the skipped bytes are still available verbatim to the caller.
    ///
    /// `false` means they were discarded (or never arrived). `true` means the
    /// reader kept them, so a caller that wants to repair can ask for them;
    /// the range is in [`DamageLocation::byte_range`].
    #[must_use]
    pub const fn recoverable_bytes(&self) -> bool {
        self.recoverable_bytes
    }

    /// Replace the whole location.
    #[must_use]
    pub const fn with_location(mut self, location: DamageLocation) -> Self {
        self.location = location;
        self
    }

    /// Record where in the input the damage is.
    #[must_use]
    pub const fn with_byte_range(mut self, range: ByteRange) -> Self {
        self.location = self.location.with_byte_range(range);
        self
    }

    /// Record the track the damaged content belongs to.
    #[must_use]
    pub const fn with_track(mut self, track: TrackId) -> Self {
        self.location = self.location.with_track(track);
        self
    }

    /// Record the media time of the damaged content.
    #[must_use]
    pub const fn with_media_time(mut self, range: MediaTimeRange) -> Self {
        self.location = self.location.with_media_time(range);
        self
    }

    /// Record the ordinal of the affected unit within its stream.
    #[must_use]
    pub const fn with_ordinal(mut self, ordinal: u64) -> Self {
        self.location = self.location.with_ordinal(ordinal);
        self
    }

    /// Record a four-character box/atom type.
    #[must_use]
    pub const fn with_fourcc(mut self, fourcc: [u8; FOURCC_LEN]) -> Self {
        self.fourcc = Some(fourcc);
        self
    }

    /// Record the typed cause.
    #[must_use]
    pub const fn with_cause(mut self, cause: WireError) -> Self {
        self.cause = Some(cause);
        self
    }

    /// Record whether the skipped bytes are still available verbatim.
    #[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(())
    }
}

/// What a [`DamagePolicy`] says to do with one report.
#[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 {
    /// Continue, and publish the report.
    #[default]
    Report,
    /// Stop with a [`DamageError`] carrying the report.
    Fail,
}

impl Disposition {
    /// A short, stable label for this disposition — used by `Display`.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Disposition::Report => "report",
            Disposition::Fail => "fail",
        }
    }
}

crate::impl_spec_display!(Disposition);

/// The caller's decision about what a [`Damage`] means.
///
/// One setting per [`Severity`], plus optional per-[`DamageKind`] overrides
/// (checked first). The default reports everything and fails on nothing:
/// best effort. There is no "ignore silently" setting — a reader always
/// produces the report; the policy only decides whether it also stops.
///
/// ```
/// use broadcast_core::damage::{Damage, DamageKind, DamagePolicy, Severity};
///
/// let policy = DamagePolicy::default().fail_on(Severity::Degraded);
/// let report = Damage::new(DamageKind::MediaUnitDropped, Severity::Degraded, "PES packet");
/// assert!(policy.admit(report).is_err());
/// let quiet = Damage::new(DamageKind::MetadataSkipped, Severity::Informational, "tag");
/// assert!(policy.admit(quiet).is_ok());
/// ```
#[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 {
    /// Set what every report of `severity` means.
    #[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
    }

    /// Fail on every report of `severity`.
    #[must_use]
    pub fn fail_on(self, severity: Severity) -> Self {
        self.with_severity(severity, Disposition::Fail)
    }

    /// Override what a report of `kind` means, whatever its severity.
    #[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
    }

    /// The decision for one report: a per-kind override if there is one,
    /// otherwise the severity setting.
    #[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,
        }
    }

    /// Decide what one report means: `Ok(damage)` hands it back to publish and
    /// continue, `Err(error)` is the typed stop carrying the same report.
    ///
    /// # Errors
    /// [`DamageError`] when the policy's decision for this report is
    /// [`Disposition::Fail`].
    pub fn admit(&self, damage: Damage) -> Result<Damage, DamageError> {
        match self.decision(&damage) {
            Disposition::Report => Ok(damage),
            Disposition::Fail => Err(DamageError::new(damage)),
        }
    }
}

/// The typed stop a [`DamagePolicy`] raises for a report it fails on.
///
/// Carries the same [`Damage`] the reader would otherwise have published, so
/// a caller that handles the error sees everything the report says.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DamageError {
    /// Boxed so a reader's `Result<_, DamageError>` stays small.
    damage: Box<Damage>,
}

impl DamageError {
    /// Wrap a report as a stop.
    #[must_use]
    pub fn new(damage: Damage) -> Self {
        Self {
            damage: Box::new(damage),
        }
    }

    /// The report this stop carries.
    #[must_use]
    pub fn damage(&self) -> &Damage {
        &self.damage
    }

    /// Take the report back out.
    #[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")
        );
    }
}