mediadecode 0.7.0

Generic, no_std-friendly type-and-trait spine for media decoders (FFmpeg, WebCodecs, R3D, BRAW, ARRIRAW, X-OCN, ProRes RAW, Canon Cinema RAW Light).
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! The demux tier — the track table, the five-arm packet envelope, and
//! the [`Demuxer`] session face.
//!
//! A container file is a bundle of *tracks*; reading it produces a
//! single interleaved stream of *packets*, each belonging to one track.
//! This module names both halves: [`TrackInfo`] describes a track,
//! [`DemuxedPacket`] delivers one packet with its track coordinate
//! attached, and [`Demuxer`] is the pull session that hands them out.
//!
//! # The session is pull-style
//!
//! The caller owns the loop. [`Demuxer::next_packet`] returns the next
//! packet in interleaved file order and `Ok(None)` at end of file. One
//! packet is in hand at a time, whatever the file's length, and the
//! caller pulls only when it is ready to consume — backpressure with no
//! machinery. This is the same rhythm the decoder faces already keep
//! (the caller schedules; see [`crate::decoder`]).
//!
//! # Construction is not on the trait
//!
//! [`Demuxer`] covers the **opened session** only: [`tracks`],
//! [`next_packet`], [`seek`]. Opening is each backend's own business
//! and each backend's is different — FFmpeg opens from a path or from a
//! `Read + Seek` reader, a WebAssembly container parser opens from a
//! byte slice. Putting a constructor on the trait would force one of
//! those spellings onto all of them, which is exactly what the decoder
//! traits already decline to do.
//!
//! # Not every backend is a demuxer
//!
//! R3D and BRAW are clip-oriented SDKs: they expose frames by index,
//! never packets, so there is nothing for them to demux. They
//! deliberately do **not** implement this trait and join a pipeline one
//! tier up, through [`crate::decoder::VideoFrameSource`] and
//! [`crate::decoder::AudioFrameSource`]. A graph that wants both shapes
//! unifies them at the *frame* tier, not here.
//!
//! [`tracks`]: Demuxer::tracks
//! [`next_packet`]: Demuxer::next_packet
//! [`seek`]: Demuxer::seek

use core::fmt::Debug;

use crate::{
  Timebase, Timestamp,
  adapter::{AudioAdapter, SubtitleAdapter, VideoAdapter},
  packet::{AudioPacket, PacketFlags, SubtitlePacket, VideoPacket},
};

/// A track's position in the table [`Demuxer::tracks`] returns.
///
/// `TrackIndex(i)` **is** the index of `tracks()[i]` — the coordinate
/// and the table position are the same number by contract, so a
/// consumer that has a packet's track can look up its description
/// without a side map. Backends whose native identifiers are sparse or
/// unordered are responsible for the translation.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TrackIndex(usize);

impl TrackIndex {
  /// Constructs a `TrackIndex` from a position in the track table.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(index: usize) -> Self {
    Self(index)
  }

  /// Returns the position in the track table.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn get(self) -> usize {
    self.0
  }
}

/// What a track carries.
///
/// A closed roster: these six are every kind a container can present,
/// and [`Unknown`](Self::Unknown) is the honest answer for a track the
/// backend cannot classify rather than an escape hatch for new kinds.
/// Minted here rather than borrowed: `mediaframe` has a track
/// *disposition* vocabulary but no kind vocabulary, and the dependency
/// direction forbids reaching the other way.
///
/// **Cover art is [`Attachment`](Self::Attachment), not
/// [`Video`](Self::Video).** A still image stored in a container's
/// video-shaped slot is an attachment by every property that matters —
/// one sample, no timeline, no motion — so the `Video` arm carries true
/// motion video and nothing else. See [`DemuxedPacket`] for the
/// delivery contract that follows from this.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TrackKind {
  /// Motion video.
  Video,
  /// Audio.
  Audio,
  /// Subtitles / captions, text or bitmap.
  Subtitle,
  /// Timed opaque data — timecode, KLV, timed ID3.
  Data,
  /// A file carried inside the container: a font, cover art.
  Attachment,
  /// The backend could not classify this track.
  #[default]
  Unknown,
}

