framefinery-api 0.0.3

Shared media pipeline APIs for FrameFinery.
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
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
#[cfg(feature = "filter-pattern")]
use std::str::FromStr;

use crate::error::MediaError;
use crate::error::Result;
use crate::pipeline::{Filter, FrameSourceRawVideoAdapter, Source};
#[cfg(any(
    feature = "filter-pattern",
    feature = "filter-crop",
    feature = "filter-scale"
))]
use crate::ChromaSampling;
use crate::Frame;
use crate::FrameInfo;
#[cfg(any(
    feature = "filter-pattern",
    feature = "filter-crop",
    feature = "filter-scale"
))]
use crate::PixelFormat;
use crate::RawVideoFrameSource;
#[cfg(feature = "filter-pattern")]
use crate::SampleBitDepth;
#[cfg(feature = "filter-pattern")]
use crate::{scale_sample_bit_depth, write_planar_sample};

/// Pipeline position served by a filter manifest entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterStageKind {
    /// A source filter generates frames and replaces file input.
    Source,
    /// A transform filter consumes and emits frames.
    Transform,
}

/// Implementation status for a declared filter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterStatus {
    /// The filter can be constructed and executed.
    Implemented,
    /// The filter is declared for help/discovery but execution is not ready.
    Scaffold,
}

/// Value shape for one parameter in a filter spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterSpecValue {
    /// Parameter must be one of the listed strings.
    Choice(&'static [&'static str]),
    /// Parameter must be an integer greater than zero.
    PositiveInteger,
    /// Parameter must be an integer greater than or equal to zero.
    UnsignedInteger,
}

/// One accepted textual form for a filter spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilterSpecForm {
    /// User-facing syntax, such as `pattern=<name>`.
    pub syntax: &'static str,
    /// Short explanation of the syntax form.
    pub summary: &'static str,
}

/// One named parameter accepted by a filter spec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilterSpecParameter {
    /// Parameter name used in the spec string.
    pub name: &'static str,
    /// Placeholder name shown for the parameter value.
    pub value_name: &'static str,
    /// Whether this parameter is required.
    pub required: bool,
    /// Value shape accepted by this parameter.
    pub value: FilterSpecValue,
    /// Short explanation of the parameter.
    pub summary: &'static str,
}

/// One example filter spec for help and generated documentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilterSpecExample {
    /// Complete filter spec string.
    pub spec: &'static str,
    /// Short explanation of the example.
    pub summary: &'static str,
}

/// Documentation manifest for one filter's accepted spec strings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilterSpecManifest {
    /// Supported syntax forms.
    pub forms: &'static [FilterSpecForm],
    /// Declared parameters.
    pub parameters: &'static [FilterSpecParameter],
    /// Example specs.
    pub examples: &'static [FilterSpecExample],
    /// Additional behavior notes.
    pub notes: &'static [&'static str],
}

/// Public manifest entry for a compiled filter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilterManifest {
    /// Stable filter name.
    pub name: &'static str,
    /// Pipeline position served by this filter.
    pub stage: FilterStageKind,
    /// Cargo feature that enables this filter.
    pub feature: &'static str,
    /// Whether the filter executes today or is only a scaffold.
    pub status: FilterStatus,
    /// Structured spec/help manifest.
    pub spec: &'static FilterSpecManifest,
    /// Short user-facing summary.
    pub summary: &'static str,
}

impl FilterManifest {
    /// Return a stable string label for this filter's implementation status.
    pub const fn implementation_status(self) -> &'static str {
        match self.status {
            FilterStatus::Implemented => "implemented",
            FilterStatus::Scaffold => "scaffold",
        }
    }
}

/// Canonical pattern source names accepted by the `pattern` source filter.
pub const PATTERN_SOURCE_NAMES: &[&str] = &["black", "checker", "gradient", "color_blocks"];

const PATTERN_SPEC_FORMS: &[FilterSpecForm] = &[
    FilterSpecForm {
        syntax: "pattern=<name>",
        summary: "generate frames from a named deterministic pattern",
    },
    FilterSpecForm {
        syntax: "pattern:<name>",
        summary: "alternate spelling accepted by the parser",
    },
];

const PATTERN_SPEC_PARAMETERS: &[FilterSpecParameter] = &[FilterSpecParameter {
    name: "name",
    value_name: "pattern",
    required: true,
    value: FilterSpecValue::Choice(PATTERN_SOURCE_NAMES),
    summary: "pattern sequence to generate",
}];

const PATTERN_SPEC_EXAMPLES: &[FilterSpecExample] = &[
    FilterSpecExample {
        spec: "pattern=black",
        summary: "generate black frames",
    },
    FilterSpecExample {
        spec: "pattern=color_blocks",
        summary: "generate moving color-block frames",
    },
];

const PATTERN_SPEC_NOTES: &[&str] = &[
    "source filters must be first and cannot be combined with an input path",
    "source filters require --video metadata and --frames",
    "currently generates planar YUV/gray frames across supported bit depths, gbrp8, and rgb24",
    "blocks is accepted as a short alias for color_blocks",
];

/// Spec manifest for the `pattern` source filter.
pub const PATTERN_FILTER_SPEC: FilterSpecManifest = FilterSpecManifest {
    forms: PATTERN_SPEC_FORMS,
    parameters: PATTERN_SPEC_PARAMETERS,
    examples: PATTERN_SPEC_EXAMPLES,
    notes: PATTERN_SPEC_NOTES,
};

const IDENTITY_SPEC_FORMS: &[FilterSpecForm] = &[FilterSpecForm {
    syntax: "identity",
    summary: "pass frames through unchanged",
}];

const IDENTITY_SPEC_EXAMPLES: &[FilterSpecExample] = &[FilterSpecExample {
    spec: "identity",
    summary: "exercise the frame filter pipeline without changing pixels",
}];

/// Spec manifest for the `identity` transform filter.
pub const IDENTITY_FILTER_SPEC: FilterSpecManifest = FilterSpecManifest {
    forms: IDENTITY_SPEC_FORMS,
    parameters: &[],
    examples: IDENTITY_SPEC_EXAMPLES,
    notes: &[],
};

const CROP_SPEC_FORMS: &[FilterSpecForm] = &[FilterSpecForm {
    syntax: "crop=x=<px>:y=<px>:w=<px>:h=<px>",
    summary: "crop a rectangular frame region",
}];

const CROP_SPEC_PARAMETERS: &[FilterSpecParameter] = &[
    FilterSpecParameter {
        name: "x",
        value_name: "px",
        required: true,
        value: FilterSpecValue::UnsignedInteger,
        summary: "left coordinate of the crop rectangle",
    },
    FilterSpecParameter {
        name: "y",
        value_name: "px",
        required: true,
        value: FilterSpecValue::UnsignedInteger,
        summary: "top coordinate of the crop rectangle",
    },
    FilterSpecParameter {
        name: "w",
        value_name: "px",
        required: true,
        value: FilterSpecValue::PositiveInteger,
        summary: "crop width",
    },
    FilterSpecParameter {
        name: "h",
        value_name: "px",
        required: true,
        value: FilterSpecValue::PositiveInteger,
        summary: "crop height",
    },
];

const CROP_SPEC_EXAMPLES: &[FilterSpecExample] = &[FilterSpecExample {
    spec: "crop=x=0:y=0:w=640:h=360",
    summary: "select a 640x360 region from the top-left corner",
}];

const CROP_SPEC_NOTES: &[&str] = &[
    "subsampled formats require crop coordinates and dimensions aligned to chroma samples",
    "the output keeps the input pixel format",
];

/// Spec manifest for the `crop` transform filter.
pub const CROP_FILTER_SPEC: FilterSpecManifest = FilterSpecManifest {
    forms: CROP_SPEC_FORMS,
    parameters: CROP_SPEC_PARAMETERS,
    examples: CROP_SPEC_EXAMPLES,
    notes: CROP_SPEC_NOTES,
};

