transmux 0.27.3

Any-to-any media container muxing hub: demux TS, fMP4/CMAF, MPEG-PS, WebM, FLV, or RTMP into one neutral IR and mux to CMAF/fMP4, progressive MP4, TS, DASH, low-latency DASH, HLS, low-latency HLS, Smooth Streaming, or RTMP. CENC/CBCS encrypt+decrypt, SSAI splice, RTP/RTCP, and an fMP4/CMAF conformance validator; parses codec config headers only, samples stay opaque. no_std + alloc, except the XML manifest paths (DASH/Smooth/PlayReady), which need the std feature.
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
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
//! CENC/CBCS sample encryption — `CencEncryptor` (issue #564).
//!
//! Applies AES-128 sample protection (`cenc` CTR / `cbcs` CBC-pattern,
//! ISO/IEC 23001-7 §10) to a cleartext [`Media`]'s samples in place,
//! implementing the hub [`broadcast_common::Encrypt`] trait — the inverse of
//! [`crate::cenc_decrypt::CencDecryptor`]'s [`broadcast_common::Decrypt`].
//! Dispatches the actual cipher work to the shared, crate-internal cipher core
//! (the same module the decrypt path uses) and records
//! the resulting per-track/per-sample crypto metadata onto
//! [`crate::media::Track::encryption`] — exactly the shape
//! [`crate::cenc_decrypt::CencDecryptor::from_fmp4`] recovers from an
//! already-protected file (the two are duals).
//!
//! # IV uniqueness is per *key*, for all time
//!
//! AES-CTR (`cenc`) requires every sample ciphered under one content key to
//! use a distinct IV — not just within one [`Encrypt::encrypt`] call, but
//! across *every* call ever made with that key (ISO/IEC 23001-7 §9.2). A
//! [`CencEncryptor`] is therefore a **stateful** value bound to one content
//! key ([`CencEncryptor::new`]): [`IvGen::Counter`]'s running index lives on
//! the encryptor instance, not in [`EncryptConfig`], so calling `encrypt`
//! twice on the *same* instance continues the counter instead of restarting
//! it — reuse *one* instance across every call sharing a key (video-only +
//! audio-only splits of one asset, successive live segments, …). See
//! [`CencEncryptor`]'s own docs for the caller obligation this does and does
//! not enforce.
//!
//! # Subsample map
//!
//! For an AVC/HEVC/VVC (NAL-carried) track under [`SubsamplePolicy::Video`],
//! each length-prefixed NAL unit in a sample ([`crate::annexb::iter_length_prefixed_nals`])
//! contributes one [`crate::cenc::SubSampleEntry`]: the 4-byte length prefix
//! plus the codec's NAL header (1 byte AVC, 2 bytes HEVC/VVC — ITU-T H.264
//! §7.3.1 / H.265 §7.3.1.2 / H.266 §7.3.1.2) is left clear, and the rest of
//! the NAL (its payload) is protected. Any other track, or
//! [`SubsamplePolicy::WholeSample`], protects the whole sample in one range
//! (an empty subsample map — ISO/IEC 23001-7 §9.3, "no subsample structure").
//!
//! # Spec citations
//!
//! - **Sample encryption / subsamples**: ISO/IEC 23001-7 §9.
//! - **AES-CTR (`cenc`) / AES-CBC pattern (`cbcs`)**: ISO/IEC 23001-7 §10 —
//!   see the crate-internal `cenc_crypto` module for the cipher-core citations.
//! - **`tenc`**: ISO/IEC 23001-7 §12.2.
//!
//! This module is gated on the `cenc` feature.

use core::fmt;

use alloc::collections::BTreeSet;
use alloc::vec::Vec;

use broadcast_common::Encrypt;

use crate::annexb::{NAL_LENGTH_SIZE, iter_length_prefixed_nals};
use crate::cenc::{CencScheme, SampleEncryptionEntry, SubSampleEntry, TrackEncryptionBox};
use crate::cenc_crypto::{self, CbcsOp};
use crate::error::{Error, Result};
use crate::media::{Media, TrackEncryption};
use crate::nal::NalCodec;
use crate::pipeline::CodecConfig;

/// Size of a KID / content key / AES-128 key **or block**, in bytes (AES-128's
/// key length and block length coincide).
const KEY_LEN: usize = 16;

/// Per-sample IV size (bytes) for [`IvGen::Counter`] (every counter IV is an
/// 8-byte big-endian value) and the fallback for an empty [`IvGen::Explicit`]
/// list — the common CMAF `cenc` convention (ISO/IEC 23001-7 §12.2 permits 8
/// or 16). [`IvGen::Constant`] derives `16` per sample when
/// [`ConstantIvSenc::Emit`] (the default), or `0` when
/// [`ConstantIvSenc::Omit`] — see [`tenc_iv_fields`].
const PER_SAMPLE_IV_SIZE: u8 = 8;

/// Default `cbcs` pattern (`crypt_byte_block`:`skip_byte_block`) — 1 crypt
/// block then 9 skip blocks, the common CMAF/DASH-IF `cbcs` convention
/// (ISO/IEC 23001-7 §10.2).
const DEFAULT_CBCS_PATTERN: (u8, u8) = (1, 9);

/// Maximum value of a `cbcs` pattern component (`crypt_byte_block` /
/// `skip_byte_block`). `tenc` packs both into a single byte, one nibble each
/// (ISO/IEC 23001-7 §12.2: `(default_crypt_byte_block << 4) |
/// default_skip_byte_block`), so any component above 15 would silently
/// truncate to its low 4 bits on the wire rather than error.
const CBCS_PATTERN_MAX: u8 = 0x0F;

/// Valid per-sample IV lengths for a `senc` entry — ISO/IEC 23001-7 §9.2/§12.2
/// permit exactly 8 or 16 bytes; any other length (including empty) desyncs
/// the AES-CTR/CBC IV derivation from `tenc.default_per_sample_iv_size` and
/// `saiz`'s per-sample aux info size.
const VALID_EXPLICIT_IV_LENS: [usize; 2] = [8, 16];

/// AES block size (16 bytes) as a `u128`, for the AES-CTR counter-range
/// arithmetic ([`assert_ctr_ranges_disjoint`]).
const BLOCK_LEN_U128: u128 = 16;

/// How to derive each sample's initialization vector.
///
/// # IV uniqueness is per *key*, not per track — and not per call
///
/// ISO/IEC 23001-7 §9.2 requires each sample's IV to be unique for the
/// **content key** it is used with. One [`EncryptConfig`] carries one key and
/// is applied to *every* track of the [`Media`], so "unique within this track"
/// is **not** sufficient: under `cenc` (AES-CTR) two samples sharing a key and
/// a counter block produce ciphertexts whose XOR is the XOR of their
/// plaintexts — a two-time pad that discloses both without the key. Every
/// variant below is therefore indexed/counted across the **whole `Media`** of
/// one [`Encrypt::encrypt`] call — and, for [`IvGen::Counter`], across every
/// call ever made on the same [`CencEncryptor`] instance (see that type's
/// docs): uniqueness does not reset just because a second call started.
/// [`CencEncryptor::encrypt`] additionally rejects any duplicate per-sample IV
/// it is about to use, *before* ciphering a single byte.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum IvGen {
    /// Per-sample IV = big-endian `next_counter + sample_index`, where
    /// `sample_index` runs **continuously across every track** of the
    /// [`Media`] in (track, sample) order — it does *not* restart per track
    /// (see this enum's docs: that would reuse one AES-CTR keystream between,
    /// say, video sample *i* and audio sample *i*) — and `next_counter` is
    /// the encrypting [`CencEncryptor`] instance's own running index, which it
    /// advances after every successful call rather than resetting to a
    /// caller-supplied `base` (see that type's docs for why the counter lives
    /// there and not here). The default.
    ///
    /// The IV width is **scheme-dependent** (audit r05-W4): 8 bytes under
    /// [`CencScheme::Cenc`], the common CMAF convention the cipher core
    /// zero-pads to a 16-byte counter block (ISO/IEC 23001-7 §12.2 permits 8
    /// or 16); 16 bytes under [`CencScheme::Cbcs`] — the 64-bit counter in the
    /// low half of a 16-byte big-endian block — because an 8-byte `cbcs`
    /// per-sample IV is the shape Bento4's `mp4decrypt` silently no-ops (see
    /// [`IvGen::Constant`]).
    #[default]
    Counter,
    /// Caller-supplied per-sample IVs, one per sample of the **whole
    /// `Media`**: exactly `media.tracks.iter().map(|t| t.samples.len()).sum()`
    /// entries, consumed in (track, sample) order (track 0's samples first,
    /// then track 1's, …). A list sized to a single track's sample count is
    /// rejected — see this enum's docs for why per-track IV lists are unsafe.
    ///
    /// Each IV must be exactly 8 or 16 bytes (ISO/IEC 23001-7 §9.2/§12.2 — no
    /// other length is valid on the wire, and an empty or otherwise-sized IV
    /// would desync the AES-CTR/CBC derivation), every IV in the list must
    /// have the same length (`tenc.default_per_sample_iv_size` is one value
    /// for the whole track), and no two entries may be equal.
    Explicit(Vec<Vec<u8>>),
    /// A single 16-byte IV shared by every sample of the track, recorded as
    /// `tenc.default_constant_IV` with `default_per_sample_iv_size == 0`
    /// (ISO/IEC 23001-7 §12.2) rather than a per-sample `senc` entry.
    ///
    /// **`cbcs`-only** — [`CencEncryptor::encrypt`] rejects this variant under
    /// [`CencScheme::Cenc`]. A constant IV is fundamentally incompatible with
    /// AES-CTR: the counter block is derived from the IV alone, so every
    /// sample of the track would be encrypted with the *same* keystream, and
    /// the XOR of any two ciphertexts would disclose the XOR of their
    /// plaintexts (a two-time pad) without the key. `cbcs` is not affected the
    /// same way — its AES-CBC chain is seeded from the IV but every block's
    /// input then depends on the preceding ciphertext, so identical plaintext
    /// blocks in different samples do not yield a recoverable keystream.
    ///
    /// The standard `cbcs` convention — real `cbcs` deployments overwhelmingly
    /// use a constant IV (confirmed against Bento4's `mp4encrypt`, which always
    /// emits one for `cbcs` regardless of the `--key` IV given it), and
    /// Bento4's `mp4decrypt` requires it (or a genuine 16-byte per-sample IV)
    /// to actually decrypt `cbcs` — an 8-byte per-sample IV silently no-ops.
    Constant([u8; KEY_LEN]),
}

