mediadecode 0.8.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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
//! 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::{self, Debug};

use derive_more::{IsVariant, TryUnwrap, Unwrap};

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

// `Demuxer::take_tracks` is the only item in this module that owns an
// allocation (`Vec<TrackInfo<_>>`); everything else is `core`-only.
// Scoped here rather than pulled in at the crate root, so a reader
// can see exactly which module needs the heap.
#[cfg(any(feature = "std", feature = "alloc"))]
extern crate alloc;

/// 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, IsVariant)]
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.
///
/// `Clone` and `Debug` derive directly — see [`VideoPacket`]'s docs
/// for why the per-parameter bound this produces is already precise.
#[derive(Clone, Debug)]
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.
///
/// `Clone` and `Debug` derive directly — see [`VideoPacket`]'s docs
/// for why the per-parameter bound this produces is already precise.
#[derive(Clone, Debug)]
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.
// ---------------------------------------------------------------------------

/// Payload for [`TrackParams::Video`].
pub struct VideoTrackParams<E: DemuxAdapter> {
  codec: E::CodecId,
  width: u32,
  height: u32,
  pixel_format: <E::Video as VideoAdapter>::PixelFormat,
  frame_rate: Option<Timebase>,
}

impl<E: DemuxAdapter> VideoTrackParams<E> {
  /// Constructs a `VideoTrackParams`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(
    codec: E::CodecId,
    width: u32,
    height: u32,
    pixel_format: <E::Video as VideoAdapter>::PixelFormat,
    frame_rate: Option<Timebase>,
  ) -> Self {
    Self {
      codec,
      width,
      height,
      pixel_format,
      frame_rate,
    }
  }

  /// Returns the codec identifier.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn codec(&self) -> E::CodecId {
    self.codec
  }
  /// Returns the coded width in pixels.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn width(&self) -> u32 {
    self.width
  }
  /// Returns the coded height in pixels.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn height(&self) -> u32 {
    self.height
  }
  /// Returns the pixel format the track declares, in the backend's
  /// vocabulary.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn pixel_format(&self) -> &<E::Video as VideoAdapter>::PixelFormat {
    &self.pixel_format
  }
  /// Returns the average frame rate, as a rate-shaped [`Timebase`]
  /// (`30000/1001` for 29.97 fps), or `None` when the container does
  /// not say.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn frame_rate(&self) -> Option<Timebase> {
    self.frame_rate
  }
}

// `Debug` is hand-written for the same associated-type reason as
// `TrackParams` itself (see its own impl, below): every field here
// that is not a plain `u32` routes through an associated type on
// `E`, and each of those already carries the bound it needs on the
// trait that declares it. `#[derive(Debug)]` would add a flat `E:
// Debug` bound the struct's own fields never ask for.
//
// No `Clone` on this type, `TrackParams`, or `TrackInfo` — see
// `TrackInfo`'s own doc, below, for the message-carrier law that
// keeps it off the whole family.
impl<E: DemuxAdapter> Debug for VideoTrackParams<E> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("VideoTrackParams")
      .field("codec", &self.codec)
      .field("width", &self.width)
      .field("height", &self.height)
      .field("pixel_format", &self.pixel_format)
      .field("frame_rate", &self.frame_rate)
      .finish()
  }
}

/// Payload for [`TrackParams::Audio`].
pub struct AudioTrackParams<E: DemuxAdapter> {
  codec: E::CodecId,
  sample_rate: u32,
  channel_count: u8,
  sample_format: <E::Audio as AudioAdapter>::SampleFormat,
  channel_layout: <E::Audio as AudioAdapter>::ChannelLayout,
}

impl<E: DemuxAdapter> AudioTrackParams<E> {
  /// Constructs an `AudioTrackParams`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(
    codec: E::CodecId,
    sample_rate: u32,
    channel_count: u8,
    sample_format: <E::Audio as AudioAdapter>::SampleFormat,
    channel_layout: <E::Audio as AudioAdapter>::ChannelLayout,
  ) -> Self {
    Self {
      codec,
      sample_rate,
      channel_count,
      sample_format,
      channel_layout,
    }
  }

  /// Returns the codec identifier.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn codec(&self) -> E::CodecId {
    self.codec
  }
  /// Returns the sample rate in Hz.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn sample_rate(&self) -> u32 {
    self.sample_rate
  }
  /// Returns the channel count.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn channel_count(&self) -> u8 {
    self.channel_count
  }
  /// Returns the sample format the track declares, in the backend's
  /// vocabulary.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn sample_format(&self) -> <E::Audio as AudioAdapter>::SampleFormat {
    self.sample_format
  }
  /// Returns the channel layout the track declares, in the backend's
  /// vocabulary.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn channel_layout(&self) -> &<E::Audio as AudioAdapter>::ChannelLayout {
    &self.channel_layout
  }
}

