mediaschema 0.2.0

Product-agnostic media-primitive schema (buffa-generated)
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
//! `Media<Id>` — shared content row (locked `schema/media.md` r9).
//!
//! The indexed media **content** — one row per content hash. Many physical
//! copies of the same bytes (the same file duplicated across
//! folders/volumes) collapse to **one** `Media`; the copy-specific
//! metadata (file name, path, filesystem creation time, discovering watch)
//! lives on the per-copy [`MediaFile`](super::MediaFile) aggregate, and
//! `files: Vec<Id>` is the reverse lookup to those copies. All
//! **content-intrinsic** scalar metadata lives here and nowhere else; the
//! kind facets are thin aggregates and stream/codec data is per-track.
//! `Media` is the architectural root of the domain — every other aggregate
//! transitively descends from it via the three optional facet FKs
//! (`video_id`/`audio_id`/`subtitle_id`).
//!
//! ## Cross-cutting (locked)
//!
//! - Generic over `Id` (default [`Uuid7`]); facet FKs are the same UUIDv7.
//! - [`FileChecksum`] is the 32-byte content hash — a **distinct newtype
//!   from `Id`** (content ≠ identity).
//! - Wall-clock: [`jiff::Timestamp`] (ms-resolution).
//! - Media-time (overall duration): [`mediatime::Timestamp`]. (The locked
//!   doc names it `mediatime::TrackTime`, but `mediatime 0.1.6` only
//!   exports `Timestamp`/`TimeRange`/`Timebase`; same doc/code drift as
//!   `Speaker.speech_duration` — read the doc's `TrackTime` as
//!   `mediatime::Timestamp` pending a doc-name fix.)
//! - `error_flags` is a maintained **rollup** of per-kind track failures
//!   ([`MediaErrorFlags`] — `VIDEO_ERROR` / `AUDIO_ERROR` /
//!   `SUBTITLE_ERROR` + reserved bits). Drill-down details live on the
//!   tracks (`*Track.index_errors`).
//! - `probe_error` is the **one** non-track error case — file unprobeable
//!   ⇒ no tracks were created.
//! - `device` / `gps` are the published `mediaframe` capture-metadata
//!   types ([`mediaframe::capture::Device`] /
//!   [`mediaframe::capture::GeoLocation`]; EXIF / capture-metadata
//!   charter).
//!
//! ## Encapsulation
//!
//! No public fields. Access via getters (`const fn` where possible);
//! mutation via `with_*` builders and `set_*` setters (returning
//! `&mut Self` so they chain). `try_new` is the validating constructor;
//! nil `id` and nil `checksum` are rejected.

use derive_more::IsVariant;
use jiff::Timestamp as JiffTimestamp;
use mediaframe::{
  capture::{Device, GeoLocation},
  container::Format,
};
use mediatime::Timestamp as MediaTimestamp;

use crate::domain::{ErrorInfo, FileChecksum, MediaErrorFlags, MediaKind, Uuid7};