pub use super::cenc::ConstantIvSenc;

/// How the protected byte ranges (subsample map) of each sample are chosen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SubsamplePolicy {
    /// NAL-aware: for AVC/HEVC/VVC tracks, clear the length-prefix + NAL
    /// header of every NAL unit and protect the remainder (see the module
    /// docs); any other track falls back to whole-sample protection.
    Video,
    /// Protect every sample in full (no subsample structure).
    WholeSample,
}

/// Configuration for [`CencEncryptor::encrypt`].
///
/// Does **not** carry the content key: the key lives on the [`CencEncryptor`]
/// instance itself ([`CencEncryptor::new`]), since one encryptor is bound to
/// one key for its whole lifetime (see that type's docs) — a per-call `key`
/// field here would let a caller silently pair one running [`IvGen::Counter`]
/// with a *different* key from call to call, which is exactly backwards.
#[derive(Debug, Clone)]
pub struct EncryptConfig {
    /// The protection scheme to apply (`cenc` AES-CTR or `cbcs` AES-CBC
    /// pattern).
    pub scheme: CencScheme,
    /// The 16-byte Key ID recorded in `tenc.default_KID`.
    pub kid: [u8; KEY_LEN],
    /// How each sample's IV is derived. Defaults to [`IvGen::Counter`].
    pub iv: IvGen,
    /// `cbcs` pattern (`crypt_byte_block`, `skip_byte_block`); defaults to
    /// `1:9` when `None`. Ignored for `cenc`.
    pub pattern: Option<(u8, u8)>,
    /// How the subsample map is chosen.
    pub subsample: SubsamplePolicy,
    /// Whether to emit a `senc` box for `cbcs` + [`IvGen::Constant`] tracks
    /// (default: [`ConstantIvSenc::Emit`] — emits a `senc` with the constant
    /// IV replicated in each sample entry for maximum decryptor interop).
    /// See [`ConstantIvSenc`] for the rationale and the opt-out shape.
    pub constant_iv_senc: ConstantIvSenc,
}

/// Applies CENC/CBCS sample protection to a [`Media`], implementing
/// [`Encrypt`] — the inverse of [`crate::cenc_decrypt::CencDecryptor`].
///
/// # Bound to one key, for the life of the instance
///
/// AES-CTR IV uniqueness is a property of the **key**, not of any one
/// `encrypt` call (see the module docs and [`IvGen`]'s). A `CencEncryptor` is
/// therefore constructed with its content key ([`CencEncryptor::new`]) and
/// carries the running [`IvGen::Counter`] index as its own state, advancing
/// it after every successful `encrypt` rather than restarting at a
/// caller-supplied base each time — reuse *one* instance across every call
/// that shares a key (e.g. a video-only pass then an audio-only pass over the
/// same asset, or successive segments of one live key period).
///
/// This closes the two-time-pad this type previously permitted when used as
/// a stateless, `Default`-constructed unit value (fixed in 0.20.0): calling
/// `CencEncryptor::new(key).encrypt(...)` a second time for a *different*
/// call that shares `key` used to restart the counter at the config's `base`,
/// silently reproducing the exact keystream-reuse defect this type exists to
/// prevent within one call.
///
/// **What this does not (and structurally cannot) enforce**: constructing
/// *two* separate `CencEncryptor::new(key)` instances with the *same* `key`
/// still collides — each starts its own counter at 0 — because the type has
/// no way to know another instance ever used `key` before. Reusing one
/// instance's counter, never re-deriving a "fresh" one for a key already in
/// use, is the caller's obligation; [`CencEncryptor::resume`] exists for the
/// one legitimate case that looks like a fresh instance (recovering
/// in-process state across e.g. a process restart, from a persisted
/// `next_counter()`).
pub struct CencEncryptor {
    /// The AES-128 content key every `encrypt` call on this instance uses.
    key: [u8; KEY_LEN],
    /// The next [`IvGen::Counter`] value this instance will hand out — the
    /// running index described above. Unused (and unadvanced) by
    /// [`IvGen::Explicit`]/[`IvGen::Constant`] calls.
    next_counter: u64,
}

/// Manual `Debug`: redacts the bound content key (a derived `Debug` would
/// print it verbatim — a `tracing::debug!`/`dbg!`/panic message of a value
/// holding a `CencEncryptor` would then write the live content key to logs).
impl fmt::Debug for CencEncryptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CencEncryptor")
            .field("key", &"<redacted>")
            .field("next_counter", &self.next_counter)
            .finish()
    }
}

/// Wipe the bound content key on drop (issue #1142).
impl Drop for CencEncryptor {
    fn drop(&mut self) {
        use zeroize::Zeroize;
        self.key.zeroize();
    }
}

impl CencEncryptor {
    /// Construct a fresh encryptor bound to `key`, with its
    /// [`IvGen::Counter`] index starting at `0`.
    ///
    /// Reuse the returned value across every `encrypt` call that shares
    /// `key` — see this type's docs for why constructing a second
    /// `CencEncryptor::new(key)` with the same `key` reintroduces the
    /// two-time pad this type exists to prevent.
    pub fn new(key: [u8; KEY_LEN]) -> Self {
        Self {
            key,
            next_counter: 0,
        }
    }

    /// Construct an encryptor bound to `key`, resuming its [`IvGen::Counter`]
    /// index at `next_counter` instead of `0`.
    ///
    /// For recovering an in-process encryptor's state across a boundary that
    /// doesn't preserve the Rust value itself (e.g. a process restart in a
    /// live-streaming pipeline) from a previously observed
    /// [`CencEncryptor::next_counter`] — **not** a substitute for reusing one
    /// instance in the common case, and not a safe way to "pick up" someone
    /// else's counter unless `next_counter` is known to be past every IV that
    /// instance ever produced for `key`.
    pub fn resume(key: [u8; KEY_LEN], next_counter: u64) -> Self {
        Self { key, next_counter }
    }

    /// The next [`IvGen::Counter`] value this instance will hand out.
    /// Snapshot this (alongside the key, out of band) to reconstruct
    /// equivalent state later via [`CencEncryptor::resume`].
    pub fn next_counter(&self) -> u64 {
        self.next_counter
    }

    /// The per-sample IV width (bytes) [`IvGen::Counter`] emits under
    /// `scheme` — 8 under [`CencScheme::Cenc`], 16 under
    /// [`CencScheme::Cbcs`].
    ///
    /// The split is deliberate (audit r05-W4). Under `cenc` the IV is the
    /// AES-CTR counter block, and the 8-byte form is the common CMAF
    /// convention (ISO/IEC 23001-7 §12.2 permits 8 or 16); a 16-byte counter
    /// there would also make the counter-range arithmetic in
    /// [`assert_ctr_ranges_disjoint`] easier for callers to get wrong, since
    /// the whole IV is the counter. Under `cbcs` the IV seeds a CBC chain, and
    /// this module's own [`IvGen::Constant`] doc records that Bento4's
    /// `mp4decrypt` requires a constant IV **or a genuine 16-byte per-sample
    /// IV** — an 8-byte per-sample IV silently no-ops there. So the default
    /// `EncryptConfig { scheme: Cbcs, iv: IvGen::default(), .. }` now emits
    /// 16-byte counter IVs instead of the 8-byte shape that decrypts to
    /// nothing on the reference tool.
    const fn counter_iv_size(scheme: CencScheme) -> usize {
        match scheme {
            CencScheme::Cenc => PER_SAMPLE_IV_SIZE as usize,
            // `CencScheme::Cbcs` and any future scheme: `cbcs` is the only
            // other scheme this crate ciphers (an unknown one is rejected in
            // `Encrypt::encrypt` before this is used), and 16 bytes is the
            // safe width there.
            _ => KEY_LEN,
        }
    }
}

impl Encrypt for CencEncryptor {
    type Media = Media;
    type Config = EncryptConfig;
    type Error = Error;