const SCALE_SPEC_FORMS: &[FilterSpecForm] = &[FilterSpecForm {
    syntax: "scale=w=<px>:h=<px>",
    summary: "resize frames to the requested output geometry",
}];

const SCALE_SPEC_PARAMETERS: &[FilterSpecParameter] = &[
    FilterSpecParameter {
        name: "w",
        value_name: "px",
        required: true,
        value: FilterSpecValue::PositiveInteger,
        summary: "output width",
    },
    FilterSpecParameter {
        name: "h",
        value_name: "px",
        required: true,
        value: FilterSpecValue::PositiveInteger,
        summary: "output height",
    },
];

const SCALE_SPEC_EXAMPLES: &[FilterSpecExample] = &[FilterSpecExample {
    spec: "scale=w=1280:h=720",
    summary: "resize frames to 1280x720",
}];

const SCALE_SPEC_NOTES: &[&str] = &[
    "uses deterministic nearest-neighbor sampling",
    "the output keeps the input pixel format",
];

/// Spec manifest for the `scale` transform filter.
pub const SCALE_FILTER_SPEC: FilterSpecManifest = FilterSpecManifest {
    forms: SCALE_SPEC_FORMS,
    parameters: SCALE_SPEC_PARAMETERS,
    examples: SCALE_SPEC_EXAMPLES,
    notes: SCALE_SPEC_NOTES,
};

/// Filter manifests compiled into this build.
pub const FILTERS: &[FilterManifest] = &[
    #[cfg(feature = "filter-pattern")]
    FilterManifest {
        name: "pattern",
        stage: FilterStageKind::Source,
        feature: "filter-pattern",
        status: FilterStatus::Implemented,
        spec: &PATTERN_FILTER_SPEC,
        summary: "generated raw-video pattern source",
    },
    #[cfg(feature = "filter-identity")]
    FilterManifest {
        name: "identity",
        stage: FilterStageKind::Transform,
        feature: "filter-identity",
        status: FilterStatus::Implemented,
        spec: &IDENTITY_FILTER_SPEC,
        summary: "no-op frame pass-through transform",
    },
    #[cfg(feature = "filter-crop")]
    FilterManifest {
        name: "crop",
        stage: FilterStageKind::Transform,
        feature: "filter-crop",
        status: FilterStatus::Implemented,
        spec: &CROP_FILTER_SPEC,
        summary: "rectangular crop transform",
    },
    #[cfg(feature = "filter-scale")]
    FilterManifest {
        name: "scale",
        stage: FilterStageKind::Transform,
        feature: "filter-scale",
        status: FilterStatus::Implemented,
        spec: &SCALE_FILTER_SPEC,
        summary: "nearest-neighbor resize transform",
    },
];

/// Find a compiled filter manifest by name.
pub fn filter_manifest(name: &str) -> Option<FilterManifest> {
    FILTERS.iter().copied().find(|filter| filter.name == name)
}

/// Find a compiled filter's spec manifest by name.
pub fn filter_spec_manifest(name: &str) -> Option<&'static FilterSpecManifest> {
    filter_manifest(name).map(|filter| filter.spec)
}

/// Parsed filter stage spec.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilterStageSpec {
    /// Filter name parsed from `spec`.
    pub name: String,
    /// Original full filter spec string.
    pub spec: String,
}

/// Parsed filter pipeline specification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilterPipelineSpec {
    /// Optional source filter. Present only when no file input is used.
    pub source: Option<FilterStageSpec>,
    /// Ordered transform filters.
    pub transforms: Vec<FilterStageSpec>,
}

/// Builder for a parsed filter pipeline specification.
///
/// This is a small API wrapper around the same filter manifest validation used
/// by the CLI. It intentionally stores textual filter specs because filter
/// syntax is still the stable interchange form between command-line arguments,
/// manifests, validation files, and future frontends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilterPipelineBuilder {
    input_present: bool,
    specs: Vec<String>,
}

impl FilterStageSpec {
    /// Parse one raw filter spec into a stage spec.
    pub fn new(spec: impl Into<String>) -> Result<Self> {
        let spec = spec.into();
        let name = filter_spec_name(&spec).to_string();
        if name.is_empty() {
            return Err(MediaError::Message(
                "filter spec cannot be empty".to_string(),
            ));
        }
        Ok(Self { name, spec })
    }
}

impl FilterPipelineSpec {
    /// Start building a pipeline that consumes an external input frame stream.
    pub fn from_input() -> FilterPipelineBuilder {
        FilterPipelineBuilder::from_input()
    }

    /// Start building a pipeline that must begin with a source filter.
    pub fn from_source_filter() -> FilterPipelineBuilder {
        FilterPipelineBuilder::from_source_filter()
    }

    /// Return the frame metadata produced by this pipeline's transform stages.
    pub fn output_info(&self, input: FrameInfo) -> Result<FrameInfo> {
        filter_pipeline_output_info(input, &self.transforms)
    }

    /// Build executable transform filters for this pipeline.
    pub fn build_transforms(&self) -> Result<Vec<Box<dyn Filter>>> {
        self.transforms
            .iter()
            .map(build_filter_transform)
            .collect::<Result<Vec<_>>>()
    }

    /// Build the executable source filter, when this pipeline has one.
    pub fn build_source(
        &self,
        info: FrameInfo,
        frames: usize,
    ) -> Result<Option<Box<dyn Source<Output = Frame>>>> {
        self.source
            .as_ref()
            .map(|source| build_source_filter(source, info, frames))
            .transpose()
    }

    /// Build the executable source filter as a raw-frame callback, when present.
    pub fn build_raw_video_source(
        &self,
        info: FrameInfo,
        frames: usize,
    ) -> Result<Option<Box<dyn RawVideoFrameSource>>> {
        self.source
            .as_ref()
            .map(|source| build_raw_video_source_filter(source, info, frames))
            .transpose()
    }
}

impl FilterPipelineBuilder {
    /// Start building a pipeline that consumes an external input frame stream.
    pub fn from_input() -> Self {
        Self {
            input_present: true,
            specs: Vec::new(),
        }
    }

    /// Start building a pipeline that must begin with a source filter.
    pub fn from_source_filter() -> Self {
        Self {
            input_present: false,
            specs: Vec::new(),
        }
    }

    /// Set whether this pipeline consumes an external input frame stream.
    pub fn with_input_present(mut self, input_present: bool) -> Self {
        self.input_present = input_present;
        self
    }

    /// Append one textual filter spec.
    pub fn filter(mut self, spec: impl Into<String>) -> Result<Self> {
        let stage = FilterStageSpec::new(spec)?;
        self.specs.push(stage.spec);
        Ok(self)
    }

    /// Append several textual filter specs.
    pub fn filters<I, S>(mut self, specs: I) -> Result<Self>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for spec in specs {
            self = self.filter(spec)?;
        }
        Ok(self)
    }

    /// Parse and validate this builder into a pipeline specification.
    pub fn build(self) -> Result<FilterPipelineSpec> {
        parse_filter_pipeline_specs(&self.specs, self.input_present)
    }
}

/// Return the filter name portion of a filter spec string.
pub fn filter_spec_name(spec: &str) -> &str {
    spec.split_once('=')
        .or_else(|| spec.split_once(':'))
        .map_or(spec, |(name, _)| name)
}