impl<E: DemuxAdapter> Debug for AudioTrackParams<E> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("AudioTrackParams")
      .field("codec", &self.codec)
      .field("sample_rate", &self.sample_rate)
      .field("channel_count", &self.channel_count)
      .field("sample_format", &self.sample_format)
      .field("channel_layout", &self.channel_layout)
      .finish()
  }
}

/// Payload for [`TrackParams::Subtitle`].
pub struct SubtitleTrackParams<E: DemuxAdapter> {
  codec: E::CodecId,
}

impl<E: DemuxAdapter> SubtitleTrackParams<E> {
  /// Constructs a `SubtitleTrackParams`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(codec: E::CodecId) -> Self {
    Self { codec }
  }

  /// Returns the codec identifier.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn codec(&self) -> E::CodecId {
    self.codec
  }
}

impl<E: DemuxAdapter> Debug for SubtitleTrackParams<E> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SubtitleTrackParams")
      .field("codec", &self.codec)
      .finish()
  }
}

/// Payload for [`TrackParams::Data`].
pub struct DataTrackParams<E: DemuxAdapter> {
  codec: E::CodecId,
}

impl<E: DemuxAdapter> DataTrackParams<E> {
  /// Constructs a `DataTrackParams`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(codec: E::CodecId) -> Self {
    Self { codec }
  }

  /// Returns the codec identifier.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn codec(&self) -> E::CodecId {
    self.codec
  }
}

impl<E: DemuxAdapter> Debug for DataTrackParams<E> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("DataTrackParams")
      .field("codec", &self.codec)
      .finish()
  }
}

/// Payload for [`TrackParams::Attachment`].
pub struct AttachmentTrackParams<E: DemuxAdapter> {
  /// Codec identifier — the font format, or the still image's codec
  /// for cover art.
  codec: E::CodecId,
}

impl<E: DemuxAdapter> AttachmentTrackParams<E> {
  /// Constructs an `AttachmentTrackParams`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(codec: E::CodecId) -> Self {
    Self { codec }
  }

  /// Returns the codec identifier — the font format, or the still
  /// image's codec for cover art.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn codec(&self) -> E::CodecId {
    self.codec
  }
}

impl<E: DemuxAdapter> Debug for AttachmentTrackParams<E> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("AttachmentTrackParams")
      .field("codec", &self.codec)
      .finish()
  }
}

/// Payload for [`TrackParams::Unknown`].
pub struct UnknownTrackParams<E: DemuxAdapter> {
  /// Codec identifier, which may itself be the backend's "none".
  codec: E::CodecId,
}

impl<E: DemuxAdapter> UnknownTrackParams<E> {
  /// Constructs an `UnknownTrackParams`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(codec: E::CodecId) -> Self {
    Self { codec }
  }

  /// Returns the codec identifier, which may itself be the backend's
  /// "none".
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn codec(&self) -> E::CodecId {
    self.codec
  }
}

impl<E: DemuxAdapter> Debug for UnknownTrackParams<E> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("UnknownTrackParams")
      .field("codec", &self.codec)
      .finish()
  }
}

/// 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.
///
/// No `Clone` — see [`TrackInfo`]'s own doc for the message-carrier
/// law that keeps it off this type too.
#[derive(IsVariant, Unwrap, TryUnwrap)]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
pub enum TrackParams<E: DemuxAdapter> {
  /// Motion video.
  Video(VideoTrackParams<E>),
  /// Audio.
  Audio(AudioTrackParams<E>),
  /// Subtitles / captions.
  Subtitle(SubtitleTrackParams<E>),
  /// Timed opaque data.
  Data(DataTrackParams<E>),
  /// An attached file — a font, cover art.
  Attachment(AttachmentTrackParams<E>),
  /// A track the backend could not classify.
  Unknown(UnknownTrackParams<E>),
}

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(p) => p.codec(),
      Self::Audio(p) => p.codec(),
      Self::Subtitle(p) => p.codec(),
      Self::Data(p) => p.codec(),
      Self::Attachment(p) => p.codec(),
      Self::Unknown(p) => p.codec(),
    }
  }
}