    /// Encrypt every track's samples in `media` in place per `cfg`, recording
    /// the resulting crypto metadata onto each [`crate::media::Track::encryption`].
    ///
    /// `cfg` (scheme/KID/IV mode/pattern/subsample policy) is applied
    /// uniformly to every track in `media`, ciphered with `self`'s bound
    /// content key. Because that one key covers every track — and, for
    /// [`IvGen::Counter`], every call ever made on `self` (see
    /// [`CencEncryptor`]'s docs) — the per-sample IV must be unique across
    /// all of it (ISO/IEC 23001-7 §9.2). This method enforces that in two
    /// phases, fully separated so the second can never run against stale or
    /// drifted data:
    ///
    /// 1. **Plan, then validate — before ciphering anything.** An internal
    ///    validation pass checks [`IvGen::Explicit`]'s count/length and
    ///    [`IvGen::Counter`]'s overflow bound; an internal planning pass then
    ///    resolves the *exact* IV every sample of `media` will use (in
    ///    (track, sample) order, continuously across tracks); a final
    ///    internal check rejects that plan outright if it contains any
    ///    duplicate. The same planning phase also walks every sample's NAL
    ///    structure into its subsample map (`plan_subsamples`),
    ///    so a malformed length prefix is rejected here too — never mid-cipher.
    ///    Only a plan that passes is ever handed to the cipher —
    ///    the same values, not a value recomputed afterwards that could
    ///    drift from what was checked.
    /// 2. **Cipher from the validated plan.** The main loop consumes
    ///    `plan[track][sample]` directly to build each
    ///    [`crate::cenc::SampleEncryptionEntry`] and to seed the cipher core —
    ///    it never calls IV resolution or sample-structure walking again, so
    ///    nothing that depends on a sample's contents can fail once the first
    ///    byte has been written.
    ///
    /// A configuration this rejects — at either phase — leaves `media`
    /// byte-identical to its input: no track's samples are touched, and no
    /// `Track::encryption` is populated, until the *whole* plan is proven
    /// duplicate-free. This is the fix for the original backstop's timing
    /// bug: a check with the same purpose used to run only after every track
    /// had already been keystreamed in place, so a reintroduced per-track
    /// index reset (the original vulnerability) rejected the config but left
    /// `media` two-time-padded with no rollback.
    ///
    /// [`IvGen::Constant`] is rejected outright under [`CencScheme::Cenc`] (a
    /// constant AES-CTR counter is a keystream repeat by construction), also
    /// before anything else is validated or touched.
    fn encrypt(&mut self, media: &mut Media, cfg: &EncryptConfig) -> Result<()> {
        if cfg.scheme == CencScheme::Cenc && matches!(cfg.iv, IvGen::Constant(_)) {
            return Err(Error::InvalidInput(
                "IvGen::Constant is cbcs-only: a constant IV under cenc (AES-CTR) derives one \
                 counter block for every sample, reusing a single keystream (two-time pad)",
            ));
        }
        let pattern = match cfg.scheme {
            CencScheme::Cbcs => {
                let p = cfg.pattern.unwrap_or(DEFAULT_CBCS_PATTERN);
                if p.0 > CBCS_PATTERN_MAX || p.1 > CBCS_PATTERN_MAX {
                    return Err(Error::InvalidInput(
                        "cbcs pattern block counts must each be 0..=15",
                    ));
                }
                // The cipher core's `crypt_byte_block == 0 && skip_byte_block != 0`
                // precondition folded into this up-front check (see
                // `cenc_crypto::cbcs_sample`): rejecting it here keeps the
                // cipher loop free of any config-dependent failure too, not
                // just content-dependent ones.
                if p.0 == 0 && p.1 != 0 {
                    return Err(Error::InvalidInput(
                        "cbcs pattern crypt_byte_block=0 with nonzero skip leaves data unprotected",
                    ));
                }
                p
            }
            CencScheme::Cenc => (0, 0),
            // `CencScheme` is `#[non_exhaustive]` (and now defined in
            // `broadcast-common`): reject a scheme this crate has no cipher
            // for rather than silently encrypting under the wrong one.
            other => return Err(Error::UnsupportedCencScheme { scheme: other }),
        };
        let (per_sample_iv_size, default_constant_iv) =
            tenc_iv_fields(cfg.scheme, &cfg.iv, cfg.constant_iv_senc)?;
        let tenc = TrackEncryptionBox {
            // `cbcs` pattern fields only carry meaning under version 1
            // (ISO/IEC 23001-7 §12.2); `cenc` has no pattern, so version 0.
            version: if cfg.scheme == CencScheme::Cbcs { 1 } else { 0 },
            default_crypt_byte_block: pattern.0,
            default_skip_byte_block: pattern.1,
            default_is_protected: 1,
            default_per_sample_iv_size: per_sample_iv_size,
            default_kid: cfg.kid,
            default_constant_iv,
        };

        // IV uniqueness spans the whole `Media` (and, for `Counter`, every
        // prior call on `self`), so every count/length/overflow check is
        // done up front, before the first sample is ciphered — a rejected
        // config leaves `media` untouched rather than half-encrypted.
        let total_samples: usize = media.tracks.iter().map(|t| t.samples.len()).sum();
        self.validate_iv_gen(&cfg.iv, total_samples)?;

        // F1 fix: resolve the *entire* planned (track, sample) -> IV mapping
        // first, and validate that plan for duplicates before a single
        // sample is touched. The main loop below then consumes this exact
        // plan (never re-resolving), so what was validated and what gets
        // recorded/ciphered can never drift apart.
        let plan = self.plan_sample_ivs(media, cfg.scheme, &cfg.iv, cfg.constant_iv_senc)?;
        assert_ivs_unique(&plan, &cfg.iv, cfg.constant_iv_senc)?;

        // Walk every sample's NAL structure into its subsample map *now*,
        // before a single byte is written. This was the last content-dependent
        // failure left inside the cipher loop: a bad length prefix on sample
        // `k` used to return `Err` after samples `0..k` had already been
        // keystreamed in place, contradicting this method's documented promise.
        let subsample_plan = Self::plan_subsamples(media, cfg.subsample)?;

        // Under `cenc` the IV *is* the AES-CTR counter block, so uniqueness of
        // the IVs alone is not enough: a sample consumes a *range* of counter
        // blocks (`iv .. iv + ceil(protected_len/16) - 1`), and two such ranges
        // must never intersect (ISO/IEC 23001-7 §10.1). A sequential IV list
        // passes the equality check yet overlaps. Checked here, on the planned
        // IV + subsample sequences, so a rejection still leaves `media`
        // byte-identical.
        let sample_lens = media
            .tracks
            .iter()
            .flat_map(|t| t.samples.iter().map(|s| s.data.len()));
        assert_ctr_ranges_disjoint(cfg.scheme, &plan, &subsample_plan, sample_lens)?;

        for ((track, track_ivs), track_subs) in
            media.tracks.iter_mut().zip(plan).zip(subsample_plan)
        {
            let sample_count = track.samples.len();
            let mut entries = Vec::with_capacity(sample_count);

            // Consume the two validated plans by value — the exact IVs and
            // subsample maps planned above, moved into their entries (never
            // recomputed), so nothing here can fail on a sample's contents.
            for (sample, (iv, subsamples)) in track
                .samples
                .iter_mut()
                .zip(track_ivs.into_iter().zip(track_subs))
            {
                let entry = SampleEncryptionEntry {
                    initialization_vector: iv,
                    subsamples,
                };

                match cfg.scheme {
                    CencScheme::Cenc => cenc_crypto::rewrite_in_place(&mut sample.data, |buf| {
                        cenc_crypto::apply_ctr(
                            &entry.initialization_vector,
                            &self.key,
                            &entry.subsamples,
                            buf,
                        )
                    })?,
                    CencScheme::Cbcs => cenc_crypto::rewrite_in_place(&mut sample.data, |buf| {
                        cenc_crypto::cbcs_sample(&tenc, &entry, &self.key, buf, CbcsOp::Encrypt)
                    })?,
                    // Unreachable in practice: the same scheme was already
                    // validated at the top of `encrypt`. Kept as an error (not
                    // `unreachable!`) so a future scheme added to
                    // `broadcast-common` can never turn this into a panic.
                    other => return Err(Error::UnsupportedCencScheme { scheme: other }),
                };

                entries.push(entry);
            }

            debug_assert_eq!(entries.len(), sample_count);
            track.encryption = Some(TrackEncryption {
                scheme: cfg.scheme,
                tenc: tenc.clone(),
                samples: entries,
                constant_iv_senc: cfg.constant_iv_senc,
            });
        }

        // Only `IvGen::Counter` consumes `self`'s running index; a
        // successful call using it must never hand out any of these IVs
        // again, from any future call on `self` (see this type's docs) — the
        // overflow this could hit was already proven impossible by
        // `validate_iv_gen` above, using the same starting point.
        if matches!(cfg.iv, IvGen::Counter) {
            self.next_counter += total_samples as u64;
        }
        Ok(())
    }
}

impl CencEncryptor {
    /// Validate an [`IvGen`] against the total sample count of the whole
    /// [`Media`], before any sample is ciphered or planned.
    ///
    /// Checks (a) that [`IvGen::Explicit`] carries exactly one IV per sample
    /// of the *whole* `Media` — not per track (ISO/IEC 23001-7 §9.2:
    /// uniqueness is per key, and one key covers every track), (b) that each
    /// IV it will hand the cipher is a valid length, and (c) that no two IVs
    /// are equal, and — for [`IvGen::Counter`] — that continuing `self`'s
    /// running index across `total_samples` more samples cannot overflow.
    /// Doing this up-front keeps `encrypt` atomic for the whole class of IV
    /// misconfiguration: a rejected config never leaves a partially-encrypted
    /// `Media` behind.
    ///
    /// [`IvGen::Counter`] needs no duplicate set here: `next_counter + idx`
    /// with a `checked_add` guard is strictly increasing, hence
    /// collision-free by construction within this call — [`assert_ivs_unique`]
    /// is the backstop that catches a future regression in that construction
    /// (e.g. a reintroduced per-track reset) rather than trusting the math
    /// alone. [`IvGen::Constant`] carries no per-sample IV at all (it lives
    /// once in `tenc.default_constant_IV`), and is `cbcs`-only — where the CBC
    /// chain, not a keystream, depends on it (see [`IvGen::Constant`]).
    fn validate_iv_gen(&self, iv_gen: &IvGen, total_samples: usize) -> Result<()> {
        match iv_gen {
            IvGen::Counter => {
                // Surface the overflow up-front rather than mid-pass.
                let last = total_samples.saturating_sub(1) as u64;
                self.next_counter
                    .checked_add(last)
                    .ok_or(Error::InvalidInput(
                        "CENC IV counter overflow (next_counter + sample_index)",
                    ))?;
                Ok(())
            }
            IvGen::Explicit(ivs) => {
                if ivs.len() != total_samples {
                    return Err(Error::InvalidInput(
                        "IvGen::Explicit must supply exactly one IV per sample of the whole Media \
                         (the sum of every track's sample count), consumed in (track, sample) order — \
                         one content key covers every track, so IV uniqueness is per key, not per track",
                    ));
                }
                let mut seen: BTreeSet<&[u8]> = BTreeSet::new();
                for iv in ivs {
                    if !VALID_EXPLICIT_IV_LENS.contains(&iv.len()) {
                        return Err(Error::InvalidInput(
                            "CENC per-sample IV must be 8 or 16 bytes",
                        ));
                    }
                    if !seen.insert(iv.as_slice()) {
                        return Err(Error::InvalidInput(
                            "duplicate IvGen::Explicit per-sample IV: an IV must be unique per \
                             content key (ISO/IEC 23001-7 §9.2) — reusing one under cenc (AES-CTR) \
                             reuses its keystream (two-time pad)",
                        ));
                    }
                }
                Ok(())
            }
            IvGen::Constant(_) => Ok(()),
        }
    }