/// Parse and validate an ordered set of filter specs for an encode pipeline.
pub fn parse_filter_pipeline_specs(
    specs: &[String],
    input_present: bool,
) -> Result<FilterPipelineSpec> {
    let mut source = None;
    let mut transforms = Vec::new();
    for (index, spec) in specs.iter().enumerate() {
        let stage = FilterStageSpec::new(spec.clone())?;
        let Some(manifest) = filter_manifest(&stage.name) else {
            return Err(MediaError::Message(format!(
                "unknown filter '{}'",
                stage.name
            )));
        };

        match manifest.stage {
            FilterStageKind::Source => {
                if input_present {
                    return Err(MediaError::Message(format!(
                        "source filter '{}' cannot be used after an input path",
                        stage.name
                    )));
                }
                if index != 0 {
                    return Err(MediaError::Message(format!(
                        "source filter '{}' must be the first filter",
                        stage.name
                    )));
                }
                if source.is_some() {
                    return Err(MediaError::Message(
                        "encode accepts only one source filter".to_string(),
                    ));
                }
                validate_executable_filter_spec(manifest, &stage)?;
                source = Some(stage);
            }
            FilterStageKind::Transform => {
                validate_executable_filter_spec(manifest, &stage)?;
                transforms.push(stage);
            }
        }
    }
    if !input_present && source.is_none() {
        return Err(MediaError::Message(
            "encode without an input requires a source filter such as --filter pattern=black"
                .to_string(),
        ));
    }
    Ok(FilterPipelineSpec { source, transforms })
}

/// Return the frame metadata produced by an ordered transform filter pipeline.
pub fn filter_pipeline_output_info(
    input: FrameInfo,
    transforms: &[FilterStageSpec],
) -> Result<FrameInfo> {
    let mut info = input;
    for stage in transforms {
        let Some(manifest) = filter_manifest(&stage.name) else {
            return Err(MediaError::Message(format!(
                "unknown filter '{}'",
                stage.name
            )));
        };
        if manifest.stage != FilterStageKind::Transform {
            return Err(MediaError::Message(format!(
                "filter '{}' is not a transform filter",
                stage.name
            )));
        }
        validate_executable_filter_spec(manifest, stage)?;
        info = filter_transform_output_info(stage, info)?;
    }
    Ok(info)
}

/// Generate raw video bytes from an executable source filter.
///
/// This helper materializes the requested frames into one `Vec<u8>` and is
/// intended for short fixtures and tests. Long streams should use
/// [`build_raw_video_source_filter`] or [`FilterPipelineSpec::build_raw_video_source`].
pub fn generate_source_filter_stream(
    stage: &FilterStageSpec,
    info: FrameInfo,
    frames: usize,
) -> Result<Vec<u8>> {
    let total_len = info
        .expected_len()
        .checked_mul(frames)
        .ok_or(MediaError::LengthOverflow)?;
    let mut output = Vec::with_capacity(total_len);
    let mut source = build_source_filter(stage, info, frames)?;
    while let Some(frame) = source.pull()? {
        output.extend_from_slice(frame.data());
    }
    Ok(output)
}

/// Build an executable source filter from a parsed stage spec.
pub fn build_source_filter(
    stage: &FilterStageSpec,
    info: FrameInfo,
    frames: usize,
) -> Result<Box<dyn Source<Output = Frame>>> {
    match stage.name.as_str() {
        "pattern" => build_pattern_filter_source(&stage.spec, info, frames),
        other => Err(MediaError::Message(format!(
            "filter '{other}' is not an executable source filter"
        ))),
    }
}

/// Build an executable source filter as a raw-frame callback.
pub fn build_raw_video_source_filter(
    stage: &FilterStageSpec,
    info: FrameInfo,
    frames: usize,
) -> Result<Box<dyn RawVideoFrameSource>> {
    match stage.name.as_str() {
        "pattern" => build_pattern_raw_video_source(&stage.spec, info, frames),
        _ => {
            let source = build_source_filter(stage, info, frames)?;
            Ok(Box::new(FrameSourceRawVideoAdapter::new(source, info)))
        }
    }
}

/// Build an executable transform filter from a parsed stage spec.
pub fn build_filter_transform(stage: &FilterStageSpec) -> Result<Box<dyn Filter>> {
    match stage.name.as_str() {
        "identity" => build_identity_filter(),
        "crop" => build_crop_filter(&stage.spec),
        "scale" => build_scale_filter(&stage.spec),
        other => Err(MediaError::Message(format!(
            "filter '{other}' is not an executable transform filter"
        ))),
    }
}

fn filter_transform_output_info(stage: &FilterStageSpec, input: FrameInfo) -> Result<FrameInfo> {
    match stage.name.as_str() {
        "identity" => Ok(input),
        "crop" => crop_filter_output_info(&stage.spec, input),
        "scale" => scale_filter_output_info(&stage.spec, input),
        other => Err(MediaError::Message(format!(
            "filter '{other}' has no output metadata model wired yet"
        ))),
    }
}

fn validate_executable_filter_spec(
    manifest: FilterManifest,
    stage: &FilterStageSpec,
) -> Result<()> {
    if manifest.status != FilterStatus::Implemented {
        return Err(MediaError::Message(format!(
            "filter '{}' is available as a discovery scaffold but execution is not implemented yet",
            stage.name
        )));
    }

    match stage.name.as_str() {
        "pattern" => validate_pattern_filter_spec(&stage.spec),
        "identity" => validate_identity_filter_spec(&stage.spec),
        "crop" => validate_crop_filter_spec(&stage.spec),
        "scale" => validate_scale_filter_spec(&stage.spec),
        other => Err(MediaError::Message(format!(
            "filter '{other}' has no execution model wired yet"
        ))),
    }
}

fn validate_identity_filter_spec(spec: &str) -> Result<()> {
    if spec.contains('=') || spec.contains(':') {
        return Err(MediaError::Message(
            "identity filter does not accept options".to_string(),
        ));
    }
    Ok(())
}

#[cfg(feature = "filter-identity")]
fn build_identity_filter() -> Result<Box<dyn Filter>> {
    Ok(Box::new(IdentityFilter))
}

#[cfg(not(feature = "filter-identity"))]
fn build_identity_filter() -> Result<Box<dyn Filter>> {
    Err(MediaError::Message("unknown filter 'identity'".to_string()))
}

#[cfg(feature = "filter-crop")]
fn validate_crop_filter_spec(spec: &str) -> Result<()> {
    parse_crop_filter_spec(spec).map(|_| ())
}

#[cfg(not(feature = "filter-crop"))]
fn validate_crop_filter_spec(_spec: &str) -> Result<()> {
    Err(MediaError::Message("unknown filter 'crop'".to_string()))
}

#[cfg(feature = "filter-scale")]
fn validate_scale_filter_spec(spec: &str) -> Result<()> {
    parse_scale_filter_spec(spec).map(|_| ())
}

#[cfg(not(feature = "filter-scale"))]
fn validate_scale_filter_spec(_spec: &str) -> Result<()> {
    Err(MediaError::Message("unknown filter 'scale'".to_string()))
}

#[cfg(feature = "filter-crop")]
fn build_crop_filter(spec: &str) -> Result<Box<dyn Filter>> {
    parse_crop_filter_spec(spec).map(|filter| Box::new(filter) as Box<dyn Filter>)
}

#[cfg(not(feature = "filter-crop"))]
fn build_crop_filter(_spec: &str) -> Result<Box<dyn Filter>> {
    Err(MediaError::Message("unknown filter 'crop'".to_string()))
}

#[cfg(feature = "filter-scale")]
fn build_scale_filter(spec: &str) -> Result<Box<dyn Filter>> {
    parse_scale_filter_spec(spec).map(|filter| Box::new(filter) as Box<dyn Filter>)
}

#[cfg(not(feature = "filter-scale"))]
fn build_scale_filter(_spec: &str) -> Result<Box<dyn Filter>> {
    Err(MediaError::Message("unknown filter 'scale'".to_string()))
}

#[cfg(feature = "filter-crop")]
fn crop_filter_output_info(spec: &str, input: FrameInfo) -> Result<FrameInfo> {
    parse_crop_filter_spec(spec)?.output_info(input)
}

#[cfg(not(feature = "filter-crop"))]
fn crop_filter_output_info(_spec: &str, _input: FrameInfo) -> Result<FrameInfo> {
    Err(MediaError::Message("unknown filter 'crop'".to_string()))
}

#[cfg(feature = "filter-scale")]
fn scale_filter_output_info(spec: &str, input: FrameInfo) -> Result<FrameInfo> {
    parse_scale_filter_spec(spec)?.output_info(input)
}