/// The indexed media content — the architectural root of the domain.
///
/// **The content row, one per content hash.** Per-copy metadata (name,
/// path, filesystem creation time, discovering watch) lives on
/// [`MediaFile`](super::MediaFile); `files` is the reverse lookup to this
/// content's copies.
///
/// **No `Default` impl** — defaulting to `{ id: nil, checksum: zero, … }`
/// would represent an orphan content row with no real identity. Construct
/// via [`Media::try_new`] (validating: rejects nil `id` and zero
/// `checksum`).
///
/// **Fields are private**; access via getters and `with_*` / `set_*`
/// mutators per the encapsulation rule.
#[derive(Debug, Clone, PartialEq)]
pub struct Media<Id = Uuid7> {
  id: Id,
  checksum: FileChecksum,
  /// **Container** format (MP4/MKV/MKA/…). Codec is per-track.
  format: Format,
  size: u64,
  duration: Option<MediaTimestamp>,
  kind: MediaKind,
  /// Verbatim `AVFormatContext.nb_streams` — the total stream count
  /// from the container probe, *including* data / attachment streams
  /// the schema may not model per-track. Kept distinct from
  /// `video_id` / `audio_id` / `subtitle_id` track-count rollups so a
  /// consumer can detect "ffmpeg saw streams we don't represent".
  nb_streams: u32,
  /// Verbatim `AVFormatContext.nb_chapters`. Kept even when
  /// `chapters.is_empty()` so a probe-without-chapter-fetch still
  /// carries the count; once the chapter probe completes, the
  /// invariant `chapters.len() == nb_chapters` should hold
  /// (application-layer, not enforced here).
  nb_chapters: u32,
  /// Reverse lookup → this content's [`MediaFile`](super::MediaFile)
  /// copies (the reverse side of `MediaFile.media_id`).
  files: std::vec::Vec<Id>,
  /// Reverse lookup → this content's [`Chapter`](super::Chapter) rows
  /// (the reverse side of `Chapter.media_id`). Empty until the chapter
  /// probe populates it.
  chapters: std::vec::Vec<Id>,
  /// FK → `Video` facet (`None` = no video stream on this file).
  video_id: Option<Id>,
  /// FK → `Audio` facet (`None` = no audio stream).
  audio_id: Option<Id>,
  /// FK → `Subtitle` facet (`None` = no subtitle stream).
  subtitle_id: Option<Id>,
  /// Maintained rollup: a bit is set iff that kind's `track_progress.failed
  /// > 0`. Drill-down details live on `*Track.index_errors`.
  error_flags: MediaErrorFlags,
  /// **File-level** probe failure only — the one non-track error case
  /// (file unprobeable ⇒ no tracks were created).
  probe_error: Option<ErrorInfo>,
  /// EXIF capture date (wall-clock; `None` = not recorded). Stored
  /// faithfully — `Some(epoch)` is preserved; the legacy wire `0`
  /// sentinel is collapsed to `None` by the wire-decode adapter, not here.
  capture_date: Option<JiffTimestamp>,
  /// EXIF device info (camera / phone make+model).
  device: Option<Device>,
  /// EXIF GPS reading.
  gps: Option<GeoLocation>,
}

impl Media<Uuid7> {
  /// Validating constructor for the canonical `Uuid7` identity type.
  ///
  /// Rejects nil `id` (every content row must have a real identity) and
  /// the zero `checksum` sentinel ("not yet computed" — a probed file
  /// always has its content hash before reaching the domain). Other
  /// content-intrinsic fields are caller-supplied; `files` starts empty
  /// (filled via `push_file` / `with_files` as copies are discovered) and
  /// facet FKs default to `None`, filled in via `with_video_id` /
  /// `with_audio_id` / `with_subtitle_id` after the corresponding facet
  /// aggregates land.
  pub fn try_new(
    id: Uuid7,
    checksum: FileChecksum,
    format: Format,
    size: u64,
    kind: MediaKind,
  ) -> Result<Self, MediaError> {
    if id.is_nil() {
      return Err(MediaError::NilId);
    }
    if checksum.is_zero() {
      return Err(MediaError::ZeroChecksum);
    }
    Ok(Self {
      id,
      checksum,
      format,
      size,
      duration: None,
      kind,
      nb_streams: 0,
      nb_chapters: 0,
      files: std::vec::Vec::new(),
      chapters: std::vec::Vec::new(),
      video_id: None,
      audio_id: None,
      subtitle_id: None,
      error_flags: MediaErrorFlags::new(),
      probe_error: None,
      capture_date: None,
      device: None,
      gps: None,
    })
  }
}

impl<Id> Media<Id> {
  /// Canonical identity.
  #[inline(always)]
  pub const fn id_ref(&self) -> &Id {
    &self.id
  }

  /// Content hash (the unique-across-`Media` index).
  #[inline(always)]
  pub const fn checksum_ref(&self) -> &FileChecksum {
    &self.checksum
  }

  /// Container format (MP4/MKV/MKA/…).
  #[inline(always)]
  pub const fn format_ref(&self) -> &Format {
    &self.format
  }

  /// File size in bytes.
  #[inline(always)]
  pub const fn size(&self) -> u64 {
    self.size
  }