/// Backend vocabulary for the **demux tier**.
///
/// Bundles the three decoding families ([`VideoAdapter`],
/// [`AudioAdapter`], [`SubtitleAdapter`]) that already exist and adds
/// the seats only a demuxer needs: extras for the two packet kinds that
/// have no decoder face, extras for a track-table row, and the text
/// carrier for a track's identity metadata.
///
/// The three families are bound to share this adapter's
/// [`CodecId`](Self::CodecId). A demuxer reads one container, and a
/// container's track table has one codec-identifier column — the same
/// namespace names its video, its audio, its subtitles, and its cover
/// art. Keeping them one type is what lets a consumer take the codec
/// identifier off an [`Attachment`](TrackKind::Attachment) track
/// carrying cover art and hand it to a video decoder.
pub trait DemuxAdapter {
  /// Codec identifier for every track in the table, whatever its kind
  /// (e.g. a newtype around FFmpeg's `AVCodecID`, a WebCodecs codec
  /// string, a container fourcc).
  type CodecId: Copy + Eq + Debug;

  /// Vocabulary for the container's video tracks.
  type Video: VideoAdapter<CodecId = Self::CodecId>;
  /// Vocabulary for the container's audio tracks.
  type Audio: AudioAdapter<CodecId = Self::CodecId>;
  /// Vocabulary for the container's subtitle tracks.
  type Subtitle: SubtitleAdapter<CodecId = Self::CodecId>;

  /// Backend-specific extras carried on every [`DataPacket`].
  type DataExtra;
  /// Backend-specific extras carried on every [`AttachmentPacket`].
  type AttachmentExtra;
  /// Backend-specific extras carried on every [`TrackInfo`] — the place
  /// a backend keeps what the portable row has no seat for (a native
  /// stream index, disposition bits, the container's metadata bag).
  type TrackExtra;

  /// Text carrier for a track's identity metadata — the attachment
  /// filename and MIME type on [`TrackInfo`].
  ///
  /// A seat rather than a fixed string type so the core stays
  /// allocator-free: a backend with compile-time names can bind
  /// `&'static str`, one that reads them out of a container binds an
  /// owned inline string.
  type Text: AsRef<str> + Debug;
}

/// The [`VideoPacket`] a [`DemuxAdapter`] delivers over buffer `D`.
pub type DemuxVideoPacket<E, D> =
  VideoPacket<<<E as DemuxAdapter>::Video as VideoAdapter>::PacketExtra, D>;

/// The [`AudioPacket`] a [`DemuxAdapter`] delivers over buffer `D`.
pub type DemuxAudioPacket<E, D> =
  AudioPacket<<<E as DemuxAdapter>::Audio as AudioAdapter>::PacketExtra, D>;

/// The [`SubtitlePacket`] a [`DemuxAdapter`] delivers over buffer `D`.
pub type DemuxSubtitlePacket<E, D> =
  SubtitlePacket<<<E as DemuxAdapter>::Subtitle as SubtitleAdapter>::PacketExtra, D>;

/// The [`DataPacket`] a [`DemuxAdapter`] delivers over buffer `D`.
pub type DemuxDataPacket<E, D> = DataPacket<<E as DemuxAdapter>::DataExtra, D>;

/// The [`AttachmentPacket`] a [`DemuxAdapter`] delivers over buffer `D`.
pub type DemuxAttachmentPacket<E, D> = AttachmentPacket<<E as DemuxAdapter>::AttachmentExtra, D>;

// ---------------------------------------------------------------------------
//  The two packet types the demux tier adds.
//
//  They live here rather than beside their three siblings in
//  `crate::packet` because they exist only as demux products: this
//  crate has no `DataDecoder` and no `AttachmentDecoder`, so nothing
//  ever hands one of these to a decoder. Their shape still follows
//  `packet.rs` exactly — private fields, `const` accessors, `with_*`
//  consuming builders and `set_*` in-place mutators.
// ---------------------------------------------------------------------------