// `Debug` is hand-written, not derived: a flat `#[derive(Debug)]`
// over the enum's own type parameter `E` would demand `E: Debug`,
// which none of the six payload structs' fields need — each already
// carries the precise bound it requires from the trait that declares
// its associated type. See each payload struct's own `Debug` impl,
// above, for the same reasoning one level down.
//
// No `Clone`: see `TrackInfo`'s own doc, below, for the
// message-carrier law.
impl<E: DemuxAdapter> Debug for TrackParams<E> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Video(p) => f.debug_tuple("Video").field(p).finish(),
      Self::Audio(p) => f.debug_tuple("Audio").field(p).finish(),
      Self::Subtitle(p) => f.debug_tuple("Subtitle").field(p).finish(),
      Self::Data(p) => f.debug_tuple("Data").field(p).finish(),
      Self::Attachment(p) => f.debug_tuple("Attachment").field(p).finish(),
      Self::Unknown(p) => f.debug_tuple("Unknown").field(p).finish(),
    }
  }
}

/// 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`].
///
/// **No `Clone`, on this type or on [`TrackParams`].** The
/// message-carrier law: messages may be `Clone`, but `Clone` is
/// always a refcount bump, never a deep copy — and a track row,
/// backend metadata down to codec parameters, is not cheap to
/// duplicate. A consumer that needs to share a row wraps it in `Arc`
/// once, at the door, instead of paying a deep copy per consumer.
/// [`Demuxer::take_tracks`] is that door: it moves the whole table
/// out in one call, meant to be taken exactly once, right after a
/// session opens, before any row needs to be shared further.
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
  }
}

// `Debug` is hand-written for the same reason as `TrackParams`'s:
// `#[derive(Debug)]` would add `E: Debug`, but the field that
// actually needs a bound is `E::TrackExtra` — `E::Text: Debug` is
// already guaranteed by `DemuxAdapter::Text`'s own trait bound, and
// `TrackParams<E>` needs no extra bound at all (see its own impl,
// above). No `Clone`: see this type's own doc, above, for the
// message-carrier law.
impl<E: DemuxAdapter> Debug for TrackInfo<E>
where
  E::TrackExtra: Debug,
{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("TrackInfo")
      .field("timebase", &self.timebase)
      .field("duration", &self.duration)
      .field("params", &self.params)
      .field("filename", &self.filename)
      .field("mime_type", &self.mime_type)
      .field("extra", &self.extra)
      .finish()
  }
}

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

/// Payload for [`DemuxedPacket::Video`].
pub struct VideoTrackPacket<E: DemuxAdapter, D> {
  track: TrackIndex,
  packet: DemuxVideoPacket<E, D>,
}

impl<E: DemuxAdapter, D> VideoTrackPacket<E, D> {
  /// Constructs a `VideoTrackPacket`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(track: TrackIndex, packet: DemuxVideoPacket<E, D>) -> Self {
    Self { track, packet }
  }

  /// Returns the track this packet belongs to.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn track(&self) -> TrackIndex {
    self.track
  }
  /// Returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn packet(&self) -> &DemuxVideoPacket<E, D> {
    &self.packet
  }
  /// Consumes the envelope and returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_packet(self) -> DemuxVideoPacket<E, D> {
    self.packet
  }
  /// Consumes the envelope and returns `(track, packet)`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_parts(self) -> (TrackIndex, DemuxVideoPacket<E, D>) {
    (self.track, self.packet)
  }
}

// `Clone` / `Debug` are hand-written for the same associated-type
// reason as `TrackParams`'s payload structs, above: the bound belongs
// on `<E::Video as VideoAdapter>::PacketExtra`, not on `E` itself,
// which `#[derive]` cannot see.
impl<E, D> Clone for VideoTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Clone,
  <E::Video as VideoAdapter>::PacketExtra: Clone,
{
  fn clone(&self) -> Self {
    Self {
      track: self.track,
      packet: self.packet.clone(),
    }
  }
}

impl<E, D> Debug for VideoTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Debug,
  <E::Video as VideoAdapter>::PacketExtra: Debug,
{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("VideoTrackPacket")
      .field("track", &self.track)
      .field("packet", &self.packet)
      .finish()
  }
}