    /// Resolve the **entire** planned per-sample IV sequence for `media`
    /// under `iv_gen`, in (track, sample) order, continuously across tracks —
    /// the exact values [`Encrypt::encrypt`] will go on to record and cipher
    /// with, computed *before* it ciphers anything.
    ///
    /// This is the data [`assert_ivs_unique`] validates and the main cipher
    /// loop consumes directly (never re-resolved), so there is no window in
    /// which what was checked for uniqueness can differ from what gets used.
    fn plan_sample_ivs(
        &self,
        media: &Media,
        scheme: CencScheme,
        iv_gen: &IvGen,
        constant_iv_senc: ConstantIvSenc,
    ) -> Result<Vec<Vec<Vec<u8>>>> {
        let mut media_sample_idx = 0usize;
        let mut plan = Vec::with_capacity(media.tracks.len());
        for track in &media.tracks {
            let mut track_ivs = Vec::with_capacity(track.samples.len());
            for _ in &track.samples {
                track_ivs.push(self.resolve_iv(
                    scheme,
                    iv_gen,
                    media_sample_idx,
                    constant_iv_senc,
                )?);
                media_sample_idx += 1;
            }
            plan.push(track_ivs);
        }
        Ok(plan)
    }

    /// Build the **entire** planned subsample-map sequence for `media`, in
    /// (track, sample) order — the exact maps [`Encrypt::encrypt`] will go on
    /// to record and cipher with, computed *before* it ciphers anything.
    ///
    /// This is what makes a rejection on malformed NAL data atomic: walking
    /// each sample's length prefixes used to happen inside the cipher loop, so
    /// a bad prefix on sample `k` returned `Err` after samples `0..k` had
    /// already been keystreamed in place — leaving `media` half-encrypted and
    /// contradicting that method's documented promise. Computing every map up
    /// front moves the last content-dependent failure out of the cipher loop:
    /// once planning succeeds, nothing there can fail on what a sample
    /// contains.
    fn plan_subsamples(
        media: &Media,
        subsample: SubsamplePolicy,
    ) -> Result<Vec<Vec<Vec<SubSampleEntry>>>> {
        media
            .tracks
            .iter()
            .map(|track| {
                let nal_codec = nal_codec_for(&track.spec.config);
                track
                    .samples
                    .iter()
                    .map(|sample| match (subsample, nal_codec) {
                        (SubsamplePolicy::Video, Some(codec)) => {
                            nal_subsamples(codec, &sample.data)
                        }
                        _ => Ok(Vec::new()),
                    })
                    .collect()
            })
            .collect()
    }

    /// Resolve the per-sample `senc` IV for `idx` — the sample's index within
    /// the **whole [`Media`]** (see [`IvGen`]), not within its track — from
    /// the configured [`IvGen`].
    ///
    /// Assumes [`Self::validate_iv_gen`] has already checked the list length,
    /// IV lengths, and overflow bound for this `Media`; the length/overflow
    /// guards here are kept as a belt-and-braces second line, never the only
    /// one. [`IvGen::Constant`] returns the 16-byte constant IV when
    /// `constant_iv_senc` is [`ConstantIvSenc::Emit`] (the default —
    /// recorded per-sample in `senc`), or an empty IV when
    /// [`ConstantIvSenc::Omit`] (the spec-minimal shape where the IV lives
    /// only in `tenc.default_constant_IV`).
    ///
    /// [`IvGen::Counter`]'s width is **scheme-dependent** (see
    /// [`Self::counter_iv_size`]): 8 bytes under `cenc`, 16 under `cbcs`, so a
    /// default `cbcs` config does not emit the 8-byte per-sample IV that
    /// Bento4 `mp4decrypt` silently no-ops (audit r05-W4).
    fn resolve_iv(
        &self,
        scheme: CencScheme,
        iv_gen: &IvGen,
        idx: usize,
        constant_iv_senc: ConstantIvSenc,
    ) -> Result<Vec<u8>> {
        match iv_gen {
            IvGen::Counter => {
                let v = self
                    .next_counter
                    .checked_add(idx as u64)
                    .ok_or(Error::InvalidInput(
                        "CENC IV counter overflow (next_counter + sample_index)",
                    ))?;
                if Self::counter_iv_size(scheme) == PER_SAMPLE_IV_SIZE as usize {
                    // 8-byte counter IV: the common `cenc` CMAF convention.
                    Ok(v.to_be_bytes().to_vec())
                } else {
                    // 16-byte counter IV (`cbcs`): the 64-bit counter in the
                    // low half of a 16-byte big-endian block, zero in the high
                    // half — a genuine 16-byte per-sample IV, which is what a
                    // `cbcs` decryptor requires.
                    Ok(u128::from(v).to_be_bytes().to_vec())
                }
            }
            IvGen::Explicit(ivs) => {
                let iv = ivs.get(idx).ok_or(Error::InvalidInput(
                    "IvGen::Explicit must supply exactly one IV per sample of the whole Media",
                ))?;
                if !VALID_EXPLICIT_IV_LENS.contains(&iv.len()) {
                    return Err(Error::InvalidInput(
                        "CENC per-sample IV must be 8 or 16 bytes",
                    ));
                }
                Ok(iv.clone())
            }
            IvGen::Constant(iv) => match constant_iv_senc {
                ConstantIvSenc::Emit => Ok(iv.to_vec()),
                ConstantIvSenc::Omit => Ok(Vec::new()),
            },
        }
    }
}

/// Reject any duplicate per-sample IV anywhere in a **planned** IV sequence
/// (see [`CencEncryptor::plan_sample_ivs`]) — called *before* a single sample
/// is ciphered.
///
/// [`CencEncryptor::validate_iv_gen`] already rejects the reachable
/// misconfigurations, so this can only fire if the plan-generation bookkeeping
/// itself is wrong (e.g. a per-track index reset — the original defect). It is
/// deliberately a check on the planned *output* rather than trusting the
/// generator's math: that makes the whole class of keystream-reuse bug
/// impossible to reintroduce silently, instead of fixing one instance of it —
/// and, because the plan is the same data the cipher loop then consumes
/// unmodified, a rejection here happens strictly before `media` is touched.
/// Cost is one `BTreeSet` of borrowed slices (no IV is cloned).
///
/// [`IvGen::Constant`] IVs are skipped: when
/// [`ConstantIvSenc::Emit`](super::ConstantIvSenc::Emit) every entry carries
/// the same constant IV by design (the duplicate check would be a false
/// positive), and when [`ConstantIvSenc::Omit`](super::ConstantIvSenc::Omit)
/// every entry is empty (there is no per-sample IV at all). Every other
/// `IvGen` + `constant_iv_senc` combination is checked — including `cenc` +
/// `Counter` with `Emit` set, where the short-circuit is intentionally NOT
/// applied: `Emit` only makes sense with `cbcs`+`Constant`, and a future
/// regression that introduces duplicates on a `cenc`/`Counter` path must
/// still be caught by this backstop.
fn assert_ivs_unique(
    plan: &[Vec<Vec<u8>>],
    iv_gen: &IvGen,
    constant_iv_senc: ConstantIvSenc,
) -> Result<()> {
    // Only skip the check for the one combination where repetition is by
    // design: cbcs with a constant IV being replicated into every entry.
    if matches!(iv_gen, IvGen::Constant(_)) && matches!(constant_iv_senc, ConstantIvSenc::Emit) {
        return Ok(());
    }
    let mut seen: BTreeSet<&[u8]> = BTreeSet::new();
    for track_ivs in plan {
        for iv in track_ivs {
            if iv.is_empty() {
                continue;
            }
            if !seen.insert(iv.as_slice()) {
                return Err(Error::InvalidInput(
                    "duplicate CENC per-sample IV planned across the Media's tracks: an IV must \
                     be unique per content key (ISO/IEC 23001-7 §9.2), and one CencEncryptor key \
                     covers every track — reuse under cenc (AES-CTR) is a two-time pad",
                ));
            }
        }
    }
    Ok(())
}

/// The number of AES-CTR counter blocks a sample consumes: one per 16 protected
/// bytes, across the concatenated *protected* ranges (clear ranges are skipped
/// and never advance the counter — see [`cenc_crypto::apply_ctr`]).
///
/// When the subsample map is empty the whole sample is protected, so the count
/// is `ceil(sample_len / 16)`. Returns `None` when the count does not fit a
/// `u128`, which cannot happen for a real sample but keeps the arithmetic
/// total.
fn protected_block_count(sample_len: usize, subsamples: &[SubSampleEntry]) -> Option<u128> {
    let protected: u128 = if subsamples.is_empty() {
        sample_len as u128
    } else {
        subsamples.iter().try_fold(0u128, |acc, s| {
            acc.checked_add(s.bytes_of_protected_data as u128)
        })?
    };
    // ceil(protected / 16)
    protected
        .checked_add(BLOCK_LEN_U128 - 1)
        .map(|v| v / BLOCK_LEN_U128)
}

/// One AES-CTR counter-block range covered by a planned sample: the counter
/// block (the per-sample IV left-justified and zero-padded to 16 bytes,
/// big-endian) through the last block the sample consumes.
#[derive(Debug, Clone, Copy)]
struct CtrRange {
    start: u128,
    end: u128,
}