/// A timed opaque-data packet — timecode, KLV, timed ID3.
///
/// Data tracks are real packet streams: they run along the file's
/// timeline and carry a payload per timestamp. They are never
/// reordered, so — like [`SubtitlePacket`] and for the same reason —
/// there is no DTS seat; a data packet's presentation time is its
/// decode time.
pub struct DataPacket<E, D> {
  pts: Option<Timestamp>,
  duration: Option<Timestamp>,
  flags: PacketFlags,
  data: D,
  extra: E,
}

impl<E, D> DataPacket<E, D> {
  /// Constructs a `DataPacket` from `data` and `extra`. Timestamps
  /// default to `None` and flags to empty.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(data: D, extra: E) -> Self {
    Self {
      pts: None,
      duration: None,
      flags: PacketFlags::empty(),
      data,
      extra,
    }
  }

  /// Returns the presentation timestamp.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn pts(&self) -> Option<Timestamp> {
    self.pts
  }
  /// Returns the packet duration.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn duration(&self) -> Option<Timestamp> {
    self.duration
  }
  /// Returns the packet flags.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn flags(&self) -> PacketFlags {
    self.flags
  }
  /// Returns the payload buffer.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn data(&self) -> &D {
    &self.data
  }
  /// Returns the backend-specific extras.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn extra(&self) -> &E {
    &self.extra
  }
  /// Returns a mutable reference to the backend-specific extras.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn extra_mut(&mut self) -> &mut E {
    &mut self.extra
  }
  /// Consumes the packet and returns the buffer.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_data(self) -> D {
    self.data
  }
  /// Consumes the packet and returns `(buffer, extras)`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_parts(self) -> (D, E) {
    (self.data, self.extra)
  }

  /// Sets the PTS (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_pts(mut self, v: Option<Timestamp>) -> Self {
    self.pts = v;
    self
  }
  /// Sets the duration (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_duration(mut self, v: Option<Timestamp>) -> Self {
    self.duration = v;
    self
  }
  /// Sets the flags (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_flags(mut self, v: PacketFlags) -> Self {
    self.flags = v;
    self
  }

  /// Sets the PTS in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_pts(&mut self, v: Option<Timestamp>) -> &mut Self {
    self.pts = v;
    self
  }
  /// Sets the duration in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_duration(&mut self, v: Option<Timestamp>) -> &mut Self {
    self.duration = v;
    self
  }
  /// Sets the flags in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_flags(&mut self, v: PacketFlags) -> &mut Self {
    self.flags = v;
    self
  }
}

/// An attachment packet — a whole file carried inside the container.
///
/// **No timestamps.** A font or a cover image is not on the timeline;
/// it is present for the whole file or not at all. Its identity — the
/// filename it was attached under, its MIME type — is not repeated here
/// either: that belongs to the track, and lives on [`TrackInfo`].
/// [`PacketFlags`] is kept because `CORRUPT` still means something for
/// a payload that failed to read.
pub struct AttachmentPacket<E, D> {
  flags: PacketFlags,
  data: D,
  extra: E,
}

impl<E, D> AttachmentPacket<E, D> {
  /// Constructs an `AttachmentPacket` from `data` and `extra`. Flags
  /// default to empty.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(data: D, extra: E) -> Self {
    Self {
      flags: PacketFlags::empty(),
      data,
      extra,
    }
  }

  /// Returns the packet flags.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn flags(&self) -> PacketFlags {
    self.flags
  }
  /// Returns the attached file's bytes.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn data(&self) -> &D {
    &self.data
  }
  /// Returns the backend-specific extras.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn extra(&self) -> &E {
    &self.extra
  }
  /// Returns a mutable reference to the backend-specific extras.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn extra_mut(&mut self) -> &mut E {
    &mut self.extra
  }
  /// Consumes the packet and returns the buffer.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_data(self) -> D {
    self.data
  }
  /// Consumes the packet and returns `(buffer, extras)`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_parts(self) -> (D, E) {
    (self.data, self.extra)
  }

  /// Sets the flags (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_flags(mut self, v: PacketFlags) -> Self {
    self.flags = v;
    self
  }

  /// Sets the flags in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_flags(&mut self, v: PacketFlags) -> &mut Self {
    self.flags = v;
    self
  }
}