#[cfg(not(feature = "filter-scale"))]
fn scale_filter_output_info(_spec: &str, _input: FrameInfo) -> Result<FrameInfo> {
    Err(MediaError::Message("unknown filter 'scale'".to_string()))
}

#[cfg(feature = "filter-pattern")]
fn validate_pattern_filter_spec(spec: &str) -> Result<()> {
    parse_pattern_stage_kind(spec).map(|_| ())
}

#[cfg(not(feature = "filter-pattern"))]
fn validate_pattern_filter_spec(_spec: &str) -> Result<()> {
    Err(MediaError::Message("unknown filter 'pattern'".to_string()))
}

#[cfg(feature = "filter-pattern")]
fn build_pattern_filter_source(
    spec: &str,
    info: FrameInfo,
    frames: usize,
) -> Result<Box<dyn Source<Output = Frame>>> {
    Ok(Box::new(PatternSource::new(
        info,
        parse_pattern_stage_kind(spec)?,
        frames,
    )?))
}

#[cfg(not(feature = "filter-pattern"))]
fn build_pattern_filter_source(
    _spec: &str,
    _info: FrameInfo,
    _frames: usize,
) -> Result<Box<dyn Source<Output = Frame>>> {
    Err(MediaError::Message("unknown filter 'pattern'".to_string()))
}

#[cfg(feature = "filter-pattern")]
fn build_pattern_raw_video_source(
    spec: &str,
    info: FrameInfo,
    frames: usize,
) -> Result<Box<dyn RawVideoFrameSource>> {
    Ok(Box::new(PatternSource::new(
        info,
        parse_pattern_stage_kind(spec)?,
        frames,
    )?))
}

#[cfg(not(feature = "filter-pattern"))]
fn build_pattern_raw_video_source(
    _spec: &str,
    _info: FrameInfo,
    _frames: usize,
) -> Result<Box<dyn RawVideoFrameSource>> {
    Err(MediaError::Message("unknown filter 'pattern'".to_string()))
}

#[cfg(feature = "filter-pattern")]
fn parse_pattern_stage_kind(spec: &str) -> Result<PatternKind> {
    if filter_spec_name(spec) != "pattern" {
        return Err(MediaError::Message(
            "source filter must be pattern=<name>".to_string(),
        ));
    }
    let Some((_, value)) = spec.split_once('=').or_else(|| spec.split_once(':')) else {
        return Err(MediaError::Message(
            "pattern source expects --filter pattern=<name>".to_string(),
        ));
    };
    PatternKind::parse(value)
}

/// No-op frame transform that returns each input frame unchanged.
#[derive(Debug, Clone, Copy, Default)]
#[cfg(feature = "filter-identity")]
pub struct IdentityFilter;

#[cfg(feature = "filter-identity")]
impl Filter for IdentityFilter {
    fn process(&mut self, frame: Frame) -> Result<Vec<Frame>> {
        Ok(vec![frame])
    }
}

/// Rectangular frame crop transform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(feature = "filter-crop")]
pub struct CropFilter {
    x: usize,
    y: usize,
    width: usize,
    height: usize,
}

#[cfg(feature = "filter-crop")]
impl CropFilter {
    /// Create a crop transform from a rectangle in luma/pixel coordinates.
    pub fn new(x: usize, y: usize, width: usize, height: usize) -> Result<Self> {
        if width == 0 || height == 0 {
            return Err(MediaError::InvalidDimensions { width, height });
        }
        Ok(Self {
            x,
            y,
            width,
            height,
        })
    }

    /// Left coordinate of the crop rectangle.
    pub const fn x(self) -> usize {
        self.x
    }

    /// Top coordinate of the crop rectangle.
    pub const fn y(self) -> usize {
        self.y
    }

    /// Width of the crop rectangle.
    pub const fn width(self) -> usize {
        self.width
    }

    /// Height of the crop rectangle.
    pub const fn height(self) -> usize {
        self.height
    }

    /// Metadata produced when this crop is applied to `input`.
    pub fn output_info(self, input: FrameInfo) -> Result<FrameInfo> {
        crop_output_info(input, self.x, self.y, self.width, self.height)
    }
}

#[cfg(feature = "filter-crop")]
impl Filter for CropFilter {
    fn process(&mut self, frame: Frame) -> Result<Vec<Frame>> {
        let input = frame.info();
        let output = self.output_info(input)?;
        let data = crop_frame_data(frame.data(), input, self.x, self.y, self.width, self.height)?;
        Ok(vec![Frame::new(output, data)?])
    }
}

/// Nearest-neighbor frame resize transform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(feature = "filter-scale")]
pub struct ScaleFilter {
    width: usize,
    height: usize,
}

#[cfg(feature = "filter-scale")]
impl ScaleFilter {
    /// Create a nearest-neighbor scale transform.
    pub fn new(width: usize, height: usize) -> Result<Self> {
        if width == 0 || height == 0 {
            return Err(MediaError::InvalidDimensions { width, height });
        }
        Ok(Self { width, height })
    }

    /// Output width in pixels.
    pub const fn width(self) -> usize {
        self.width
    }

    /// Output height in pixels.
    pub const fn height(self) -> usize {
        self.height
    }

    /// Metadata produced when this scale is applied to `input`.
    pub fn output_info(self, input: FrameInfo) -> Result<FrameInfo> {
        FrameInfo::new(self.width, self.height, input.format)
    }
}

#[cfg(feature = "filter-scale")]
impl Filter for ScaleFilter {
    fn process(&mut self, frame: Frame) -> Result<Vec<Frame>> {
        let input = frame.info();
        let output = self.output_info(input)?;
        let data = scale_frame_data(frame.data(), input, self.width, self.height)?;
        Ok(vec![Frame::new(output, data)?])
    }
}

#[cfg(feature = "filter-crop")]
fn parse_crop_filter_spec(spec: &str) -> Result<CropFilter> {
    let params = parse_filter_params("crop", spec)?;
    let mut x = None;
    let mut y = None;
    let mut width = None;
    let mut height = None;
    for (key, value) in params {
        match key {
            "x" => assign_usize_param("crop", "x", value, false, &mut x)?,
            "y" => assign_usize_param("crop", "y", value, false, &mut y)?,
            "w" => assign_usize_param("crop", "w", value, true, &mut width)?,
            "h" => assign_usize_param("crop", "h", value, true, &mut height)?,
            other => {
                return Err(MediaError::Message(format!(
                    "crop filter does not accept parameter '{other}'"
                )));
            }
        }
    }
    CropFilter::new(
        require_param("crop", "x", x)?,
        require_param("crop", "y", y)?,
        require_param("crop", "w", width)?,
        require_param("crop", "h", height)?,
    )
}

#[cfg(feature = "filter-scale")]
fn parse_scale_filter_spec(spec: &str) -> Result<ScaleFilter> {
    let params = parse_filter_params("scale", spec)?;
    let mut width = None;
    let mut height = None;
    for (key, value) in params {
        match key {
            "w" => assign_usize_param("scale", "w", value, true, &mut width)?,
            "h" => assign_usize_param("scale", "h", value, true, &mut height)?,
            other => {
                return Err(MediaError::Message(format!(
                    "scale filter does not accept parameter '{other}'"
                )));
            }
        }
    }
    ScaleFilter::new(
        require_param("scale", "w", width)?,
        require_param("scale", "h", height)?,
    )
}

#[cfg(any(feature = "filter-crop", feature = "filter-scale"))]
fn parse_filter_params<'a>(filter_name: &str, spec: &'a str) -> Result<Vec<(&'a str, &'a str)>> {
    if filter_spec_name(spec) != filter_name {
        return Err(MediaError::Message(format!(
            "{filter_name} filter expects a spec starting with {filter_name}="
        )));
    }
    let Some((_, body)) = spec.split_once('=') else {
        return Err(MediaError::Message(format!(
            "{filter_name} filter expects key=value parameters"
        )));
    };
    if body.is_empty() {
        return Err(MediaError::Message(format!(
            "{filter_name} filter expects key=value parameters"
        )));
    }
    let mut params = Vec::new();
    for token in body.split(':') {
        let Some((key, value)) = token.split_once('=') else {
            return Err(MediaError::Message(format!(
                "{filter_name} filter parameter '{token}' must use key=value syntax"
            )));
        };
        if key.is_empty() || value.is_empty() {
            return Err(MediaError::Message(format!(
                "{filter_name} filter parameters cannot have empty keys or values"
            )));
        }
        params.push((key, value));
    }
    Ok(params)
}