  /// **Overall** media length (per-track duration is on the track).
  #[inline(always)]
  pub const fn duration_ref(&self) -> Option<&MediaTimestamp> {
    self.duration.as_ref()
  }

  /// Top-level media kind.
  #[inline(always)]
  pub const fn kind(&self) -> MediaKind {
    self.kind
  }

  /// Verbatim `AVFormatContext.nb_streams`.
  #[inline(always)]
  pub const fn nb_streams(&self) -> u32 {
    self.nb_streams
  }

  /// Verbatim `AVFormatContext.nb_chapters`.
  #[inline(always)]
  pub const fn nb_chapters(&self) -> u32 {
    self.nb_chapters
  }

  /// Reverse lookup → this content's [`MediaFile`](super::MediaFile)
  /// copies (projects the slice, never `&Vec`).
  #[inline(always)]
  pub const fn files_slice(&self) -> &[Id] {
    self.files.as_slice()
  }

  /// Reverse lookup → this content's [`Chapter`](super::Chapter) rows.
  #[inline(always)]
  pub const fn chapters_slice(&self) -> &[Id] {
    self.chapters.as_slice()
  }

  /// FK → `Video` facet.
  #[inline(always)]
  pub const fn video_id_ref(&self) -> Option<&Id> {
    self.video_id.as_ref()
  }

  /// FK → `Audio` facet.
  #[inline(always)]
  pub const fn audio_id_ref(&self) -> Option<&Id> {
    self.audio_id.as_ref()
  }

  /// FK → `Subtitle` facet.
  #[inline(always)]
  pub const fn subtitle_id_ref(&self) -> Option<&Id> {
    self.subtitle_id.as_ref()
  }

  /// Per-kind error rollup.
  #[inline(always)]
  pub const fn error_flags(&self) -> MediaErrorFlags {
    self.error_flags
  }

  /// File-level probe error (the non-track case).
  #[inline(always)]
  pub const fn probe_error_ref(&self) -> Option<&ErrorInfo> {
    self.probe_error.as_ref()
  }

  /// EXIF capture timestamp.
  #[inline(always)]
  pub const fn capture_date_ref(&self) -> Option<&JiffTimestamp> {
    self.capture_date.as_ref()
  }

  /// EXIF device info.
  #[inline(always)]
  pub const fn device_ref(&self) -> Option<&Device> {
    self.device.as_ref()
  }

  /// EXIF GPS reading.
  #[inline(always)]
  pub const fn gps_ref(&self) -> Option<&GeoLocation> {
    self.gps.as_ref()
  }

  // --- builders -----------------------------------------------------------

  /// Builder: replace overall `duration`.
  ///
  /// `duration` is an overall-media *length*, so a negative
  /// [`MediaTimestamp::pts`] is rejected with
  /// [`MediaError::NegativeDuration`]. Zero and positive PTS are
  /// accepted, as is `None` (duration unknown).
  #[inline]
  pub fn try_with_duration(mut self, d: Option<MediaTimestamp>) -> Result<Self, MediaError> {
    if let Some(ts) = d {
      if ts.pts() < 0 {
        return Err(MediaError::NegativeDuration);
      }
    }
    self.duration = d;
    Ok(self)
  }

  /// Builder: replace `nb_streams` (verbatim from probe).
  #[inline(always)]
  #[must_use]
  pub const fn with_nb_streams(mut self, n: u32) -> Self {
    self.nb_streams = n;
    self
  }

  /// Builder: replace `nb_chapters` (verbatim from probe).
  #[inline(always)]
  #[must_use]
  pub const fn with_nb_chapters(mut self, n: u32) -> Self {
    self.nb_chapters = n;
    self
  }

  /// Builder: replace the whole `files` reverse-lookup list.
  #[inline(always)]
  #[must_use]
  pub fn with_files(mut self, files: std::vec::Vec<Id>) -> Self {
    self.files = files;
    self
  }