/// Payload for [`DemuxedPacket::Audio`].
pub struct AudioTrackPacket<E: DemuxAdapter, D> {
  track: TrackIndex,
  packet: DemuxAudioPacket<E, D>,
}

impl<E: DemuxAdapter, D> AudioTrackPacket<E, D> {
  /// Constructs an `AudioTrackPacket`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(track: TrackIndex, packet: DemuxAudioPacket<E, D>) -> Self {
    Self { track, packet }
  }

  /// Returns the track this packet belongs to.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn track(&self) -> TrackIndex {
    self.track
  }
  /// Returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn packet(&self) -> &DemuxAudioPacket<E, D> {
    &self.packet
  }
  /// Consumes the envelope and returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_packet(self) -> DemuxAudioPacket<E, D> {
    self.packet
  }
  /// Consumes the envelope and returns `(track, packet)`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_parts(self) -> (TrackIndex, DemuxAudioPacket<E, D>) {
    (self.track, self.packet)
  }
}

impl<E, D> Clone for AudioTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Clone,
  <E::Audio as AudioAdapter>::PacketExtra: Clone,
{
  fn clone(&self) -> Self {
    Self {
      track: self.track,
      packet: self.packet.clone(),
    }
  }
}

impl<E, D> Debug for AudioTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Debug,
  <E::Audio as AudioAdapter>::PacketExtra: Debug,
{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("AudioTrackPacket")
      .field("track", &self.track)
      .field("packet", &self.packet)
      .finish()
  }
}

/// Payload for [`DemuxedPacket::Subtitle`].
pub struct SubtitleTrackPacket<E: DemuxAdapter, D> {
  track: TrackIndex,
  packet: DemuxSubtitlePacket<E, D>,
}

impl<E: DemuxAdapter, D> SubtitleTrackPacket<E, D> {
  /// Constructs a `SubtitleTrackPacket`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(track: TrackIndex, packet: DemuxSubtitlePacket<E, D>) -> Self {
    Self { track, packet }
  }

  /// Returns the track this packet belongs to.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn track(&self) -> TrackIndex {
    self.track
  }
  /// Returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn packet(&self) -> &DemuxSubtitlePacket<E, D> {
    &self.packet
  }
  /// Consumes the envelope and returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_packet(self) -> DemuxSubtitlePacket<E, D> {
    self.packet
  }
  /// Consumes the envelope and returns `(track, packet)`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_parts(self) -> (TrackIndex, DemuxSubtitlePacket<E, D>) {
    (self.track, self.packet)
  }
}

impl<E, D> Clone for SubtitleTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Clone,
  <E::Subtitle as SubtitleAdapter>::PacketExtra: Clone,
{
  fn clone(&self) -> Self {
    Self {
      track: self.track,
      packet: self.packet.clone(),
    }
  }
}

impl<E, D> Debug for SubtitleTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Debug,
  <E::Subtitle as SubtitleAdapter>::PacketExtra: Debug,
{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("SubtitleTrackPacket")
      .field("track", &self.track)
      .field("packet", &self.packet)
      .finish()
  }
}

/// Payload for [`DemuxedPacket::Data`].
pub struct DataTrackPacket<E: DemuxAdapter, D> {
  track: TrackIndex,
  packet: DemuxDataPacket<E, D>,
}

impl<E: DemuxAdapter, D> DataTrackPacket<E, D> {
  /// Constructs a `DataTrackPacket`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(track: TrackIndex, packet: DemuxDataPacket<E, D>) -> Self {
    Self { track, packet }
  }

  /// Returns the track this packet belongs to.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn track(&self) -> TrackIndex {
    self.track
  }
  /// Returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn packet(&self) -> &DemuxDataPacket<E, D> {
    &self.packet
  }
  /// Consumes the envelope and returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_packet(self) -> DemuxDataPacket<E, D> {
    self.packet
  }
  /// Consumes the envelope and returns `(track, packet)`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_parts(self) -> (TrackIndex, DemuxDataPacket<E, D>) {
    (self.track, self.packet)
  }
}

impl<E, D> Clone for DataTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Clone,
  E::DataExtra: Clone,
{
  fn clone(&self) -> Self {
    Self {
      track: self.track,
      packet: self.packet.clone(),
    }
  }
}

impl<E, D> Debug for DataTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Debug,
  E::DataExtra: Debug,
{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("DataTrackPacket")
      .field("track", &self.track)
      .field("packet", &self.packet)
      .finish()
  }
}