#[cfg(any(feature = "filter-crop", feature = "filter-scale"))]
fn assign_usize_param(
    filter: &str,
    key: &str,
    value: &str,
    positive: bool,
    slot: &mut Option<usize>,
) -> Result<()> {
    if slot.is_some() {
        return Err(MediaError::Message(format!(
            "{filter} filter parameter '{key}' was provided more than once"
        )));
    }
    let parsed = value.parse::<usize>().map_err(|_| {
        MediaError::Message(format!(
            "{filter} filter parameter '{key}' expects an integer, got '{value}'"
        ))
    })?;
    if positive && parsed == 0 {
        return Err(MediaError::Message(format!(
            "{filter} filter parameter '{key}' must be greater than zero"
        )));
    }
    *slot = Some(parsed);
    Ok(())
}

#[cfg(any(feature = "filter-crop", feature = "filter-scale"))]
fn require_param(filter: &str, key: &str, value: Option<usize>) -> Result<usize> {
    value.ok_or_else(|| {
        MediaError::Message(format!(
            "{filter} filter is missing required parameter '{key}'"
        ))
    })
}

#[cfg(feature = "filter-crop")]
fn crop_output_info(
    input: FrameInfo,
    x: usize,
    y: usize,
    width: usize,
    height: usize,
) -> Result<FrameInfo> {
    let x_end = x.checked_add(width).ok_or(MediaError::LengthOverflow)?;
    let y_end = y.checked_add(height).ok_or(MediaError::LengthOverflow)?;
    if x_end > input.width || y_end > input.height {
        return Err(MediaError::IncompatibleFormat {
            format: input.format.name(),
            reason: format!(
                "crop rectangle x={x}:y={y}:w={width}:h={height} exceeds {}x{} input",
                input.width, input.height
            ),
        });
    }
    validate_crop_alignment(input.format, x, y, width, height)?;
    FrameInfo::new(width, height, input.format)
}

#[cfg(feature = "filter-crop")]
fn validate_crop_alignment(
    format: PixelFormat,
    x: usize,
    y: usize,
    width: usize,
    height: usize,
) -> Result<()> {
    let Some(sampling) = format.chroma_sampling() else {
        return Ok(());
    };
    let subsample_x = sampling.subsample_x();
    let subsample_y = sampling.subsample_y();
    if !x.is_multiple_of(subsample_x)
        || !width.is_multiple_of(subsample_x)
        || !y.is_multiple_of(subsample_y)
        || !height.is_multiple_of(subsample_y)
    {
        return Err(MediaError::IncompatibleFormat {
            format: format.name(),
            reason: format!(
                "crop coordinates and dimensions must be aligned to {subsample_x}x{subsample_y} samples"
            ),
        });
    }
    Ok(())
}

#[cfg(feature = "filter-crop")]
fn crop_frame_data(
    input: &[u8],
    info: FrameInfo,
    x: usize,
    y: usize,
    width: usize,
    height: usize,
) -> Result<Vec<u8>> {
    let output = crop_output_info(info, x, y, width, height)?;
    if input.len() != info.expected_len() {
        return Err(MediaError::BufferLength {
            expected: info.expected_len(),
            actual: input.len(),
        });
    }
    let mut data = vec![0; output.expected_len()];
    match info.format {
        PixelFormat::Rgb24 => crop_packed_rgb24(input, &mut data, info.width, x, y, width, height),
        PixelFormat::Gbrp8 => crop_full_planes(
            input,
            &mut data,
            info.width,
            info.height,
            1,
            x,
            y,
            width,
            height,
            3,
        ),
        PixelFormat::Gray { bit_depth } => crop_full_planes(
            input,
            &mut data,
            info.width,
            info.height,
            bit_depth.bytes_per_sample(),
            x,
            y,
            width,
            height,
            1,
        ),
        PixelFormat::PlanarYuv {
            chroma_sampling,
            bit_depth,
        } => crop_planar_yuv(
            input,
            &mut data,
            info.width,
            info.height,
            chroma_sampling,
            bit_depth,
            x,
            y,
            width,
            height,
        ),
    }
    Ok(data)
}

#[cfg(feature = "filter-scale")]
fn scale_frame_data(input: &[u8], info: FrameInfo, width: usize, height: usize) -> Result<Vec<u8>> {
    let output = FrameInfo::new(width, height, info.format)?;
    if input.len() != info.expected_len() {
        return Err(MediaError::BufferLength {
            expected: info.expected_len(),
            actual: input.len(),
        });
    }
    let mut data = vec![0; output.expected_len()];
    match info.format {
        PixelFormat::Rgb24 => {
            scale_packed_rgb24(input, &mut data, info.width, info.height, width, height)
        }
        PixelFormat::Gbrp8 => scale_full_planes(
            input,
            &mut data,
            info.width,
            info.height,
            width,
            height,
            1,
            3,
        ),
        PixelFormat::Gray { bit_depth } => scale_full_planes(
            input,
            &mut data,
            info.width,
            info.height,
            width,
            height,
            bit_depth.bytes_per_sample(),
            1,
        ),
        PixelFormat::PlanarYuv {
            chroma_sampling,
            bit_depth,
        } => scale_planar_yuv(
            input,
            &mut data,
            info.width,
            info.height,
            width,
            height,
            chroma_sampling,
            bit_depth,
        ),
    }
    Ok(data)
}

#[cfg(feature = "filter-crop")]
#[allow(clippy::too_many_arguments)]
fn crop_packed_rgb24(
    input: &[u8],
    output: &mut [u8],
    input_width: usize,
    x: usize,
    y: usize,
    width: usize,
    height: usize,
) {
    crop_plane_bytes(input, output, input_width, x, y, width, height, width, 3);
}

#[cfg(feature = "filter-scale")]
fn scale_packed_rgb24(
    input: &[u8],
    output: &mut [u8],
    input_width: usize,
    input_height: usize,
    output_width: usize,
    output_height: usize,
) {
    scale_plane_bytes(
        input,
        output,
        input_width,
        input_height,
        output_width,
        output_height,
        3,
    );
}

#[cfg(feature = "filter-crop")]
#[allow(clippy::too_many_arguments)]
fn crop_full_planes(
    input: &[u8],
    output: &mut [u8],
    input_width: usize,
    input_height: usize,
    bytes_per_sample: usize,
    x: usize,
    y: usize,
    width: usize,
    height: usize,
    planes: usize,
) {
    let input_plane_len = input_width * input_height * bytes_per_sample;
    let output_plane_len = width * height * bytes_per_sample;
    for plane in 0..planes {
        let input_start = plane * input_plane_len;
        let output_start = plane * output_plane_len;
        crop_plane_bytes(
            &input[input_start..input_start + input_plane_len],
            &mut output[output_start..output_start + output_plane_len],
            input_width,
            x,
            y,
            width,
            height,
            width,
            bytes_per_sample,
        );
    }
}

#[cfg(feature = "filter-scale")]
#[allow(clippy::too_many_arguments)]
fn scale_full_planes(
    input: &[u8],
    output: &mut [u8],
    input_width: usize,
    input_height: usize,
    output_width: usize,
    output_height: usize,
    bytes_per_sample: usize,
    planes: usize,
) {
    let input_plane_len = input_width * input_height * bytes_per_sample;
    let output_plane_len = output_width * output_height * bytes_per_sample;
    for plane in 0..planes {
        let input_start = plane * input_plane_len;
        let output_start = plane * output_plane_len;
        scale_plane_bytes(
            &input[input_start..input_start + input_plane_len],
            &mut output[output_start..output_start + output_plane_len],
            input_width,
            input_height,
            output_width,
            output_height,
            bytes_per_sample,
        );
    }
}