  /// Builder: append one `MediaFile` id to the reverse-lookup list.
  #[inline(always)]
  #[must_use]
  pub fn push_file(mut self, file: Id) -> Self {
    self.files.push(file);
    self
  }

  /// Builder: replace the whole `chapters` reverse-lookup list.
  #[inline(always)]
  #[must_use]
  pub fn with_chapters(mut self, chapters: std::vec::Vec<Id>) -> Self {
    self.chapters = chapters;
    self
  }

  /// Builder: append one `Chapter` id to the reverse-lookup list.
  #[inline(always)]
  #[must_use]
  pub fn push_chapter(mut self, chapter: Id) -> Self {
    self.chapters.push(chapter);
    self
  }

  /// Builder: set the `Video` facet FK.
  #[inline(always)]
  #[must_use]
  pub fn with_video_id(mut self, video_id: Option<Id>) -> Self {
    self.video_id = video_id;
    self
  }

  /// Builder: set the `Audio` facet FK.
  #[inline(always)]
  #[must_use]
  pub fn with_audio_id(mut self, audio_id: Option<Id>) -> Self {
    self.audio_id = audio_id;
    self
  }

  /// Builder: set the `Subtitle` facet FK.
  #[inline(always)]
  #[must_use]
  pub fn with_subtitle_id(mut self, subtitle_id: Option<Id>) -> Self {
    self.subtitle_id = subtitle_id;
    self
  }

  /// Builder: replace the per-kind error-rollup.
  #[inline(always)]
  #[must_use]
  pub const fn with_error_flags(mut self, flags: MediaErrorFlags) -> Self {
    self.error_flags = flags;
    self
  }

  /// Builder: replace `probe_error`.
  #[inline(always)]
  #[must_use]
  pub fn with_probe_error(mut self, e: Option<ErrorInfo>) -> Self {
    self.probe_error = e;
    self
  }

  /// Builder: replace `capture_date`.
  ///
  /// The supplied `Option` is stored **faithfully** — `Some(epoch)` is a
  /// real timestamp and is preserved distinctly from `None`. Translating
  /// the legacy wire `0` (Unix epoch, ms) sentinel to `None` is the
  /// responsibility of the wire-decode adapter, not the domain.
  #[inline(always)]
  #[must_use]
  pub const fn with_capture_date(mut self, t: Option<JiffTimestamp>) -> Self {
    self.capture_date = t;
    self
  }

  /// Builder: replace `device`.
  #[inline(always)]
  #[must_use]
  pub fn with_device(mut self, d: Option<Device>) -> Self {
    self.device = d;
    self
  }

  /// Builder: replace `gps`.
  #[inline(always)]
  #[must_use]
  pub const fn with_gps(mut self, g: Option<GeoLocation>) -> Self {
    self.gps = g;
    self
  }

  // --- in-place setters ---------------------------------------------------

  /// In-place mutator for overall `duration`.
  ///
  /// `duration` is an overall-media *length*, so a negative
  /// [`MediaTimestamp::pts`] is rejected with
  /// [`MediaError::NegativeDuration`] and the prior value is left
  /// unchanged. Zero and positive PTS are accepted, as is `None`.
  #[inline]
  pub fn try_set_duration(&mut self, d: Option<MediaTimestamp>) -> Result<&mut Self, MediaError> {
    if let Some(ts) = d {
      if ts.pts() < 0 {
        return Err(MediaError::NegativeDuration);
      }
    }
    self.duration = d;
    Ok(self)
  }

  /// In-place mutator: replace `nb_streams` (verbatim from probe).
  #[inline(always)]
  pub const fn set_nb_streams(&mut self, n: u32) -> &mut Self {
    self.nb_streams = n;
    self
  }

  /// In-place mutator: replace `nb_chapters` (verbatim from probe).
  #[inline(always)]
  pub const fn set_nb_chapters(&mut self, n: u32) -> &mut Self {
    self.nb_chapters = n;
    self
  }

  /// In-place mutator: replace the whole `files` reverse-lookup list.
  #[inline(always)]
  pub fn set_files(&mut self, files: std::vec::Vec<Id>) -> &mut Self {
    self.files = files;
    self
  }