/// Payload for [`DemuxedPacket::Attachment`].
pub struct AttachmentTrackPacket<E: DemuxAdapter, D> {
  track: TrackIndex,
  packet: DemuxAttachmentPacket<E, D>,
}

impl<E: DemuxAdapter, D> AttachmentTrackPacket<E, D> {
  /// Constructs an `AttachmentTrackPacket`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(track: TrackIndex, packet: DemuxAttachmentPacket<E, D>) -> Self {
    Self { track, packet }
  }

  /// Returns the track this packet belongs to.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn track(&self) -> TrackIndex {
    self.track
  }
  /// Returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn packet(&self) -> &DemuxAttachmentPacket<E, D> {
    &self.packet
  }
  /// Consumes the envelope and returns the packet.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_packet(self) -> DemuxAttachmentPacket<E, D> {
    self.packet
  }
  /// Consumes the envelope and returns `(track, packet)`.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_parts(self) -> (TrackIndex, DemuxAttachmentPacket<E, D>) {
    (self.track, self.packet)
  }
}

impl<E, D> Clone for AttachmentTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Clone,
  E::AttachmentExtra: Clone,
{
  fn clone(&self) -> Self {
    Self {
      track: self.track,
      packet: self.packet.clone(),
    }
  }
}

impl<E, D> Debug for AttachmentTrackPacket<E, D>
where
  E: DemuxAdapter,
  D: Debug,
  E::AttachmentExtra: Debug,
{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("AttachmentTrackPacket")
      .field("track", &self.track)
      .field("packet", &self.packet)
      .finish()
  }
}

/// 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.
#[derive(IsVariant, Unwrap, TryUnwrap)]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
pub enum DemuxedPacket<E: DemuxAdapter, D> {
  /// A compressed video packet.
  Video(VideoTrackPacket<E, D>),
  /// A compressed audio packet.
  Audio(AudioTrackPacket<E, D>),
  /// A compressed subtitle packet.
  Subtitle(SubtitleTrackPacket<E, D>),
  /// A timed opaque-data packet.
  Data(DataTrackPacket<E, D>),
  /// An attachment payload.
  Attachment(AttachmentTrackPacket<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(p) => p.track(),
      Self::Audio(p) => p.track(),
      Self::Subtitle(p) => p.track(),
      Self::Data(p) => p.track(),
      Self::Attachment(p) => p.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,
    }
  }
}

// `Clone` / `Debug` are hand-written for the same associated-type
// reason as `TrackParams` and `TrackInfo` above. The five payload
// types this enum carries route through `DemuxAdapter` and its three
// per-kind sub-adapters — `<E::Video as VideoAdapter>::PacketExtra`,
// `<E::Audio as AudioAdapter>::PacketExtra`, `<E::Subtitle as
// SubtitleAdapter>::PacketExtra`, `E::DataExtra`, `E::AttachmentExtra`
// — five independent associated types plus the buffer `D`, none of
// which `#[derive]`'s flat `E: Clone` bound would name.
impl<E, D> Clone for DemuxedPacket<E, D>
where
  E: DemuxAdapter,
  D: Clone,
  <E::Video as VideoAdapter>::PacketExtra: Clone,
  <E::Audio as AudioAdapter>::PacketExtra: Clone,
  <E::Subtitle as SubtitleAdapter>::PacketExtra: Clone,
  E::DataExtra: Clone,
  E::AttachmentExtra: Clone,
{
  fn clone(&self) -> Self {
    match self {
      Self::Video(p) => Self::Video(p.clone()),
      Self::Audio(p) => Self::Audio(p.clone()),
      Self::Subtitle(p) => Self::Subtitle(p.clone()),
      Self::Data(p) => Self::Data(p.clone()),
      Self::Attachment(p) => Self::Attachment(p.clone()),
    }
  }
}

impl<E, D> Debug for DemuxedPacket<E, D>
where
  E: DemuxAdapter,
  D: Debug,
  <E::Video as VideoAdapter>::PacketExtra: Debug,
  <E::Audio as AudioAdapter>::PacketExtra: Debug,
  <E::Subtitle as SubtitleAdapter>::PacketExtra: Debug,
  E::DataExtra: Debug,
  E::AttachmentExtra: Debug,
{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Video(p) => f.debug_tuple("Video").field(p).finish(),
      Self::Audio(p) => f.debug_tuple("Audio").field(p).finish(),
      Self::Subtitle(p) => f.debug_tuple("Subtitle").field(p).finish(),
      Self::Data(p) => f.debug_tuple("Data").field(p).finish(),
      Self::Attachment(p) => f.debug_tuple("Attachment").field(p).finish(),
    }
  }
}