#[cfg(feature = "filter-crop")]
#[allow(clippy::too_many_arguments)]
fn crop_planar_yuv(
    input: &[u8],
    output: &mut [u8],
    input_width: usize,
    input_height: usize,
    chroma_sampling: ChromaSampling,
    bit_depth: SampleBitDepth,
    x: usize,
    y: usize,
    width: usize,
    height: usize,
) {
    let bytes_per_sample = bit_depth.bytes_per_sample();
    let input_luma_len = input_width * input_height * bytes_per_sample;
    let output_luma_len = width * height * bytes_per_sample;
    crop_plane_bytes(
        &input[..input_luma_len],
        &mut output[..output_luma_len],
        input_width,
        x,
        y,
        width,
        height,
        width,
        bytes_per_sample,
    );
    if chroma_sampling == ChromaSampling::Monochrome {
        return;
    }

    let subsample_x = chroma_sampling.subsample_x();
    let subsample_y = chroma_sampling.subsample_y();
    let input_chroma_width = input_width / subsample_x;
    let input_chroma_height = input_height / subsample_y;
    let output_chroma_width = width / subsample_x;
    let output_chroma_height = height / subsample_y;
    let input_chroma_len = input_chroma_width * input_chroma_height * bytes_per_sample;
    let output_chroma_len = output_chroma_width * output_chroma_height * bytes_per_sample;
    let chroma_x = x / subsample_x;
    let chroma_y = y / subsample_y;
    for plane in 0..2 {
        let input_start = input_luma_len + plane * input_chroma_len;
        let output_start = output_luma_len + plane * output_chroma_len;
        crop_plane_bytes(
            &input[input_start..input_start + input_chroma_len],
            &mut output[output_start..output_start + output_chroma_len],
            input_chroma_width,
            chroma_x,
            chroma_y,
            output_chroma_width,
            output_chroma_height,
            output_chroma_width,
            bytes_per_sample,
        );
    }
}

#[cfg(feature = "filter-scale")]
#[allow(clippy::too_many_arguments)]
fn scale_planar_yuv(
    input: &[u8],
    output: &mut [u8],
    input_width: usize,
    input_height: usize,
    output_width: usize,
    output_height: usize,
    chroma_sampling: ChromaSampling,
    bit_depth: SampleBitDepth,
) {
    let bytes_per_sample = bit_depth.bytes_per_sample();
    let input_luma_len = input_width * input_height * bytes_per_sample;
    let output_luma_len = output_width * output_height * bytes_per_sample;
    scale_plane_bytes(
        &input[..input_luma_len],
        &mut output[..output_luma_len],
        input_width,
        input_height,
        output_width,
        output_height,
        bytes_per_sample,
    );
    if chroma_sampling == ChromaSampling::Monochrome {
        return;
    }

    let subsample_x = chroma_sampling.subsample_x();
    let subsample_y = chroma_sampling.subsample_y();
    let input_chroma_width = input_width / subsample_x;
    let input_chroma_height = input_height / subsample_y;
    let output_chroma_width = output_width / subsample_x;
    let output_chroma_height = output_height / subsample_y;
    let input_chroma_len = input_chroma_width * input_chroma_height * bytes_per_sample;
    let output_chroma_len = output_chroma_width * output_chroma_height * bytes_per_sample;
    for plane in 0..2 {
        let input_start = input_luma_len + plane * input_chroma_len;
        let output_start = output_luma_len + plane * output_chroma_len;
        scale_plane_bytes(
            &input[input_start..input_start + input_chroma_len],
            &mut output[output_start..output_start + output_chroma_len],
            input_chroma_width,
            input_chroma_height,
            output_chroma_width,
            output_chroma_height,
            bytes_per_sample,
        );
    }
}

#[cfg(feature = "filter-crop")]
#[allow(clippy::too_many_arguments)]
fn crop_plane_bytes(
    input: &[u8],
    output: &mut [u8],
    input_width: usize,
    x: usize,
    y: usize,
    width: usize,
    height: usize,
    output_width: usize,
    bytes_per_sample: usize,
) {
    let row_bytes = width * bytes_per_sample;
    let input_stride = input_width * bytes_per_sample;
    let output_stride = output_width * bytes_per_sample;
    for row in 0..height {
        let input_start = (y + row) * input_stride + x * bytes_per_sample;
        let output_start = row * output_stride;
        output[output_start..output_start + row_bytes]
            .copy_from_slice(&input[input_start..input_start + row_bytes]);
    }
}

#[cfg(feature = "filter-scale")]
#[allow(clippy::too_many_arguments)]
fn scale_plane_bytes(
    input: &[u8],
    output: &mut [u8],
    input_width: usize,
    input_height: usize,
    output_width: usize,
    output_height: usize,
    bytes_per_sample: usize,
) {
    let input_stride = input_width * bytes_per_sample;
    let output_stride = output_width * bytes_per_sample;
    for y in 0..output_height {
        let source_y = y * input_height / output_height;
        for x in 0..output_width {
            let source_x = x * input_width / output_width;
            let input_start = source_y * input_stride + source_x * bytes_per_sample;
            let output_start = y * output_stride + x * bytes_per_sample;
            output[output_start..output_start + bytes_per_sample]
                .copy_from_slice(&input[input_start..input_start + bytes_per_sample]);
        }
    }
}

/// Deterministic pattern produced by the `pattern` source filter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(feature = "filter-pattern")]
pub enum PatternKind {
    /// Solid black frames.
    Black,
    /// Moving checkerboard frames.
    Checker,
    /// Moving luma/chroma gradient frames.
    Gradient,
    /// Moving colored block frames.
    ColorBlocks,
}

#[cfg(feature = "filter-pattern")]
impl PatternKind {
    /// Canonical names accepted by the pattern parser.
    pub const CANONICAL_NAMES: &'static [&'static str] = PATTERN_SOURCE_NAMES;

    /// Parse a pattern kind by name.
    pub fn parse(value: &str) -> Result<Self> {
        value.parse()
    }

    /// Canonical name for this pattern kind.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Black => "black",
            Self::Checker => "checker",
            Self::Gradient => "gradient",
            Self::ColorBlocks => "color_blocks",
        }
    }
}

#[cfg(feature = "filter-pattern")]
impl FromStr for PatternKind {
    type Err = MediaError;

    fn from_str(value: &str) -> Result<Self> {
        match value.trim() {
            "black" => Ok(Self::Black),
            "checker" => Ok(Self::Checker),
            "gradient" => Ok(Self::Gradient),
            "color_blocks" | "blocks" => Ok(Self::ColorBlocks),
            other => Err(MediaError::Message(format!(
                "unknown pattern source '{other}'; accepted patterns: {}",
                PatternKind::CANONICAL_NAMES.join(", ")
            ))),
        }
    }
}

/// Source stage that generates deterministic raw frames from a pattern.
#[derive(Debug, Clone)]
#[cfg(feature = "filter-pattern")]
pub struct PatternSource {
    info: FrameInfo,
    pattern: PatternKind,
    frames_remaining: usize,
    frame_index: usize,
}

#[cfg(feature = "filter-pattern")]
impl PatternSource {
    /// Create a finite pattern source.
    pub fn new(info: FrameInfo, pattern: PatternKind, frames: usize) -> Result<Self> {
        validate_pattern_format(info.format)?;
        Ok(Self {
            info,
            pattern,
            frames_remaining: frames,
            frame_index: 0,
        })
    }

    /// Pattern emitted by this source.
    pub const fn pattern(&self) -> PatternKind {
        self.pattern
    }

    /// Frame metadata emitted by this source.
    pub const fn info(&self) -> FrameInfo {
        self.info
    }

    /// Number of frames still available before EOF.
    pub const fn frames_remaining(&self) -> usize {
        self.frames_remaining
    }