// ---------------------------------------------------------------------------
//  The track table.
// ---------------------------------------------------------------------------

/// A track's codec and per-kind parameters.
///
/// The arm **is** the kind: [`TrackInfo::kind`] reads it off this enum
/// rather than storing a second copy that could disagree with the
/// payload beside it.
pub enum TrackParams<E: DemuxAdapter> {
  /// Motion video.
  Video {
    /// Codec identifier.
    codec: E::CodecId,
    /// Coded width in pixels.
    width: u32,
    /// Coded height in pixels.
    height: u32,
    /// Pixel format the track declares, in the backend's vocabulary.
    pixel_format: <E::Video as VideoAdapter>::PixelFormat,
    /// Average frame rate, as a rate-shaped [`Timebase`] (`30000/1001`
    /// for 29.97 fps), or `None` when the container does not say.
    frame_rate: Option<Timebase>,
  },
  /// Audio.
  Audio {
    /// Codec identifier.
    codec: E::CodecId,
    /// Sample rate in Hz.
    sample_rate: u32,
    /// Channel count.
    channel_count: u8,
    /// Sample format the track declares, in the backend's vocabulary.
    sample_format: <E::Audio as AudioAdapter>::SampleFormat,
    /// Channel layout the track declares, in the backend's vocabulary.
    channel_layout: <E::Audio as AudioAdapter>::ChannelLayout,
  },
  /// Subtitles / captions.
  Subtitle {
    /// Codec identifier.
    codec: E::CodecId,
  },
  /// Timed opaque data.
  Data {
    /// Codec identifier.
    codec: E::CodecId,
  },
  /// An attached file — a font, cover art.
  Attachment {
    /// Codec identifier — the font format, or the still image's codec
    /// for cover art.
    codec: E::CodecId,
  },
  /// A track the backend could not classify.
  Unknown {
    /// Codec identifier, which may itself be the backend's "none".
    codec: E::CodecId,
  },
}

impl<E: DemuxAdapter> TrackParams<E> {
  /// Returns the kind this arm describes.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn kind(&self) -> TrackKind {
    match self {
      Self::Video { .. } => TrackKind::Video,
      Self::Audio { .. } => TrackKind::Audio,
      Self::Subtitle { .. } => TrackKind::Subtitle,
      Self::Data { .. } => TrackKind::Data,
      Self::Attachment { .. } => TrackKind::Attachment,
      Self::Unknown { .. } => TrackKind::Unknown,
    }
  }

  /// Returns the codec identifier, whichever arm this is.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn codec(&self) -> E::CodecId {
    match self {
      Self::Video { codec, .. }
      | Self::Audio { codec, .. }
      | Self::Subtitle { codec }
      | Self::Data { codec }
      | Self::Attachment { codec }
      | Self::Unknown { codec } => *codec,
    }
  }
}

/// One row of the track table [`Demuxer::tracks`] returns.
///
/// Carries what a consumer needs to decide whether it wants the track
/// and how to open a decoder for it: the kind, the timebase every
/// timestamp on that track is expressed in, the duration when the
/// container knows it, the per-kind codec parameters, and — for
/// attachments — the identity the file was attached under.
///
/// Everything a particular backend knows and this row has no seat for
/// rides [`DemuxAdapter::TrackExtra`].
pub struct TrackInfo<E: DemuxAdapter> {
  timebase: Timebase,
  duration: Option<Timestamp>,
  params: TrackParams<E>,
  filename: Option<E::Text>,
  mime_type: Option<E::Text>,
  extra: E::TrackExtra,
}