// ---------------------------------------------------------------------------
//  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>];

  /// Moves the whole track table out, once.
  ///
  /// The **owned-tracks door**: [`TrackInfo`] has no `Clone` (see its
  /// own doc), so a caller that needs to hold onto track rows beyond
  /// a borrow of `&self` cannot clone its way to one. This is the
  /// door instead. The **first call** moves every row out and returns
  /// it; after that call, [`tracks`](Self::tracks) answers the empty
  /// slice — the rows are gone, not duplicated. A second call to
  /// `take_tracks` returns an empty `Vec` too, for the same reason.
  ///
  /// The intended caller takes the table exactly once, right after
  /// opening a session and before pulling any packet, and wraps each
  /// row in `Arc` for fan-out to whatever downstream consumers need
  /// their own handle on it — one allocation per track, ever, and
  /// every consumer after that shares by refcount.
  #[cfg(any(feature = "std", feature = "alloc"))]
  #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
  fn take_tracks(&mut self) -> alloc::vec::Vec<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::*;

  // `Vec` is not in the prelude in the alloc-without-std tier (the
  // crate is `#![no_std]` there; the crate-root `alloc`-as-`std` alias
  // only makes `std::`-qualified paths resolve, it does not inject
  // prelude items) — same reason the trait's own `take_tracks` above
  // spells its return type `alloc::vec::Vec`. `format!` needs the same
  // bridge. Unconditional whenever this arm runs: the enclosing `alloc`
  // binding above is gated the same way.
  #[cfg(any(feature = "std", feature = "alloc"))]
  use alloc::{format, vec, vec::Vec};

  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(VideoTrackParams::new(1, 1920, 1080, 7, None)),
        TrackKind::Video,
      ),
      (
        TrackParams::Audio(AudioTrackParams::new(2, 48_000, 2, 3, 4)),
        TrackKind::Audio,
      ),
      (
        TrackParams::Subtitle(SubtitleTrackParams::new(3)),
        TrackKind::Subtitle,
      ),
      (TrackParams::Data(DataTrackParams::new(4)), TrackKind::Data),
      (
        TrackParams::Attachment(AttachmentTrackParams::new(5)),
        TrackKind::Attachment,
      ),
      (
        TrackParams::Unknown(UnknownTrackParams::new(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(AttachmentTrackParams::new(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");
  }

  // `format!` needs an allocator; see the `Vec`/`format!` import note
  // above `VLoop`.
  #[cfg(any(feature = "std", feature = "alloc"))]
  #[test]
  fn data_packet_clone_matches_the_original() {
    let pts = Timestamp::new(1500, ms_tb());
    let original: DataPacket<(), &[u8]> = DataPacket::new(&b"klv"[..], ())
      .with_pts(Some(pts))
      .with_duration(Some(Timestamp::new(40, ms_tb())))
      .with_flags(PacketFlags::KEY);
    let cloned = original.clone();
    assert_eq!(cloned.pts(), original.pts());
    assert_eq!(cloned.duration(), original.duration());
    assert_eq!(cloned.flags(), original.flags());
    assert_eq!(cloned.data(), original.data());
    assert!(format!("{cloned:?}").contains("DataPacket"));
  }

  #[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"[..]);
  }

  // `format!` needs an allocator; see the `Vec`/`format!` import note
  // above `VLoop`.
  #[cfg(any(feature = "std", feature = "alloc"))]
  #[test]
  fn attachment_packet_clone_matches_the_original() {
    let mut original: AttachmentPacket<(), &[u8]> = AttachmentPacket::new(&b"\x00\x01TTF"[..], ());
    original.set_flags(PacketFlags::CORRUPT);
    let cloned = original.clone();
    assert_eq!(cloned.flags(), original.flags());
    assert_eq!(cloned.data(), original.data());
    assert!(format!("{cloned:?}").contains("AttachmentPacket"));
  }

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

  // `format!` needs an allocator; see the `Vec`/`format!` import note
  // above `VLoop`.
  #[cfg(any(feature = "std", feature = "alloc"))]
  #[test]
  fn demuxed_packet_clone_matches_the_original() {
    let track = TrackIndex::new(2);
    let packets: [DemuxedPacket<Loopback, &[u8]>; 5] = [
      DemuxedPacket::Video(VideoTrackPacket::new(track, VideoPacket::new(&[][..], ()))),
      DemuxedPacket::Audio(AudioTrackPacket::new(track, AudioPacket::new(&[][..], ()))),
      DemuxedPacket::Subtitle(SubtitleTrackPacket::new(
        track,
        SubtitlePacket::new(&[][..], ()),
      )),
      DemuxedPacket::Data(DataTrackPacket::new(track, DataPacket::new(&[][..], ()))),
      DemuxedPacket::Attachment(AttachmentTrackPacket::new(
        track,
        AttachmentPacket::new(&[][..], ()),
      )),
    ];
    for packet in packets {
      let cloned = packet.clone();
      assert_eq!(cloned.track(), packet.track());
      assert_eq!(cloned.kind(), packet.kind());
      assert!(!format!("{cloned:?}").is_empty());
    }
  }

  #[test]
  fn demuxed_packet_carries_the_derived_accessor_face() {
    // `IsVariant` / `Unwrap` / `TryUnwrap` — one arm per derive family,
    // proving the house accessor face rides the enum rather than
    // asserting the shape of every variant.
    let track = TrackIndex::new(0);
    let video: DemuxedPacket<Loopback, &[u8]> =
      DemuxedPacket::Video(VideoTrackPacket::new(track, VideoPacket::new(&[][..], ())));
    assert!(video.is_video());
    assert!(!video.is_audio());
    assert_eq!(video.unwrap_video_ref().track(), track);
    assert!(video.try_unwrap_audio().is_err());
  }

  /// Trivial loopback session — proves the trait is implementable and
  /// that its associated types resolve through the adapter bundle.
  ///
  /// `Vec`-backed, so the whole mock (and the two tests that construct
  /// it, below) is gated on the same tier `take_tracks` itself needs —
  /// see the `Vec`/`format!` import note above `VLoop`.
  #[cfg(any(feature = "std", feature = "alloc"))]
  struct LoopDemuxer {
    tracks: Vec<TrackInfo<Loopback>>,
    drained: bool,
  }

  #[cfg(any(feature = "std", feature = "alloc"))]
  #[derive(Debug)]
  struct LoopError;

  #[cfg(any(feature = "std", feature = "alloc"))]
  impl Demuxer for LoopDemuxer {
    type Adapter = Loopback;
    type Buffer = &'static [u8];
    type Error = LoopError;

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

    fn take_tracks(&mut self) -> Vec<TrackInfo<Loopback>> {
      core::mem::take(&mut 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(AudioTrackPacket::new(
        TrackIndex::new(0),
        AudioPacket::new(&[][..], ()),
      ))))
    }

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

  #[cfg(any(feature = "std", feature = "alloc"))]
  #[test]
  fn the_session_face_is_implementable_and_none_means_eof() {
    fn _accepts<D: Demuxer>() {}
    _accepts::<LoopDemuxer>();

    let mut d = LoopDemuxer {
      tracks: vec![TrackInfo::new(
        ms_tb(),
        TrackParams::Audio(AudioTrackParams::new(1, 48_000, 2, 0, 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());
  }

  #[cfg(any(feature = "std", feature = "alloc"))]
  #[test]
  fn take_tracks_moves_every_row_out_once_and_leaves_the_table_empty() {
    let mut d = LoopDemuxer {
      tracks: vec![
        TrackInfo::new(
          ms_tb(),
          TrackParams::Audio(AudioTrackParams::new(1, 48_000, 2, 0, 0)),
          (),
        ),
        TrackInfo::new(
          ms_tb(),
          TrackParams::Subtitle(SubtitleTrackParams::new(2)),
          (),
        ),
      ],
      drained: false,
    };
    let expected: Vec<TrackKind> = d.tracks().iter().map(|t| t.kind()).collect();

    let taken = d.take_tracks();
    assert_eq!(
      taken.iter().map(|t| t.kind()).collect::<Vec<_>>(),
      expected,
      "every row comes out, in table order",
    );
    assert!(
      d.tracks().is_empty(),
      "the table is empty after the first take"
    );

    // The door does not reopen: a second call has nothing left to give.
    assert!(d.take_tracks().is_empty(), "a second take yields nothing");
  }
}