    /// Fill `output` with the next generated frame.
    ///
    /// Returns `Ok(false)` when the finite pattern source is exhausted.
    pub fn fill_frame(&mut self, output: &mut [u8]) -> Result<bool> {
        if self.frames_remaining == 0 {
            return Ok(false);
        }
        fill_pattern_frame(self.info, self.pattern, self.frame_index, output)?;
        self.frames_remaining -= 1;
        self.frame_index += 1;
        Ok(true)
    }
}

#[cfg(feature = "filter-pattern")]
impl Source for PatternSource {
    type Output = Frame;

    fn pull(&mut self) -> Result<Option<Self::Output>> {
        let mut data = vec![0; self.info.expected_len()];
        if !self.fill_frame(&mut data)? {
            return Ok(None);
        }
        Frame::new(self.info, data).map(Some)
    }
}

#[cfg(feature = "filter-pattern")]
impl RawVideoFrameSource for PatternSource {
    fn read_frame(&mut self, frame: &mut [u8]) -> Result<bool> {
        self.fill_frame(frame)
    }
}

#[cfg(feature = "filter-pattern")]
/// Generate a finite raw byte stream for a deterministic pattern.
pub fn generate_pattern_stream(
    info: FrameInfo,
    pattern: PatternKind,
    frames: usize,
) -> Result<Vec<u8>> {
    let total_len = info
        .expected_len()
        .checked_mul(frames)
        .ok_or(MediaError::LengthOverflow)?;
    let mut output = Vec::with_capacity(total_len);
    let mut source = PatternSource::new(info, pattern, frames)?;
    while let Some(frame) = source.pull()? {
        output.extend_from_slice(frame.data());
    }
    Ok(output)
}

#[cfg(feature = "filter-pattern")]
/// Generate one deterministic raw frame for a pattern.
pub fn pattern_frame_data(info: FrameInfo, pattern: PatternKind, frame: usize) -> Result<Vec<u8>> {
    validate_pattern_format(info.format)?;
    let mut output = vec![0; info.expected_len()];
    fill_pattern_frame(info, pattern, frame, &mut output)?;
    Ok(output)
}

#[cfg(feature = "filter-pattern")]
fn validate_pattern_format(format: PixelFormat) -> Result<()> {
    match format {
        PixelFormat::PlanarYuv { .. }
        | PixelFormat::Gray { .. }
        | PixelFormat::Gbrp8
        | PixelFormat::Rgb24 => Ok(()),
    }
}

#[cfg(feature = "filter-pattern")]
fn fill_pattern_frame(
    info: FrameInfo,
    pattern: PatternKind,
    frame: usize,
    output: &mut [u8],
) -> Result<()> {
    let expected = info.expected_len();
    if output.len() != expected {
        return Err(MediaError::BufferLength {
            expected,
            actual: output.len(),
        });
    }
    validate_pattern_format(info.format)?;
    match info.format {
        PixelFormat::Rgb24 => fill_pattern_rgb24(info.width, info.height, pattern, frame, output),
        PixelFormat::Gbrp8 => fill_pattern_gbrp8(info.width, info.height, pattern, frame, output),
        PixelFormat::Gray { bit_depth } => {
            fill_pattern_gray(info.width, info.height, bit_depth, pattern, frame, output)
        }
        PixelFormat::PlanarYuv {
            chroma_sampling,
            bit_depth,
        } => fill_pattern_planar_yuv(
            info.width,
            info.height,
            chroma_sampling,
            bit_depth,
            pattern,
            frame,
            output,
        ),
    }
    Ok(())
}

#[cfg(feature = "filter-pattern")]
fn fill_pattern_rgb24(
    width: usize,
    height: usize,
    pattern: PatternKind,
    frame: usize,
    output: &mut [u8],
) {
    for y in 0..height {
        for x in 0..width {
            let (r, g, b) = pattern_sample(pattern, x, y, frame);
            let offset = (y * width + x) * 3;
            output[offset] = r;
            output[offset + 1] = g;
            output[offset + 2] = b;
        }
    }
}

#[cfg(feature = "filter-pattern")]
fn fill_pattern_gbrp8(
    width: usize,
    height: usize,
    pattern: PatternKind,
    frame: usize,
    output: &mut [u8],
) {
    let pixels = width * height;
    for y in 0..height {
        for x in 0..width {
            let idx = y * width + x;
            let (r, g, b) = pattern_sample(pattern, x, y, frame);
            output[idx] = g;
            output[pixels + idx] = b;
            output[2 * pixels + idx] = r;
        }
    }
}

#[cfg(feature = "filter-pattern")]
fn fill_pattern_gray(
    width: usize,
    height: usize,
    bit_depth: SampleBitDepth,
    pattern: PatternKind,
    frame: usize,
    output: &mut [u8],
) {
    for y in 0..height {
        for x in 0..width {
            let (sample, _, _) = pattern_sample(pattern, x, y, frame);
            write_pattern_sample(output, y * width + x, sample, bit_depth);
        }
    }
}

#[cfg(feature = "filter-pattern")]
#[allow(clippy::too_many_arguments)]
fn fill_pattern_planar_yuv(
    width: usize,
    height: usize,
    chroma_sampling: ChromaSampling,
    bit_depth: SampleBitDepth,
    pattern: PatternKind,
    frame: usize,
    output: &mut [u8],
) {
    for y in 0..height {
        for x in 0..width {
            let (luma, _, _) = pattern_sample(pattern, x, y, frame);
            write_pattern_sample(output, y * width + x, luma, bit_depth);
        }
    }

    if chroma_sampling == ChromaSampling::Monochrome {
        return;
    }

    let bytes_per_sample = bit_depth.bytes_per_sample();
    let luma_len = width * height * bytes_per_sample;
    let subsample_x = chroma_sampling.subsample_x();
    let subsample_y = chroma_sampling.subsample_y();
    let chroma_width = width / subsample_x;
    let chroma_height = height / subsample_y;
    let chroma_len = chroma_width * chroma_height * bytes_per_sample;
    let (u_plane, v_plane) = output[luma_len..luma_len + chroma_len * 2].split_at_mut(chroma_len);

    for chroma_y in 0..chroma_height {
        for chroma_x in 0..chroma_width {
            let mut u_sum = 0u32;
            let mut v_sum = 0u32;
            for dy in 0..subsample_y {
                for dx in 0..subsample_x {
                    let x = chroma_x * subsample_x + dx;
                    let y = chroma_y * subsample_y + dy;
                    let (_, u, v) = pattern_sample(pattern, x, y, frame);
                    u_sum += u32::from(u);
                    v_sum += u32::from(v);
                }
            }
            let denom = (subsample_x * subsample_y) as u32;
            let index = chroma_y * chroma_width + chroma_x;
            write_pattern_sample(u_plane, index, (u_sum / denom) as u8, bit_depth);
            write_pattern_sample(v_plane, index, (v_sum / denom) as u8, bit_depth);
        }
    }
}

#[cfg(feature = "filter-pattern")]
fn write_pattern_sample(
    output: &mut [u8],
    sample_index: usize,
    sample: u8,
    bit_depth: SampleBitDepth,
) {
    let sample = scale_sample_bit_depth(
        u16::from(sample),
        SampleBitDepth::new(8).expect("8-bit samples must be supported"),
        bit_depth,
    );
    write_planar_sample(output, sample_index, sample, bit_depth)
        .expect("validated pattern output must contain every sample");
}