impl<E: DemuxAdapter> TrackInfo<E> {
  /// Constructs a `TrackInfo`. Identity metadata defaults to `None`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(timebase: Timebase, params: TrackParams<E>, extra: E::TrackExtra) -> Self {
    Self {
      timebase,
      duration: None,
      params,
      filename: None,
      mime_type: None,
      extra,
    }
  }

  /// Returns the track's kind, read off [`Self::params`].
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn kind(&self) -> TrackKind {
    self.params.kind()
  }
  /// Returns the timebase every timestamp on this track is expressed in.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn timebase(&self) -> Timebase {
    self.timebase
  }
  /// Returns the track duration, or `None` when the container does not
  /// carry one.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn duration(&self) -> Option<Timestamp> {
    self.duration
  }
  /// Returns the per-kind codec parameters.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn params(&self) -> &TrackParams<E> {
    &self.params
  }
  /// Returns the filename an attachment was attached under, when the
  /// container carries one. `None` for every other kind.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn filename(&self) -> Option<&E::Text> {
    self.filename.as_ref()
  }
  /// Returns an attachment's declared MIME type, when the container
  /// carries one. `None` for every other kind.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn mime_type(&self) -> Option<&E::Text> {
    self.mime_type.as_ref()
  }
  /// Returns the backend-specific extras.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn extra(&self) -> &E::TrackExtra {
    &self.extra
  }
  /// Returns a mutable reference to the backend-specific extras.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn extra_mut(&mut self) -> &mut E::TrackExtra {
    &mut self.extra
  }

  /// Sets the duration (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub const fn with_duration(mut self, v: Option<Timestamp>) -> Self {
    self.duration = v;
    self
  }
  /// Sets the attachment filename (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_filename(mut self, v: Option<E::Text>) -> Self {
    self.filename = v;
    self
  }
  /// Sets the attachment MIME type (consuming builder).
  #[cfg_attr(not(tarpaulin), inline(always))]
  #[must_use]
  pub fn with_mime_type(mut self, v: Option<E::Text>) -> Self {
    self.mime_type = v;
    self
  }

  /// Sets the duration in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn set_duration(&mut self, v: Option<Timestamp>) -> &mut Self {
    self.duration = v;
    self
  }
  /// Sets the attachment filename in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_filename(&mut self, v: Option<E::Text>) -> &mut Self {
    self.filename = v;
    self
  }
  /// Sets the attachment MIME type in place.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn set_mime_type(&mut self, v: Option<E::Text>) -> &mut Self {
    self.mime_type = v;
    self
  }
}

// ---------------------------------------------------------------------------
//  The delivery envelope.
// ---------------------------------------------------------------------------

/// One demuxed packet, with the track it came from.
///
/// Five arms — the whole delivery roster. Packets do not carry track
/// coordinates; this envelope does, which is what lets the same
/// [`VideoPacket`] type be handed straight to a decoder without
/// stripping a field the decoder has no use for.
///
/// A track whose kind is [`TrackKind::Unknown`] has no arm, and its
/// packets are therefore never delivered. The roster is closed at five
/// on purpose: a kind nothing can name is a kind nothing can consume.
pub enum DemuxedPacket<E: DemuxAdapter, D> {
  /// A compressed video packet.
  Video {
    /// The track it belongs to.
    track: TrackIndex,
    /// The packet.
    packet: DemuxVideoPacket<E, D>,
  },
  /// A compressed audio packet.
  Audio {
    /// The track it belongs to.
    track: TrackIndex,
    /// The packet.
    packet: DemuxAudioPacket<E, D>,
  },
  /// A compressed subtitle packet.
  Subtitle {
    /// The track it belongs to.
    track: TrackIndex,
    /// The packet.
    packet: DemuxSubtitlePacket<E, D>,
  },
  /// A timed opaque-data packet.
  Data {
    /// The track it belongs to.
    track: TrackIndex,
    /// The packet.
    packet: DemuxDataPacket<E, D>,
  },
  /// An attachment payload.
  Attachment {
    /// The track it belongs to.
    track: TrackIndex,
    /// The packet.
    packet: DemuxAttachmentPacket<E, D>,
  },
}