  /// In-place mutator: replace the whole `chapters` reverse-lookup list.
  #[inline(always)]
  pub fn set_chapters(&mut self, chapters: std::vec::Vec<Id>) -> &mut Self {
    self.chapters = chapters;
    self
  }

  /// In-place mutator: append one `Chapter` id to the reverse-lookup
  /// list.
  #[inline(always)]
  pub fn add_chapter(&mut self, chapter: Id) -> &mut Self {
    self.chapters.push(chapter);
    self
  }

  /// In-place mutator: append one `MediaFile` id to the reverse-lookup
  /// list.
  #[inline(always)]
  pub fn add_file(&mut self, file: Id) -> &mut Self {
    self.files.push(file);
    self
  }

  /// In-place mutator for the `Video` facet FK.
  #[inline(always)]
  pub fn set_video_id(&mut self, video_id: Option<Id>) -> &mut Self {
    self.video_id = video_id;
    self
  }

  /// In-place mutator for the `Audio` facet FK.
  #[inline(always)]
  pub fn set_audio_id(&mut self, audio_id: Option<Id>) -> &mut Self {
    self.audio_id = audio_id;
    self
  }

  /// In-place mutator for the `Subtitle` facet FK.
  #[inline(always)]
  pub fn set_subtitle_id(&mut self, subtitle_id: Option<Id>) -> &mut Self {
    self.subtitle_id = subtitle_id;
    self
  }

  /// In-place mutator for the per-kind error rollup.
  #[inline(always)]
  pub const fn set_error_flags(&mut self, flags: MediaErrorFlags) -> &mut Self {
    self.error_flags = flags;
    self
  }

  /// In-place mutator for `probe_error`.
  #[inline(always)]
  pub fn set_probe_error(&mut self, e: Option<ErrorInfo>) -> &mut Self {
    self.probe_error = e;
    self
  }

  /// In-place mutator for `capture_date`. Stores the supplied `Option`
  /// faithfully — see [`Media::with_capture_date`].
  #[inline(always)]
  pub const fn set_capture_date(&mut self, t: Option<JiffTimestamp>) -> &mut Self {
    self.capture_date = t;
    self
  }

  /// In-place mutator for `device`.
  #[inline(always)]
  pub fn set_device(&mut self, d: Option<Device>) -> &mut Self {
    self.device = d;
    self
  }

  /// In-place mutator for `gps`.
  #[inline(always)]
  pub const fn set_gps(&mut self, g: Option<GeoLocation>) -> &mut Self {
    self.gps = g;
    self
  }
}

/// Error returned when [`Media::try_new`] cannot uphold the
/// non-nil-id / non-zero-checksum invariants. Unit-only enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, IsVariant, thiserror::Error)]
#[non_exhaustive]
pub enum MediaError {
  /// Supplied `id` was the [`Uuid7`] nil sentinel — not a real identity.
  #[error("Media id must not be the nil UUID")]
  NilId,
  /// Supplied `checksum` was the all-zero "not yet computed" sentinel
  /// — a `Media` reaches the domain layer only after probing, so the
  /// content hash should already be filled in.
  #[error("Media checksum must not be the all-zero sentinel (file must be probed)")]
  ZeroChecksum,
  /// Supplied `duration` had a negative PTS — an overall-media length
  /// cannot be negative.
  #[error("Media duration must not be negative")]
  NegativeDuration,
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(all(test, feature = "std"))]
mod tests {
  use core::num::NonZeroU32;

  use mediatime::Timebase;

  use super::*;

  fn fake_checksum() -> FileChecksum {
    let mut bytes = [0u8; 32];
    bytes[0] = 0x01;
    FileChecksum::from_bytes(bytes)
  }

  /// A representative non-epoch capture timestamp.
  fn real_ts() -> JiffTimestamp {
    JiffTimestamp::from_millisecond(1_700_000_000_000).expect("valid timestamp")
  }