/// Reject planned `cenc` (AES-CTR) counter-block ranges that overlap.
///
/// [`assert_ivs_unique`] compares IVs for *equality only*, which is not the
/// property that matters under `cenc`: the CENC counter block **is** the IV,
/// zero-padded to 16 bytes, and `Ctr128BE` increments the full 128-bit block
/// once per 16-byte cipher block (ISO/IEC 23001-7 §10.1). Sample *i* therefore
/// consumes counters `iv_i .. iv_i + blocks_i - 1`, so the natural sequential
/// list `base + i` — every adjacent pair a distinct, "unique" IV — reuses
/// sample *i*'s second keystream block as sample *i+1*'s first whenever a
/// sample is longer than one block. That is a two-time pad across every
/// consecutive pair, and it is exactly what a caller assembling IVs as
/// `base + i` reaches.
///
/// `cbcs` is exempt: its IV seeds a CBC chain per protected block (the IV is
/// not a counter), so a shifted IV is not keystream reuse.
///
/// Runs on the *planned* IV + subsample sequences, before any sample is
/// ciphered, so a rejection leaves `media` byte-identical.
fn assert_ctr_ranges_disjoint(
    scheme: CencScheme,
    plan: &[Vec<Vec<u8>>],
    subsample_plan: &[Vec<Vec<SubSampleEntry>>],
    sample_lens: impl Iterator<Item = usize>,
) -> Result<()> {
    if scheme != CencScheme::Cenc {
        return Ok(());
    }
    let mut sample_lens = sample_lens;
    let mut ranges: Vec<CtrRange> = Vec::new();
    for (track_ivs, track_subs) in plan.iter().zip(subsample_plan) {
        for (iv, subs) in track_ivs.iter().zip(track_subs) {
            // Every sample has an entry: the two plans were built one per
            // sample, in the same (track, sample) order.
            let len = sample_lens.next().ok_or(Error::InvalidInput(
                "CENC sample-length iterator shorter than the planned sample count",
            ))?;
            if iv.is_empty() {
                // `apply_ctr` rejects an empty IV itself (no counter block to
                // derive); nothing to range-check here.
                continue;
            }
            let mut counter = [0u8; KEY_LEN];
            counter[..iv.len()].copy_from_slice(iv);
            let start = u128::from_be_bytes(counter);
            let blocks = protected_block_count(len, subs).ok_or(Error::InvalidInput(
                "CENC protected byte count overflows the u128 counter space",
            ))?;
            // A sample that protects no whole block (a subsample map whose
            // protected bytes are all in a partial tail, or an empty sample)
            // consumes no keystream, so it cannot collide with anything — skip
            // it rather than give it a degenerate zero-width range (which the
            // overlap test below would also treat as harmless, but skipping
            // keeps the list minimal and the intent explicit).
            if blocks == 0 {
                continue;
            }
            let end = start.checked_add(blocks).ok_or(Error::InvalidInput(
                "CENC AES-CTR counter block range overflows 128 bits (iv + protected blocks)",
            ))?;
            ranges.push(CtrRange { start, end });
        }
    }
    // Sort by start, then reject any overlap with the previous end. Sorting
    // keeps this O(n log n) for a whole-Media plan rather than O(n²).
    ranges.sort_unstable_by_key(|r| r.start);
    for pair in ranges.windows(2) {
        if pair[1].start < pair[0].end {
            return Err(Error::InvalidInput(
                "overlapping CENC AES-CTR counter-block ranges: under cenc the per-sample IV is \
                 the 128-bit counter block and the counter advances once per 16-byte protected \
                 block (ISO/IEC 23001-7 §10.1), so a sequential IV list such as base+i reuses \
                 sample i's later keystream blocks as sample i+1's first (a two-time pad). Space \
                 the IVs by at least the previous sample's protected block count",
            ));
        }
    }
    Ok(())
}

/// Map a track's codec config to the NAL-header layout used to build its
/// subsample map, or `None` for a track this encryptor cannot walk as NAL
/// units (audio, or any other non-NAL-carried codec) — such tracks always
/// fall back to whole-sample protection regardless of [`SubsamplePolicy`].
fn nal_codec_for(config: &CodecConfig) -> Option<NalCodec> {
    match config {
        CodecConfig::Avc { .. } => Some(NalCodec::Avc),
        CodecConfig::Hevc { .. } => Some(NalCodec::Hevc),
        CodecConfig::Vvc { .. } => Some(NalCodec::Vvc),
        _ => None,
    }
}

/// Build a NAL-aware subsample map for one sample's length-prefixed NAL data:
/// each NAL's 4-byte length prefix + `codec`'s NAL header is clear, and the
/// remainder of the NAL (its payload) is protected — one
/// [`SubSampleEntry`] per NAL unit (ISO/IEC 23001-7 §9.3).
fn nal_subsamples(codec: NalCodec, data: &[u8]) -> Result<Vec<SubSampleEntry>> {
    let header_len: usize = match codec {
        NalCodec::Avc => 1,
        NalCodec::Hevc | NalCodec::Vvc => 2,
    };
    let nals = iter_length_prefixed_nals(data)?;
    let mut out = Vec::with_capacity(nals.len());
    for nal in nals {
        // A NAL too short to carry its own header (should not occur in a
        // well-formed stream) is left entirely clear rather than under- or
        // over-running the header boundary.
        let clear_header = header_len.min(nal.len());
        out.push(SubSampleEntry {
            bytes_of_clear_data: (NAL_LENGTH_SIZE + clear_header) as u16,
            bytes_of_protected_data: (nal.len() - clear_header) as u32,
        });
    }

    let total: usize = out
        .iter()
        .map(|s| s.bytes_of_clear_data as usize + s.bytes_of_protected_data as usize)
        .sum();
    if total != data.len() {
        return Err(Error::InvalidInput(
            "NAL subsample map does not cover the whole sample",
        ));
    }
    Ok(out)
}

/// Derive `tenc`'s `(default_per_sample_iv_size, default_constant_IV)` pair
/// from the chosen [`IvGen`] and [`ConstantIvSenc`] choice (ISO/IEC 23001-7 §12.2):
///
/// - [`IvGen::Constant`] + [`ConstantIvSenc::Emit`]: `default_per_sample_iv_size = 16`,
///   `default_constant_IV = Some(iv)` — the constant IV is carried in both
///   `tenc` and replicated into every `senc` entry (the default for maximum
///   interop).
/// - [`IvGen::Constant`] + [`ConstantIvSenc::Omit`]: `default_per_sample_iv_size = 0`,
///   `default_constant_IV = Some(iv)` — the spec-minimal, `tenc`-only shape
///   (no `senc`/`saiz`/`saio`).
/// - [`IvGen::Counter`]: `default_per_sample_iv_size` is
///   [`CencEncryptor::counter_iv_size`] of the scheme — 8 under `cenc`
///   (every counter IV is an 8-byte big-endian value), 16 under `cbcs`
///   (a genuine 16-byte per-sample IV is what a `cbcs` decryptor requires;
///   see that method) — no constant IV.
/// - [`IvGen::Explicit`]: `default_per_sample_iv_size` is the shared length of
///   every supplied IV (checked uniform here, since the wire format has only
///   one track-wide size — a per-sample length mismatch would otherwise
///   silently desync `senc`'s IV field width from `saiz`'s per-sample aux
///   size), no constant IV. That shared length is also validated here to be
///   exactly 8 or 16 bytes — an empty (or any other length) IV would build an
///   all-zero or malformed AES-CTR/CBC counter (a two-time-pad, in the
///   all-zero case). An empty list falls back to the scheme's counter IV
///   width (there is no sample to measure; [`CencEncryptor::validate_iv_gen`]
///   will itself reject the count mismatch against the `Media`'s real total
///   sample count).
fn tenc_iv_fields(
    scheme: CencScheme,
    iv_gen: &IvGen,
    constant_iv_senc: ConstantIvSenc,
) -> Result<(u8, Option<Vec<u8>>)> {
    match iv_gen {
        IvGen::Constant(iv) => match constant_iv_senc {
            ConstantIvSenc::Emit => Ok((16, Some(iv.to_vec()))),
            ConstantIvSenc::Omit => Ok((0, Some(iv.to_vec()))),
        },
        IvGen::Counter => Ok((CencEncryptor::counter_iv_size(scheme) as u8, None)),
        IvGen::Explicit(ivs) => {
            let len = match ivs.first() {
                Some(first) => {
                    if ivs.iter().any(|iv| iv.len() != first.len()) {
                        return Err(Error::InvalidInput(
                            "IvGen::Explicit IVs must all share one length (tenc.default_per_sample_iv_size is one value for the whole track)",
                        ));
                    }
                    first.len()
                }
                None => CencEncryptor::counter_iv_size(scheme),
            };
            if !VALID_EXPLICIT_IV_LENS.contains(&len) {
                return Err(Error::InvalidInput(
                    "CENC per-sample IV must be 8 or 16 bytes",
                ));
            }
            Ok((len as u8, None))
        }
    }
}

#[cfg(test)]
mod tests {
    //! Byte-exact IR-level round-trip tests: encrypt with [`CencEncryptor`]
    //! (the public surface), then reverse with the shared cipher core
    //! ([`cenc_crypto::apply_ctr`] / [`cenc_crypto::cbcs_sample`] +
    //! [`CbcsOp::Decrypt`]) directly — the same functions
    //! [`crate::cenc_decrypt::CencDecryptor`] calls — using each recorded
    //! [`crate::cenc::SampleEncryptionEntry`]'s IV/subsample map. Only
    //! reachable from an in-crate unit test (`cenc_crypto` is `pub(crate)`);
    //! `tests/cenc_encrypt.rs` covers the equivalent public-API-only surface
    //! (see that file's docs for why it does not repeat this exact reversal).

    use super::*;
    use broadcast_common::Unpackage;
    use bytes::Bytes;

    use crate::ts_demux::TsDemux;

    const KID: [u8; 16] = [
        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
        0x00,
    ];
    const KEY: [u8; 16] = [
        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
        0x10,
    ];