impl<E: DemuxAdapter, D> DemuxedPacket<E, D> {
  /// Returns the track this packet belongs to.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn track(&self) -> TrackIndex {
    match self {
      Self::Video { track, .. }
      | Self::Audio { track, .. }
      | Self::Subtitle { track, .. }
      | Self::Data { track, .. }
      | Self::Attachment { track, .. } => *track,
    }
  }

  /// Returns the kind of track this packet came from.
  ///
  /// Always equal to `demuxer.tracks()[self.track().get()].kind()`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn kind(&self) -> TrackKind {
    match self {
      Self::Video { .. } => TrackKind::Video,
      Self::Audio { .. } => TrackKind::Audio,
      Self::Subtitle { .. } => TrackKind::Subtitle,
      Self::Data { .. } => TrackKind::Data,
      Self::Attachment { .. } => TrackKind::Attachment,
    }
  }
}

// ---------------------------------------------------------------------------
//  The session face.
// ---------------------------------------------------------------------------

/// An opened container session: the track table, a pull loop, and a seek.
///
/// # Delivery order
///
/// [`next_packet`](Self::next_packet) returns packets in **interleaved
/// file order** — the order the container stores them in, tracks mixed
/// together exactly as written. `Ok(None)` means end of file, and once
/// it is returned it stays returned until a [`seek`](Self::seek) moves
/// the session somewhere else.
///
/// # The attachment contract
///
/// An [`Attachment`](TrackKind::Attachment) track delivers **exactly
/// one packet, before any timed packet**. Attachments are not on the
/// timeline, so a consumer must be able to collect them all before it
/// starts consuming time — a subtitle renderer needs its fonts before
/// the first cue, and a thumbnailer wants the cover art without reading
/// the file to its end. Backends satisfy this by synthesising the
/// packet when the container keeps the payload outside the packet
/// stream (fonts, whose bytes live in the track's codec extradata) and
/// by hoisting the natural one when it exists (cover art, which is a
/// real packet the container stores).
///
/// A track's identity — the filename it was attached under, its MIME
/// type — is on [`TrackInfo`], not repeated on every packet.
///
/// # Seeking
///
/// [`seek`](Self::seek) obeys three laws:
///
/// 1. **It flushes session state.** Anything buffered from before the
///    seek is discarded; the next [`next_packet`](Self::next_packet)
///    reads from the new position.
/// 2. **It lands on the nearest keyframe at or before the target.**
///    Never after. A decoder fed from a landing point past the target
///    would have no reference frame, so "at or before" is a
///    correctness requirement, not a preference — the caller discards
///    the packets between the landing point and the target itself.
/// 3. **Attachments are never replayed.** An attachment already
///    delivered is not delivered again, however many times the session
///    seeks. One attachment track yields one packet for the life of the
///    session — a seek moves the *timeline*, and attachments are not on
///    it.
///
/// # What is not here
///
/// Opening. See the [module docs](self#construction-is-not-on-the-trait).
pub trait Demuxer {
  /// Backend-specific vocabulary.
  type Adapter: DemuxAdapter;
  /// Buffer type held by the packets this session produces.
  type Buffer: AsRef<[u8]>;
  /// Demuxer-specific error type.
  type Error;

  /// Returns the container's track table.
  ///
  /// Position `i` describes [`TrackIndex::new(i)`](TrackIndex::new) —
  /// the coordinate every [`DemuxedPacket`] carries.
  fn tracks(&self) -> &[TrackInfo<Self::Adapter>];

  /// Pulls the next packet in interleaved file order, or `Ok(None)` at
  /// end of file.
  fn next_packet(
    &mut self,
  ) -> Result<Option<DemuxedPacket<Self::Adapter, Self::Buffer>>, Self::Error>;