  #[test]
  fn try_new_happy_path() {
    let id = Uuid7::new();
    let cs = fake_checksum();
    let m = Media::try_new(id, cs, Format::Mp4, 12_345, MediaKind::Video)
      .expect("valid construction must succeed");
    assert_eq!(m.id_ref(), &id);
    assert_eq!(m.checksum_ref(), &cs);
    assert_eq!(m.format_ref(), &Format::Mp4);
    assert_eq!(m.size(), 12_345);
    assert!(m.kind().is_video());
    assert!(
      m.files_slice().is_empty(),
      "files start empty on construction"
    );
    assert!(m.video_id_ref().is_none());
    assert!(m.audio_id_ref().is_none());
    assert!(m.subtitle_id_ref().is_none());
    assert!(m.duration_ref().is_none());
    assert_eq!(m.error_flags(), MediaErrorFlags::new());
    assert!(m.probe_error_ref().is_none());
    assert!(m.capture_date_ref().is_none());
    assert!(m.device_ref().is_none());
    assert!(m.gps_ref().is_none());
  }

  #[test]
  fn try_new_rejects_nil_id() {
    let r = Media::try_new(
      Uuid7::nil(),
      fake_checksum(),
      Format::Mp4,
      0,
      MediaKind::Video,
    );
    assert_eq!(r.err(), Some(MediaError::NilId));
    assert!(MediaError::NilId.is_nil_id());
  }

  #[test]
  fn try_new_rejects_zero_checksum() {
    let r = Media::try_new(
      Uuid7::new(),
      FileChecksum::new(),
      Format::Mp4,
      0,
      MediaKind::Video,
    );
    assert_eq!(r.err(), Some(MediaError::ZeroChecksum));
    assert!(MediaError::ZeroChecksum.is_zero_checksum());
  }

  #[test]
  fn files_round_trip() {
    let a = Uuid7::new();
    let b = Uuid7::new();
    let m = Media::try_new(
      Uuid7::new(),
      fake_checksum(),
      Format::Mp4,
      0,
      MediaKind::Video,
    )
    .unwrap()
    .push_file(a)
    .with_files(vec![a, b]);
    assert_eq!(m.files_slice(), &[a, b]);

    // In-place vocabulary mirrors the builders.
    let mut m = m;
    let c = Uuid7::new();
    m.add_file(c);
    assert_eq!(m.files_slice(), &[a, b, c]);
    m.set_files(vec![c]);
    assert_eq!(m.files_slice(), &[c]);
  }

  #[test]
  fn capture_date_stored_faithfully() {
    // The domain preserves `Some(epoch)` distinctly from `None`. Collapsing
    // the legacy wire `0` sentinel is the wire-decode adapter's job, not the
    // domain's — see `Media::with_capture_date`.
    let epoch = JiffTimestamp::default();
    let m = Media::try_new(
      Uuid7::new(),
      fake_checksum(),
      Format::Mp4,
      0,
      MediaKind::Video,
    )
    .unwrap()
    .with_capture_date(Some(epoch));
    assert_eq!(
      m.capture_date_ref(),
      Some(&epoch),
      "Some(epoch) must be preserved faithfully"
    );

    // A real instant is preserved too.
    let m = m.with_capture_date(Some(real_ts()));
    assert_eq!(m.capture_date_ref(), Some(&real_ts()));

    // An explicit `None` stays `None`.
    let m = m.with_capture_date(None);
    assert!(m.capture_date_ref().is_none());

    // The in-place setter stores faithfully and identically.
    let mut m = m;
    m.set_capture_date(Some(epoch));
    assert_eq!(m.capture_date_ref(), Some(&epoch));
  }