    /// The real cleartext H.264 capture used by `cenc_decrypt`'s tests too,
    /// narrowed to its single AVC video track so the per-scheme cipher tests
    /// below have a deterministic, single-track `Media`. Cross-track IV
    /// uniqueness (the property a single-track `Media` structurally cannot
    /// test) is covered by [`multi_track_media`]'s tests and by
    /// `tests/cenc_encrypt.rs`'s `counter_ivs_are_unique_across_every_track`.
    fn clear_media() -> Media {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264");
        path.push("main.ts");
        let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("read {path:?}: {e}"));
        let mut demux = TsDemux::new();
        let media = demux
            .unpackage(bytes.as_slice())
            .expect("demux fixtures/ts/h264/main.ts");
        media
            .select_tracks_by(|t| matches!(t.spec.config, CodecConfig::Avc { .. }))
            .expect("AVC video track present")
    }

    /// A real **two-track** (H.264 video + AAC audio) TS capture with both
    /// tracks kept — the shape that exposes cross-track keystream reuse.
    fn multi_track_media() -> Media {
        let mut path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("..");
        path.push("fixtures");
        path.push("ts");
        path.push("h264_aac.ts");
        let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("read {path:?}: {e}"));
        let mut demux = TsDemux::new();
        let media = demux
            .unpackage(bytes.as_slice())
            .expect("demux fixtures/ts/h264_aac.ts");
        assert!(
            media.tracks.len() > 1,
            "h264_aac.ts must be a multi-track fixture (got {})",
            media.tracks.len()
        );
        media
    }

    fn snapshot(media: &Media) -> Vec<Bytes> {
        media.tracks[0]
            .samples
            .iter()
            .map(|s| s.data.clone())
            .collect()
    }

    /// Every sample's bytes of every track, in (track, sample) order.
    fn snapshot_all(media: &Media) -> Vec<Bytes> {
        media
            .tracks
            .iter()
            .flat_map(|t| t.samples.iter().map(|s| s.data.clone()))
            .collect()
    }

    /// `n` distinct IVs of `len` bytes (an IV must be unique per content key),
    /// each placed in its own 2^32-wide slot so consecutive samples' AES-CTR
    /// counter ranges cannot intersect — see [`assert_ctr_ranges_disjoint`].
    /// A plainly sequential list (`base + i`) would be rejected under `cenc`,
    /// which is exactly what that check exists for.
    fn distinct_ivs(n: usize, len: usize) -> Vec<Vec<u8>> {
        (0..n)
            .map(|i| {
                let mut iv = alloc::vec![0xABu8; len];
                // The IV is the big-endian counter block, so the low-order
                // bytes are the last. Write the index into bits 32..63 of the
                // low half: consecutive samples then start 2^32 counter blocks
                // apart (far more than any real sample's protected block
                // count, which is what keeps the ranges disjoint).
                iv[len - 5] = (i & 0xFF) as u8;
                iv[len - 6] = ((i >> 8) & 0xFF) as u8;
                iv[len - 7] = ((i >> 16) & 0xFF) as u8;
                iv[len - 8] = ((i >> 24) & 0xFF) as u8;
                iv
            })
            .collect()
    }

    /// W8: `CencEncryptor`'s `Debug` must never print the bound content key
    /// (a derived `Debug` would — see this type's manual `impl fmt::Debug`).
    #[test]
    fn debug_redacts_content_key() {
        let enc = CencEncryptor::new(KEY);
        let out = alloc::format!("{enc:?}");
        assert!(
            !out.contains(&alloc::format!("{KEY:?}")),
            "Debug output must not contain the key's array representation: {out}"
        );
        // Every individual key byte's decimal form would also be a giveaway
        // if concatenated; check the exact array rendering is absent, and
        // that the placeholder and the (non-secret) counter are present.
        assert!(out.contains("<redacted>"));
        assert!(out.contains("next_counter"));
    }

    #[test]
    fn cenc_round_trip_reverses_byte_identical() {
        let mut media = clear_media();
        let original = snapshot(&media);

        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Counter,
            pattern: None,
            subsample: SubsamplePolicy::Video,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        CencEncryptor::resume(KEY, 7)
            .encrypt(&mut media, &cfg)
            .expect("encrypt");

        let track = &mut media.tracks[0];
        let enc = track.encryption.clone().expect("track.encryption Some");
        assert_eq!(enc.scheme, CencScheme::Cenc);
        assert_eq!(enc.tenc.default_kid, KID);
        assert_eq!(enc.samples.len(), track.samples.len());

        // Encryption must have actually changed at least one sample's bytes
        // (real cipher, not a passthrough).
        assert!(
            track
                .samples
                .iter()
                .zip(original.iter())
                .any(|(s, o)| s.data != *o),
            "encrypt must change protected bytes"
        );

        for (sample, entry) in track.samples.iter_mut().zip(enc.samples.iter()) {
            cenc_crypto::rewrite_in_place(&mut sample.data, |buf| {
                cenc_crypto::apply_ctr(&entry.initialization_vector, &KEY, &entry.subsamples, buf)
            })
            .expect("reverse apply_ctr");
        }
        let reversed: Vec<Bytes> = track.samples.iter().map(|s| s.data.clone()).collect();
        assert_eq!(reversed, original, "cenc round trip must be byte-identical");
    }

    #[test]
    fn cbcs_round_trip_reverses_byte_identical() {
        let mut media = clear_media();
        let original = snapshot(&media);

        let cfg = EncryptConfig {
            scheme: CencScheme::Cbcs,
            kid: KID,
            iv: IvGen::Counter,
            pattern: Some((1, 9)),
            subsample: SubsamplePolicy::Video,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .expect("encrypt");

        let track = &mut media.tracks[0];
        let enc = track.encryption.clone().expect("track.encryption Some");
        assert_eq!(enc.scheme, CencScheme::Cbcs);
        assert_eq!(enc.tenc.default_crypt_byte_block, 1);
        assert_eq!(enc.tenc.default_skip_byte_block, 9);
        assert_eq!(enc.samples.len(), track.samples.len());

        assert!(
            track
                .samples
                .iter()
                .zip(original.iter())
                .any(|(s, o)| s.data != *o),
            "encrypt must change protected bytes"
        );

        for (sample, entry) in track.samples.iter_mut().zip(enc.samples.iter()) {
            cenc_crypto::rewrite_in_place(&mut sample.data, |buf| {
                cenc_crypto::cbcs_sample(&enc.tenc, entry, &KEY, buf, CbcsOp::Decrypt)
            })
            .expect("reverse cbcs_sample");
        }
        let reversed: Vec<Bytes> = track.samples.iter().map(|s| s.data.clone()).collect();
        assert_eq!(reversed, original, "cbcs round trip must be byte-identical");
    }

    #[test]
    fn whole_sample_policy_yields_empty_subsample_map() {
        let mut media = clear_media();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::default(),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .expect("encrypt");
        let enc = media.tracks[0].encryption.as_ref().expect("Some");
        assert!(
            enc.samples.iter().all(|e| e.subsamples.is_empty()),
            "WholeSample policy must record an empty subsample map"
        );
    }

    #[test]
    fn explicit_iv_count_mismatch_errors() {
        let mut media = clear_media();
        let n = media.tracks[0].samples.len();
        assert!(n > 1, "fixture must have more than one sample to bite");
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Explicit(alloc::vec![alloc::vec![0u8; 8]; n - 1]),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    #[test]
    fn explicit_iv_too_long_errors() {
        let mut media = clear_media();
        let n = media.tracks[0].samples.len();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Explicit(alloc::vec![alloc::vec![0u8; 17]; n]),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    /// `IvGen::Explicit` with empty (0-byte) per-sample IVs must error, not
    /// silently build an all-zero AES-CTR counter (a two-time-pad — the same
    /// keystream would be reused for every sample, making the plaintext
    /// trivially recoverable).
    #[test]
    fn explicit_iv_empty_errors() {
        let mut media = clear_media();
        let n = media.tracks[0].samples.len();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Explicit(alloc::vec![alloc::vec![]; n]),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    /// `IvGen::Explicit` with a uniform, but non-8/16-byte, per-sample IV
    /// length must error (only 8 and 16 bytes are valid on the wire —
    /// ISO/IEC 23001-7 §9.2/§12.2).
    #[test]
    fn explicit_iv_wrong_uniform_length_errors() {
        let mut media = clear_media();
        let n = media.tracks[0].samples.len();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Explicit(alloc::vec![alloc::vec![0u8; 12]; n]),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    /// `IvGen::Explicit` accepts both valid per-sample IV lengths — 8 and 16
    /// bytes (ISO/IEC 23001-7 §9.2/§12.2) — recording the matching
    /// `tenc.default_per_sample_iv_size` for each.
    #[test]
    fn explicit_iv_valid_lengths_are_ok() {
        for len in [8usize, 16] {
            let mut media = clear_media();
            let n = media.tracks[0].samples.len();
            let cfg = EncryptConfig {
                scheme: CencScheme::Cenc,
                kid: KID,
                iv: IvGen::Explicit(distinct_ivs(n, len)),
                pattern: None,
                subsample: SubsamplePolicy::WholeSample,
                constant_iv_senc: ConstantIvSenc::default(),
            };
            CencEncryptor::new(KEY)
                .encrypt(&mut media, &cfg)
                .unwrap_or_else(|e| panic!("{len}-byte explicit IV must be accepted: {e:?}"));
            let enc = media.tracks[0].encryption.as_ref().expect("Some");
            assert_eq!(
                enc.tenc.default_per_sample_iv_size, len as u8,
                "tenc.default_per_sample_iv_size must match the actual IV length used"
            );
        }
    }

    /// Audit r05-W4: the default `IvGen::Counter` under `cbcs` must emit
    /// **16-byte** per-sample IVs, not the 8-byte shape this module's own
    /// [`IvGen::Constant`] doc records that Bento4 `mp4decrypt` silently
    /// no-ops. `cenc` keeps the 8-byte CMAF convention.
    #[test]
    fn cbcs_default_counter_emits_16_byte_ivs() {
        // cbcs + the Default::default() IvGen (Counter) — the shape a caller
        // reaches with `EncryptConfig { scheme: Cbcs, ..Default::default() }`.
        let mut media = clear_media();
        let n = media.tracks[0].samples.len();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cbcs,
            kid: KID,
            iv: IvGen::default(),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        assert!(
            matches!(cfg.iv, IvGen::Counter),
            "the default must be Counter"
        );
        CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .expect("encrypt");
        let enc = media.tracks[0].encryption.as_ref().expect("Some");
        assert_eq!(enc.tenc.default_per_sample_iv_size, 16);
        // Every recorded per-sample IV must really be 16 bytes (a tenc that
        // said 16 while senc carried 8 would desync saiz against senc).
        assert_eq!(enc.samples.len(), n);
        for (i, s) in enc.samples.iter().enumerate() {
            assert_eq!(
                s.initialization_vector.len(),
                16,
                "cbcs sample {i} IV must be 16 bytes"
            );
        }
        // The IV is the 64-bit counter zero-extended into a 16-byte block:
        // sample 0 starts at 0, sample 1 at 1, …
        assert_eq!(
            enc.samples[0].initialization_vector,
            alloc::vec![0u8; 16],
            "first cbcs counter IV is counter 0"
        );
        let mut second = alloc::vec![0u8; 16];
        second[15] = 1;
        assert_eq!(enc.samples[1].initialization_vector, second);
    }

    /// Audit r05-W4: `cenc` + `IvGen::Counter` keeps the 8-byte CMAF IV.
    #[test]
    fn cenc_default_counter_emits_8_byte_ivs() {
        let mut media = clear_media();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::default(),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .expect("encrypt");
        let enc = media.tracks[0].encryption.as_ref().expect("Some");
        assert_eq!(enc.tenc.default_per_sample_iv_size, 8);
        for s in &enc.samples {
            assert_eq!(s.initialization_vector.len(), 8);
        }
    }

    /// Audit r05-W3: under `cenc` the per-sample IV **is** the 128-bit AES-CTR
    /// counter block, and the counter advances once per 16-byte protected
    /// block (ISO/IEC 23001-7 §10.1). Two samples whose counter-block *ranges*
    /// intersect reuse keystream — a two-time pad — even though their IVs are
    /// distinct. A caller that supplies the natural sequential list
    /// `base + i` (the exact shape the equality-only check let through) must be
    /// rejected.
    #[test]
    fn cenc_sequential_16_byte_ivs_overlap_is_rejected() {
        let mut media = clear_media();
        let n = media.tracks[0].samples.len();
        // Sequential 16-byte IVs, spaced one apart — sample i+1's first
        // counter block equals sample i's second whenever a sample is longer
        // than one 16-byte block, which real video samples always are.
        let ivs: Vec<Vec<u8>> = (0..n)
            .map(|i| {
                let mut iv = alloc::vec![0u8; 16];
                iv[14] = (i >> 8) as u8;
                iv[15] = i as u8;
                iv
            })
            .collect();
        // Precondition: the IVs are genuinely distinct, so the *equality*
        // check the audit found insufficient would have accepted them.
        let unique: alloc::collections::BTreeSet<&Vec<u8>> = ivs.iter().collect();
        assert_eq!(unique.len(), n, "the test IVs must all differ");

        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Explicit(ivs),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let before = snapshot_all(&media);
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .expect_err("sequential 16-byte cenc IVs must be rejected");
        assert!(matches!(err, Error::InvalidInput(_)), "got {err:?}");
        // Atomicity: a rejection must leave every sample byte-identical.
        assert_eq!(snapshot_all(&media), before, "media must be untouched");
    }

    /// Audit r05-W3: the *same* sequential IVs are fine under `cbcs`, whose IV
    /// seeds a CBC chain rather than a counter (no keystream to reuse).
    #[test]
    fn cbcs_sequential_16_byte_ivs_accepted() {
        let mut media = clear_media();
        let n = media.tracks[0].samples.len();
        let ivs: Vec<Vec<u8>> = (0..n)
            .map(|i| {
                let mut iv = alloc::vec![0u8; 16];
                iv[14] = (i >> 8) as u8;
                iv[15] = i as u8;
                iv
            })
            .collect();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cbcs,
            kid: KID,
            iv: IvGen::Explicit(ivs),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .expect("cbcs must accept sequential IVs (no counter)");
    }

    /// `cbcs` pattern `crypt_byte_block == 0` with a nonzero
    /// `skip_byte_block` must error — otherwise the whole range is left
    /// silently unprotected while `tenc.default_is_protected` still claims
    /// protection (see `cenc_crypto::cbcs_sample`'s guard).
    #[test]
    fn cbcs_pattern_zero_crypt_nonzero_skip_errors() {
        let mut media = clear_media();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cbcs,
            kid: KID,
            iv: IvGen::Counter,
            pattern: Some((0, 9)),
            subsample: SubsamplePolicy::Video,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    /// A `cbcs` pattern component above 15 must error rather than silently
    /// truncate to its low 4 bits when packed into `tenc` (ISO/IEC 23001-7
    /// §12.2: `(crypt_byte_block << 4) | skip_byte_block`) — e.g. `(17, 9)`
    /// would otherwise silently become `(1, 9)` on the wire.
    #[test]
    fn cbcs_pattern_component_too_large_errors() {
        let mut media = clear_media();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cbcs,
            kid: KID,
            iv: IvGen::Counter,
            pattern: Some((17, 9)),
            subsample: SubsamplePolicy::Video,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    /// **Multi-track byte-exact round trip, both schemes.** Encrypt a real
    /// two-track (video + audio) `Media` with one `EncryptConfig`, then reverse
    /// every track's samples with the shared cipher core using that track's own
    /// recorded `tenc`/`senc` metadata, and require every sample of every track
    /// back byte-identical.
    ///
    /// The single-track round trips above cannot catch a cross-track
    /// bookkeeping error (wrong IV attributed to the wrong track's samples);
    /// this one can, because the per-sample IVs now differ *between* tracks as
    /// well as within them.
    #[test]
    fn multi_track_round_trip_reverses_byte_identical_both_schemes() {
        for scheme in [CencScheme::Cenc, CencScheme::Cbcs] {
            let mut media = multi_track_media();
            let original = snapshot_all(&media);
            let cfg = EncryptConfig {
                scheme,
                kid: KID,
                iv: IvGen::Counter,
                pattern: if scheme == CencScheme::Cbcs {
                    Some((1, 9))
                } else {
                    None
                },
                subsample: SubsamplePolicy::Video,
                constant_iv_senc: ConstantIvSenc::default(),
            };
            CencEncryptor::resume(KEY, 3)
                .encrypt(&mut media, &cfg)
                .unwrap_or_else(|e| panic!("{}: encrypt: {e:?}", scheme.name()));
            assert_ne!(
                snapshot_all(&media),
                original,
                "{}: encrypt must change protected bytes",
                scheme.name()
            );

            for track in &mut media.tracks {
                let enc = track.encryption.clone().expect("track.encryption Some");
                assert_eq!(enc.samples.len(), track.samples.len());
                for (sample, entry) in track.samples.iter_mut().zip(enc.samples.iter()) {
                    cenc_crypto::rewrite_in_place(&mut sample.data, |buf| match scheme {
                        CencScheme::Cenc => cenc_crypto::apply_ctr(
                            &entry.initialization_vector,
                            &KEY,
                            &entry.subsamples,
                            buf,
                        ),
                        CencScheme::Cbcs => {
                            cenc_crypto::cbcs_sample(&enc.tenc, entry, &KEY, buf, CbcsOp::Decrypt)
                        }
                        // This test drives exactly the two schemes above; a
                        // third reaching here means the caller list changed
                        // without the reverse-cipher being taught about it.
                        other => panic!("test drives only cenc/cbcs, got {other}"),
                    })
                    .unwrap_or_else(|e| panic!("{}: reverse: {e:?}", scheme.name()));
                }
            }
            assert_eq!(
                snapshot_all(&media),
                original,
                "{}: multi-track round trip must be byte-identical",
                scheme.name()
            );
        }
    }

    /// The IV counter must not restart per track: the last IV of track 0 and
    /// the first IV of track 1 must be consecutive, and the whole `Media`'s
    /// IVs must be distinct. (`tests/cenc_encrypt.rs` asserts the same
    /// uniqueness property through the public API; this pins the *continuity*
    /// of the counter, which is what makes the uniqueness hold.)
    #[test]
    fn counter_iv_runs_continuously_across_tracks() {
        const BASE: u64 = 0x0102_0304_0506_0708;
        let mut media = multi_track_media();
        let first_track_len = media.tracks[0].samples.len();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Counter,
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        CencEncryptor::resume(KEY, BASE)
            .encrypt(&mut media, &cfg)
            .expect("encrypt");

        let ivs: Vec<Vec<u8>> = media
            .tracks
            .iter()
            .flat_map(|t| {
                t.encryption
                    .as_ref()
                    .expect("Some")
                    .samples
                    .iter()
                    .map(|e| e.initialization_vector.clone())
            })
            .collect();
        for (i, iv) in ivs.iter().enumerate() {
            assert_eq!(
                iv.as_slice(),
                &(BASE + i as u64).to_be_bytes()[..],
                "IV {i} (Media-wide index) must be base + i"
            );
        }
        // The specific boundary the original defect got wrong.
        assert_eq!(
            ivs[first_track_len].as_slice(),
            &(BASE + first_track_len as u64).to_be_bytes()[..],
            "track 1's first IV must continue track 0's counter, not restart at base"
        );
    }

    /// `IvGen::Constant` + `cenc` is rejected, and the `Media` is left
    /// untouched (no track partially encrypted, no metadata recorded).
    #[test]
    fn constant_iv_under_cenc_errors_and_leaves_media_untouched() {
        let mut media = multi_track_media();
        let original = snapshot_all(&media);
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Constant([0x5Au8; KEY_LEN]),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
        assert_eq!(snapshot_all(&media), original, "no sample may be ciphered");
        assert!(media.tracks.iter().all(|t| t.encryption.is_none()));
    }

    /// A rejected `IvGen::Explicit` list (wrong total count) must be caught
    /// *before* any cipher work, leaving the `Media` byte-identical — not with
    /// track 0 encrypted and track 1 clear.
    #[test]
    fn rejected_explicit_iv_list_leaves_media_untouched() {
        let mut media = multi_track_media();
        let original = snapshot_all(&media);
        let first_track_len = media.tracks[0].samples.len();
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            // The old per-track meaning: one IV per sample of track 0 only.
            iv: IvGen::Explicit(distinct_ivs(first_track_len, 8)),
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
        assert_eq!(snapshot_all(&media), original, "no sample may be ciphered");
        assert!(media.tracks.iter().all(|t| t.encryption.is_none()));
    }

    /// The pre-cipher plan-uniqueness backstop bites: a **planned** IV
    /// sequence (see [`CencEncryptor::plan_sample_ivs`]) that repeats an IV
    /// across tracks is rejected by [`assert_ivs_unique`] — the exact shape a
    /// reintroduced per-track index reset (the original defect) would
    /// produce. Built by hand (the only way to reach it now that generation
    /// is correct) to prove the guard is real rather than dead code; it is
    /// what makes a future reintroduction of that defect fail loudly, and —
    /// because it runs on the plan *before* any cipher work — fail before
    /// `media` is ever touched (see
    /// [`planned_ivs_are_validated_before_any_sample_is_touched`] for the
    /// end-to-end proof of that ordering).
    #[test]
    fn planned_duplicate_ivs_are_rejected_before_ciphering() {
        // Two tracks; track 1's plan replays track 0's first IV instead of
        // continuing from where track 0 left off — exactly what a per-track
        // counter reset produces.
        let dup = alloc::vec![0u8, 0, 0, 0, 0, 0, 0, 1];
        let plan: Vec<Vec<Vec<u8>>> = alloc::vec![
            alloc::vec![dup.clone(), alloc::vec![0u8, 0, 0, 0, 0, 0, 0, 2]],
            alloc::vec![dup],
        ];
        let err = assert_ivs_unique(&plan, &IvGen::Counter, ConstantIvSenc::Omit).unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));

        // A correctly-generated (strictly increasing, Media-wide) plan must
        // pass unchanged.
        let good_plan: Vec<Vec<Vec<u8>>> = alloc::vec![
            alloc::vec![
                alloc::vec![0u8, 0, 0, 0, 0, 0, 0, 0],
                alloc::vec![0u8, 0, 0, 0, 0, 0, 0, 1],
            ],
            alloc::vec![alloc::vec![0u8, 0, 0, 0, 0, 0, 0, 2]],
        ];
        assert!(
            assert_ivs_unique(&good_plan, &IvGen::Counter, ConstantIvSenc::Omit).is_ok(),
            "a correctly Media-wide-continuous plan must pass the backstop"
        );
    }

    /// **Regression #783**: `cenc` + `IvGen::Counter` + `ConstantIvSenc::Emit`
    /// must NOT short-circuit the duplicate-IV check.  The `Emit` variant
    /// only makes semantic sense with `cbcs`+`Constant`; a duplicate IV on
    /// a `cenc`/`Counter` path (even with `Emit` set) is still a two-time
    /// pad and must be caught by this backstop.
    #[test]
    fn emit_does_not_short_circuit_duplicate_check_for_cenc_counter() {
        let dup = alloc::vec![0u8; 8];
        // Two identical IVs across tracks — same shape as
        // `planned_duplicate_ivs_are_rejected_before_ciphering`.
        let plan: Vec<Vec<Vec<u8>>> = alloc::vec![alloc::vec![dup.clone()], alloc::vec![dup],];
        let err = assert_ivs_unique(&plan, &IvGen::Counter, ConstantIvSenc::Emit)
            .expect_err("duplicate IV on cenc+Counter+Emit must be rejected");
        assert!(matches!(err, Error::InvalidInput(_)));
    }

    /// **F1 regression, end to end**: a `Media` whose `encrypt()` call is
    /// rejected (a wrong `IvGen::Explicit` count, one of the plan-validation
    /// failure modes) leaves every sample byte-identical to the input — no
    /// track partially keystreamed. This exercises the real
    /// [`Encrypt::encrypt`] entry point (not [`assert_ivs_unique`] in
    /// isolation, which [`planned_duplicate_ivs_are_rejected_before_ciphering`]
    /// covers), so it pins the property the whole plan-then-cipher restructure
    /// exists for: planning and validating happen entirely before the cipher
    /// loop, so a rejected plan can never leave a half-encrypted `Media`
    /// behind. See also [`rejected_explicit_iv_list_leaves_media_untouched`]
    /// and [`constant_iv_under_cenc_errors_and_leaves_media_untouched`] above,
    /// which pin the same property for the other two rejection paths
    /// ([`IvGen::Explicit`]'s per-track-sized list and [`IvGen::Constant`]
    /// under `cenc`).
    #[test]
    fn planned_ivs_are_validated_before_any_sample_is_touched() {
        let mut media = multi_track_media();
        let original = snapshot_all(&media);
        let n = media.tracks[0].samples.len();
        assert!(n > 1, "fixture must have more than one sample to bite");
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Explicit(distinct_ivs(n - 1, 8)), // wrong total count
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };
        let err = CencEncryptor::new(KEY)
            .encrypt(&mut media, &cfg)
            .unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)));
        assert_eq!(
            snapshot_all(&media),
            original,
            "a rejected plan must leave every track's samples byte-identical"
        );
        assert!(media.tracks.iter().all(|t| t.encryption.is_none()));
    }

    /// **F2 regression test.** Two successive `encrypt()` calls on the SAME
    /// [`CencEncryptor`] instance (hence the same content key) — the shape a
    /// video-only + audio-only split of one asset, or successive live
    /// segments under one key period, actually produces — must never repeat
    /// a per-sample IV. Before this fix, [`IvGen::Counter`]'s `base` lived in
    /// `EncryptConfig` and was always whatever the caller passed (`0` via
    /// [`IvGen::default`]), so two calls sharing a key and using the default
    /// reproduced the exact two-time pad this type exists to prevent within
    /// one call. Now the running counter lives on the [`CencEncryptor`]
    /// instance and advances after each call, so reusing the instance
    /// continues instead of restarting.
    #[test]
    fn successive_encrypt_calls_on_one_instance_produce_disjoint_ivs() {
        let cfg = EncryptConfig {
            scheme: CencScheme::Cenc,
            kid: KID,
            iv: IvGen::Counter,
            pattern: None,
            subsample: SubsamplePolicy::WholeSample,
            constant_iv_senc: ConstantIvSenc::default(),
        };

        let mut enc = CencEncryptor::new(KEY);

        let mut media_a = clear_media();
        enc.encrypt(&mut media_a, &cfg).expect("first encrypt");
        let ivs_a: alloc::collections::BTreeSet<Vec<u8>> = media_a.tracks[0]
            .encryption
            .as_ref()
            .expect("Some")
            .samples
            .iter()
            .map(|e| e.initialization_vector.clone())
            .collect();

        let mut media_b = clear_media();
        enc.encrypt(&mut media_b, &cfg)
            .expect("second encrypt, same instance/key");
        let ivs_b: alloc::collections::BTreeSet<Vec<u8>> = media_b.tracks[0]
            .encryption
            .as_ref()
            .expect("Some")
            .samples
            .iter()
            .map(|e| e.initialization_vector.clone())
            .collect();

        assert!(
            ivs_a.is_disjoint(&ivs_b),
            "two encrypt() calls sharing one CencEncryptor (hence one key) must never reuse an \
             IV — a shared IV under one key is a two-time pad (ISO/IEC 23001-7 §9.2)"
        );

        // The documented residual: a FRESH `CencEncryptor::new(KEY)` (the
        // pre-fix shape every call used to be, via `IvGen::default()`
        // restarting at `base: 0`) reproduces media_a's exact IV set —
        // proving the fix is "reuse one instance per key", not some property
        // of the fixture, and that constructing a second fresh instance for
        // a key already in use is a caller error this type documents but
        // cannot detect.
        let mut media_c = clear_media();
        CencEncryptor::new(KEY)
            .encrypt(&mut media_c, &cfg)
            .expect("fresh instance, third encrypt");
        let ivs_c: alloc::collections::BTreeSet<Vec<u8>> = media_c.tracks[0]
            .encryption
            .as_ref()
            .expect("Some")
            .samples
            .iter()
            .map(|e| e.initialization_vector.clone())
            .collect();
        assert_eq!(
            ivs_a, ivs_c,
            "a fresh CencEncryptor::new(KEY) must reproduce media_a's exact IV set: \
             CencEncryptor::new always starts the counter at 0, so reusing the SAME key across \
             SEPARATE fresh instances is the one collision this type cannot structurally prevent \
             — documented as the caller's obligation"
        );
    }

    /// **The provably-taken fast path (media plane step 2b, G12)**: every
    /// sample straight out of [`clear_media`]'s fresh `TsDemux` — the shape
    /// `CencEncryptor::encrypt` actually sees in real use, before any sample
    /// has been fanned out to another consumer — is uniquely owned, so
    /// [`cenc_crypto::rewrite_in_place`] must take the zero-copy
    /// `try_into_mut` branch for every one of them. Complements the
    /// mechanism-level proof in `cenc_crypto`'s own tests (which also proves
    /// the shared/fallback branch) and the whole-pipeline allocation count in
    /// `tests/alloc_measurement.rs`.
    #[test]
    fn real_fixture_samples_take_the_zero_copy_fast_path() {
        let mut media = clear_media();
        let track = &mut media.tracks[0];
        assert!(track.samples.len() > 1, "fixture must carry samples");
        for sample in &mut track.samples {
            let took_fast_path =
                cenc_crypto::rewrite_in_place(&mut sample.data, |_buf| Ok(())).expect("no-op ok");
            assert!(
                took_fast_path,
                "a freshly-demuxed, not-yet-fanned-out sample must take the zero-copy path"
            );
        }
    }

    /// The inverse: once a sample has been fanned out (cloned to a second
    /// consumer — a refcount bump, per the whole point of switching to
    /// `Bytes`), a subsequent in-place rewrite of the ORIGINAL must fall back
    /// to a copy rather than mutate bytes the other consumer still holds.
    #[test]
    fn fanned_out_sample_forces_the_copy_fallback() {
        let mut media = clear_media();
        let sample = &mut media.tracks[0].samples[0];
        let fanned_out_consumer = sample.data.clone(); // refcount 2
        let took_fast_path = cenc_crypto::rewrite_in_place(&mut sample.data, |buf| {
            buf[0] ^= 0xFF;
            Ok(())
        })
        .expect("rewrite ok");
        assert!(
            !took_fast_path,
            "a sample already fanned out to another consumer must not take the fast path"
        );
        assert_ne!(
            sample.data[0], fanned_out_consumer[0],
            "the rewritten handle's first byte must differ from the untouched consumer's"
        );
    }
}