  /// Seeks to `target`, landing on the nearest keyframe at or before it.
  ///
  /// See the [three laws](Self#seeking) on the trait.
  fn seek(&mut self, target: Timestamp) -> Result<(), Self::Error>;
}

#[cfg(test)]
mod tests {
  use core::num::NonZeroI32;

  use super::*;

  struct VLoop;
  impl VideoAdapter for VLoop {
    type CodecId = u32;
    type PixelFormat = u32;
    type PacketExtra = ();
    type FrameExtra = ();
  }

  struct ALoop;
  impl AudioAdapter for ALoop {
    type CodecId = u32;
    type SampleFormat = u32;
    type ChannelLayout = u32;
    type PacketExtra = ();
    type FrameExtra = ();
  }

  struct SLoop;
  impl SubtitleAdapter for SLoop {
    type CodecId = u32;
    type PacketExtra = ();
    type FrameExtra = ();
  }

  struct Loopback;
  impl DemuxAdapter for Loopback {
    type CodecId = u32;
    type Video = VLoop;
    type Audio = ALoop;
    type Subtitle = SLoop;
    type DataExtra = ();
    type AttachmentExtra = ();
    type TrackExtra = ();
    type Text = &'static str;
  }

  fn ms_tb() -> Timebase {
    Timebase::new(1, NonZeroI32::new(1000).expect("non-zero"))
  }

  #[test]
  fn track_index_round_trips() {
    assert_eq!(TrackIndex::new(3).get(), 3);
    assert_eq!(TrackIndex::default(), TrackIndex::new(0));
  }

  #[test]
  fn the_kind_is_read_off_the_params_arm() {
    // The one-source-of-truth property: there is no way to build a
    // `TrackInfo` whose advertised kind disagrees with its payload.
    let rows: [(TrackParams<Loopback>, TrackKind); 6] = [
      (
        TrackParams::Video {
          codec: 1,
          width: 1920,
          height: 1080,
          pixel_format: 7,
          frame_rate: None,
        },
        TrackKind::Video,
      ),
      (
        TrackParams::Audio {
          codec: 2,
          sample_rate: 48_000,
          channel_count: 2,
          sample_format: 3,
          channel_layout: 4,
        },
        TrackKind::Audio,
      ),
      (TrackParams::Subtitle { codec: 3 }, TrackKind::Subtitle),
      (TrackParams::Data { codec: 4 }, TrackKind::Data),
      (TrackParams::Attachment { codec: 5 }, TrackKind::Attachment),
      (TrackParams::Unknown { codec: 0 }, TrackKind::Unknown),
    ];
    for (params, expected) in rows {
      let codec = params.codec();
      let info = TrackInfo::<Loopback>::new(ms_tb(), params, ());
      assert_eq!(info.kind(), expected);
      assert_eq!(info.params().kind(), expected);
      assert_eq!(info.params().codec(), codec);
    }
  }

  #[test]
  fn attachment_identity_lives_on_the_track() {
    let info = TrackInfo::<Loopback>::new(ms_tb(), TrackParams::Attachment { codec: 9 }, ())
      .with_filename(Some("Arial.ttf"))
      .with_mime_type(Some("application/x-truetype-font"));
    assert_eq!(info.filename().copied(), Some("Arial.ttf"));
    assert_eq!(
      info.mime_type().copied(),
      Some("application/x-truetype-font")
    );
    assert_eq!(info.duration(), None);
  }

  #[test]
  fn data_packet_follows_the_house_shape() {
    let pts = Timestamp::new(1500, ms_tb());
    let p: DataPacket<(), &[u8]> = DataPacket::new(&b"klv"[..], ())
      .with_pts(Some(pts))
      .with_duration(Some(Timestamp::new(40, ms_tb())))
      .with_flags(PacketFlags::KEY);
    assert_eq!(p.pts(), Some(pts));
    assert_eq!(p.duration(), Some(Timestamp::new(40, ms_tb())));
    assert!(p.flags().contains(PacketFlags::KEY));
    let (data, _) = p.into_parts();
    assert_eq!(data, b"klv");
  }