  #[test]
  fn builders_chain() {
    let id = Uuid7::new();
    let video_id = Uuid7::new();
    let audio_id = Uuid7::new();
    let gps = GeoLocation::try_new(37.7749, -122.4194, Some(20.0)).expect("valid coordinates");
    let m = Media::try_new(id, fake_checksum(), Format::Mp4, 12_345, MediaKind::Video)
      .unwrap()
      .with_video_id(Some(video_id))
      .with_audio_id(Some(audio_id))
      .with_error_flags(MediaErrorFlags::VIDEO_ERROR)
      .with_capture_date(Some(real_ts()))
      .with_device(Some(
        Device::new().with_make("Apple").with_model("iPhone 15 Pro"),
      ))
      .with_gps(Some(gps));

    assert_eq!(m.video_id_ref(), Some(&video_id));
    assert_eq!(m.audio_id_ref(), Some(&audio_id));
    assert!(m.subtitle_id_ref().is_none());
    assert_eq!(m.error_flags(), MediaErrorFlags::VIDEO_ERROR);
    assert!(m.capture_date_ref().is_some());
    let dev = m.device_ref().expect("device set");
    assert_eq!(dev.make(), "Apple");
    assert_eq!(dev.model(), "iPhone 15 Pro");
    let gps = m.gps_ref().expect("gps set");
    assert_eq!(gps.lat(), 37.7749);
    assert_eq!(gps.lon(), -122.4194);
    assert_eq!(gps.altitude(), Some(20.0));
  }

  #[test]
  fn setters_mutate_in_place() {
    let mut m = Media::try_new(
      Uuid7::new(),
      fake_checksum(),
      Format::Mp4,
      0,
      MediaKind::Video,
    )
    .unwrap();
    m.set_video_id(Some(Uuid7::new()));
    m.set_error_flags(MediaErrorFlags::AUDIO_ERROR | MediaErrorFlags::SUBTITLE_ERROR);
    m.set_gps(Some(
      GeoLocation::try_new(0.0, 0.0, None).expect("valid coordinates"),
    ));
    assert!(m.video_id_ref().is_some());
    assert!(m
      .error_flags()
      .contains(MediaErrorFlags::AUDIO_ERROR | MediaErrorFlags::SUBTITLE_ERROR));
    assert_eq!(m.gps_ref().map(GeoLocation::altitude), Some(None));
  }

  fn sample_media() -> Media {
    Media::try_new(
      Uuid7::new(),
      fake_checksum(),
      Format::Mp4,
      0,
      MediaKind::Video,
    )
    .unwrap()
  }

  fn pts(value: i64) -> MediaTimestamp {
    MediaTimestamp::new(value, Timebase::new(1, NonZeroU32::new(1000).unwrap()))
  }

  #[test]
  fn try_with_duration_accepts_zero_positive_and_none() {
    let m = sample_media().try_with_duration(Some(pts(0))).unwrap();
    assert_eq!(m.duration_ref().map(MediaTimestamp::pts), Some(0));

    let m = m.try_with_duration(Some(pts(48_000))).unwrap();
    assert_eq!(m.duration_ref().map(MediaTimestamp::pts), Some(48_000));

    let m = m.try_with_duration(None).unwrap();
    assert!(m.duration_ref().is_none());
  }

  #[test]
  fn try_with_duration_rejects_negative() {
    let r = sample_media().try_with_duration(Some(pts(-1)));
    assert_eq!(r.err(), Some(MediaError::NegativeDuration));
    assert!(MediaError::NegativeDuration.is_negative_duration());
  }

  #[test]
  fn try_set_duration_accepts_zero_positive_and_none() {
    let mut m = sample_media();

    m.try_set_duration(Some(pts(0))).unwrap();
    assert_eq!(m.duration_ref().map(MediaTimestamp::pts), Some(0));

    m.try_set_duration(Some(pts(48_000))).unwrap();
    assert_eq!(m.duration_ref().map(MediaTimestamp::pts), Some(48_000));

    m.try_set_duration(None).unwrap();
    assert!(m.duration_ref().is_none());
  }

  #[test]
  fn try_set_duration_rejects_negative_and_preserves_prior_value() {
    let mut m = sample_media().try_with_duration(Some(pts(48_000))).unwrap();

    let r = m.try_set_duration(Some(pts(-1)));
    assert_eq!(r.err(), Some(MediaError::NegativeDuration));
    // Rejected setter leaves the prior value unchanged.
    assert_eq!(
      m.duration_ref().map(MediaTimestamp::pts),
      Some(48_000),
      "rejected try_set_duration must not mutate the prior value"
    );
  }
}