#[cfg(feature = "filter-pattern")]
fn pattern_sample(pattern: PatternKind, x: usize, y: usize, frame: usize) -> (u8, u8, u8) {
    match pattern {
        PatternKind::Black => (0, 0, 0),
        PatternKind::Checker => {
            if ((x / 8) + (y / 8) + frame) & 1 == 0 {
                (208, 176, 80)
            } else {
                (48, 96, 160)
            }
        }
        PatternKind::Gradient => (
            ((x * 7 + y * 5 + frame * 17) & 0xFF) as u8,
            ((64 + x * 3 + frame * 11) & 0xFF) as u8,
            ((96 + y * 4 + frame * 13) & 0xFF) as u8,
        ),
        PatternKind::ColorBlocks => {
            const PALETTE: [(u8, u8, u8); 4] = [
                (32, 128, 128),
                (80, 96, 176),
                (144, 176, 96),
                (224, 112, 144),
            ];
            PALETTE[((x / 8) + (y / 8) * 2 + frame) % PALETTE.len()]
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn filter_manifest_reports_compiled_filters() {
        assert_eq!(
            filter_manifest("pattern").is_some(),
            cfg!(feature = "filter-pattern")
        );
        assert_eq!(
            filter_manifest("identity").is_some(),
            cfg!(feature = "filter-identity")
        );
        assert_eq!(
            filter_manifest("crop").is_some(),
            cfg!(feature = "filter-crop")
        );
        assert_eq!(
            filter_manifest("scale").is_some(),
            cfg!(feature = "filter-scale")
        );
    }

    #[cfg(feature = "filter-pattern")]
    #[test]
    fn pattern_manifest_reports_source_contract() {
        let pattern = filter_manifest("pattern").expect("pattern manifest");
        assert_eq!(pattern.stage, FilterStageKind::Source);
        assert_eq!(pattern.status, FilterStatus::Implemented);
        assert_eq!(pattern.feature, "filter-pattern");
        assert_eq!(pattern.spec.forms[0].syntax, "pattern=<name>");
        assert_eq!(pattern.spec.parameters[0].name, "name");
        assert_eq!(
            pattern.spec.parameters[0].value,
            FilterSpecValue::Choice(PATTERN_SOURCE_NAMES)
        );
    }

    #[cfg(feature = "filter-crop")]
    #[test]
    fn crop_manifest_reports_transform_contract() {
        let crop = filter_manifest("crop").expect("crop manifest");
        assert_eq!(crop.stage, FilterStageKind::Transform);
        assert_eq!(crop.status, FilterStatus::Implemented);
        assert_eq!(
            crop.spec.forms[0].syntax,
            "crop=x=<px>:y=<px>:w=<px>:h=<px>"
        );
    }

    #[cfg(feature = "filter-scale")]
    #[test]
    fn scale_manifest_reports_transform_contract() {
        let scale = filter_manifest("scale").expect("scale manifest");
        assert_eq!(scale.stage, FilterStageKind::Transform);
        assert_eq!(scale.status, FilterStatus::Implemented);
        assert_eq!(scale.spec.forms[0].syntax, "scale=w=<px>:h=<px>");
    }

    #[cfg(feature = "filter-pattern")]
    #[test]
    fn pattern_kind_parses_aliases_and_reports_canonical_names() {
        assert_eq!(PatternKind::parse("black").unwrap(), PatternKind::Black);
        assert_eq!(
            PatternKind::parse("blocks").unwrap(),
            PatternKind::ColorBlocks
        );
        assert_eq!(
            PatternKind::CANONICAL_NAMES,
            ["black", "checker", "gradient", "color_blocks"]
        );
    }

    #[cfg(feature = "filter-identity")]
    #[test]
    fn identity_filter_preserves_frame() {
        let info = FrameInfo::new(2, 2, PixelFormat::Rgb24).unwrap();
        let frame = Frame::new(info, vec![9; info.expected_len()]).unwrap();
        let mut filter = IdentityFilter;
        let out = filter.process(frame.clone()).unwrap();
        assert_eq!(out, vec![frame]);
    }

    #[cfg(feature = "filter-crop")]
    #[test]
    fn crop_filter_extracts_aligned_yuv420_region() {
        let info = FrameInfo::new(4, 4, PixelFormat::Yuv420p8).unwrap();
        let input = [
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 100, 101, 102, 103, 200, 201,
            202, 203,
        ];
        let frame = Frame::new(info, input.to_vec()).unwrap();
        let mut filter = CropFilter::new(2, 2, 2, 2).unwrap();
        let output = filter.process(frame).unwrap();

        assert_eq!(output.len(), 1);
        assert_eq!(
            output[0].info(),
            FrameInfo::new(2, 2, PixelFormat::Yuv420p8).unwrap()
        );
        assert_eq!(output[0].data(), &[10, 11, 14, 15, 103, 203]);
    }

    #[cfg(feature = "filter-crop")]
    #[test]
    fn crop_filter_rejects_unaligned_yuv420_region() {
        let info = FrameInfo::new(4, 4, PixelFormat::Yuv420p8).unwrap();
        let err = CropFilter::new(1, 0, 2, 2)
            .unwrap()
            .output_info(info)
            .unwrap_err();
        assert!(err.to_string().contains("aligned to 2x2"), "{err}");
    }

    #[cfg(feature = "filter-scale")]
    #[test]
    fn scale_filter_resizes_yuv420_with_nearest_neighbor() {
        let info = FrameInfo::new(2, 2, PixelFormat::Yuv420p8).unwrap();
        let frame = Frame::new(info, vec![1, 2, 3, 4, 5, 6]).unwrap();
        let mut filter = ScaleFilter::new(4, 4).unwrap();
        let output = filter.process(frame).unwrap();

        assert_eq!(output.len(), 1);
        assert_eq!(
            output[0].info(),
            FrameInfo::new(4, 4, PixelFormat::Yuv420p8).unwrap()
        );
        assert_eq!(
            output[0].data(),
            &[1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6,]
        );
    }

    #[cfg(all(feature = "filter-crop", feature = "filter-scale"))]
    #[test]
    fn filter_pipeline_output_info_tracks_geometry_changes() {
        let input = FrameInfo::new(16, 16, PixelFormat::Yuv420p8).unwrap();
        let transforms = [
            FilterStageSpec::new("crop=x=0:y=0:w=8:h=8").unwrap(),
            FilterStageSpec::new("scale=w=16:h=16").unwrap(),
        ];
        let output = filter_pipeline_output_info(input, &transforms).unwrap();
        assert_eq!(output, input);
    }

    #[cfg(feature = "filter-pattern")]
    #[test]
    fn pattern_source_generates_black_yuv420_frame() {
        let info = FrameInfo::new(8, 8, PixelFormat::Yuv420p8).unwrap();
        let mut source = PatternSource::new(info, PatternKind::Black, 1).unwrap();
        let frame = source.pull().unwrap().expect("frame");
        assert_eq!(frame.data(), vec![0; info.expected_len()]);
        assert!(source.pull().unwrap().is_none());
    }

    #[cfg(feature = "filter-pattern")]
    #[test]
    fn pattern_stream_generates_all_requested_frames() {
        let info = FrameInfo::new(8, 8, PixelFormat::Yuv444p8).unwrap();
        let data = generate_pattern_stream(info, PatternKind::Checker, 2).unwrap();
        assert_eq!(data.len(), info.expected_len() * 2);
        assert_ne!(&data[..info.expected_len()], &data[info.expected_len()..]);
    }

    #[cfg(feature = "filter-pattern")]
    #[test]
    fn pattern_source_generates_rgb24_frame() {
        let info = FrameInfo::new(8, 8, PixelFormat::Rgb24).unwrap();
        let mut source = PatternSource::new(info, PatternKind::Checker, 1).unwrap();
        let frame = source.pull().unwrap().expect("frame");
        assert_eq!(frame.data().len(), info.expected_len());
        assert!(frame.data().chunks_exact(3).any(|pixel| pixel != [0, 0, 0]));
    }

    #[cfg(feature = "filter-pattern")]
    #[test]
    fn pattern_source_generates_high_bit_depth_planar_frame() {
        let info = FrameInfo::new(8, 8, PixelFormat::yuv444(10).unwrap()).unwrap();
        let frame = pattern_frame_data(info, PatternKind::Gradient, 0).unwrap();
        assert_eq!(frame.len(), info.expected_len());
        let first = crate::read_planar_sample(&frame, 1, info.format.bit_depth()).unwrap();
        assert!(first > 0);
    }
}