  #[test]
  fn an_attachment_packet_has_no_timestamp_seat() {
    let mut p: AttachmentPacket<(), &[u8]> = AttachmentPacket::new(&b"\x00\x01TTF"[..], ());
    assert_eq!(p.flags(), PacketFlags::empty());
    p.set_flags(PacketFlags::CORRUPT);
    assert!(p.flags().contains(PacketFlags::CORRUPT));
    assert_eq!(p.data(), &&b"\x00\x01TTF"[..]);
  }

  #[test]
  fn the_envelope_carries_the_coordinate_and_the_kind() {
    let track = TrackIndex::new(2);
    let packets: [(DemuxedPacket<Loopback, &[u8]>, TrackKind); 5] = [
      (
        DemuxedPacket::Video {
          track,
          packet: VideoPacket::new(&[][..], ()),
        },
        TrackKind::Video,
      ),
      (
        DemuxedPacket::Audio {
          track,
          packet: AudioPacket::new(&[][..], ()),
        },
        TrackKind::Audio,
      ),
      (
        DemuxedPacket::Subtitle {
          track,
          packet: SubtitlePacket::new(&[][..], ()),
        },
        TrackKind::Subtitle,
      ),
      (
        DemuxedPacket::Data {
          track,
          packet: DataPacket::new(&[][..], ()),
        },
        TrackKind::Data,
      ),
      (
        DemuxedPacket::Attachment {
          track,
          packet: AttachmentPacket::new(&[][..], ()),
        },
        TrackKind::Attachment,
      ),
    ];
    for (packet, expected) in packets {
      assert_eq!(packet.track(), track);
      assert_eq!(packet.kind(), expected);
    }
  }

  /// Trivial loopback session — proves the trait is implementable and
  /// that its associated types resolve through the adapter bundle.
  struct LoopDemuxer {
    tracks: [TrackInfo<Loopback>; 1],
    drained: bool,
  }

  #[derive(Debug)]
  struct LoopError;

  impl Demuxer for LoopDemuxer {
    type Adapter = Loopback;
    type Buffer = &'static [u8];
    type Error = LoopError;

    fn tracks(&self) -> &[TrackInfo<Loopback>] {
      &self.tracks
    }

    fn next_packet(&mut self) -> Result<Option<DemuxedPacket<Loopback, &'static [u8]>>, LoopError> {
      if self.drained {
        return Ok(None);
      }
      self.drained = true;
      Ok(Some(DemuxedPacket::Audio {
        track: TrackIndex::new(0),
        packet: AudioPacket::new(&[][..], ()),
      }))
    }

    fn seek(&mut self, _target: Timestamp) -> Result<(), LoopError> {
      self.drained = false;
      Ok(())
    }
  }

  #[test]
  fn the_session_face_is_implementable_and_none_means_eof() {
    fn _accepts<D: Demuxer>() {}
    _accepts::<LoopDemuxer>();

    let mut d = LoopDemuxer {
      tracks: [TrackInfo::new(
        ms_tb(),
        TrackParams::Audio {
          codec: 1,
          sample_rate: 48_000,
          channel_count: 2,
          sample_format: 0,
          channel_layout: 0,
        },
        (),
      )],
      drained: false,
    };
    assert_eq!(d.tracks().len(), 1);
    assert_eq!(d.tracks()[0].kind(), TrackKind::Audio);
    assert!(matches!(
      d.next_packet().expect("pull"),
      Some(DemuxedPacket::Audio { .. })
    ));
    assert!(d.next_packet().expect("pull").is_none());
    assert!(d.next_packet().expect("pull").is_none(), "EOF is sticky");
    d.seek(Timestamp::new(0, ms_tb())).expect("seek");
    assert!(d.next_packet().expect("pull").is_some());
  }
}