rff-filter 0.2.2

Remade FFmpeg (Rust): frame filters (scale, crop) — the libavfilter equivalent.
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
//! `rff-filter` — frame filters, the `libavfilter` equivalent.
//!
//! A [`FilterChain`] is the engine's `-vf` graph: an ordered list of filters
//! that each transform a raw [`VideoFrame`] into another. Built from an
//! FFmpeg-style spec string (`scale=320:240,crop=100:100:0:0`) and applied
//! between decode and encode in the transcode loop.
//!
//! Filters operate on **8-bit planar YUV** (4:2:0 / 4:2:2 / 4:4:4) for now;
//! other layouts return [`Error::Unsupported`]. Each filter is a 1-in/1-out
//! transform.

mod audio;

pub use audio::{trim_audio_frame, AudioFilterChain};

use rff_core::{ColorRange, Error, PixelFormat, Result, VideoFrame};

/// One frame transform. Implementors map a video frame to a new video frame.
pub trait Filter: Send {
    /// The filter's CLI name (`scale`, `crop`, ...).
    fn name(&self) -> &'static str;

    /// Transform one frame.
    fn filter(&mut self, frame: VideoFrame) -> Result<VideoFrame>;

    /// Report the output dimensions this filter produces for a given input
    /// size, without running it (so the muxer can size the output stream up
    /// front). Defaults to unchanged.
    fn output_dims(&self, in_w: u32, in_h: u32) -> (u32, u32) {
        (in_w, in_h)
    }

    /// The luma/chroma range this filter's output is in, when the filter is the
    /// one that decides it. Only a colour conversion knows this; everything else
    /// passes the incoming range through, hence the `None` default.
    ///
    /// The muxer needs it: writing full-range samples into a container that
    /// labels them limited-range silently rescales them on the way out.
    fn output_color_range(&self) -> Option<ColorRange> {
        None
    }

    /// Tell the filter what range its input is in. Only a colour conversion
    /// cares, and only when the spec string did not pin the range itself.
    fn set_source_color_range(&mut self, _range: ColorRange) {}
}

/// An ordered chain of filters (the `-vf` graph).
#[derive(Default)]
pub struct FilterChain {
    filters: Vec<Box<dyn Filter>>,
}

impl FilterChain {
    /// Parse an FFmpeg-style filter spec: filters separated by `,`, each
    /// `name=a:b:c`. An empty/blank spec yields an empty (pass-through) chain.
    pub fn parse(spec: &str) -> Result<FilterChain> {
        let mut filters: Vec<Box<dyn Filter>> = Vec::new();
        for token in spec.split(',') {
            let token = token.trim();
            if token.is_empty() {
                continue;
            }
            let (name, args) = token.split_once('=').unwrap_or((token, ""));
            let parts: Vec<&str> = if args.is_empty() {
                Vec::new()
            } else {
                args.split(':').collect()
            };
            match name {
                "scale" => filters.push(Box::new(Scale::parse(&parts)?)),
                "crop" => filters.push(Box::new(Crop::parse(&parts)?)),
                "hflip" => filters.push(Box::new(HFlip)),
                "vflip" => filters.push(Box::new(VFlip)),
                "transpose" => filters.push(Box::new(Transpose::parse(&parts)?)),
                "pad" => filters.push(Box::new(Pad::parse(&parts)?)),
                "format" => filters.push(Box::new(FormatConv::parse(&parts)?)),
                "setrange" => filters.push(Box::new(SetRange::parse(&parts)?)),
                "negate" => filters.push(Box::new(Negate)),
                "gray" | "grayscale" => filters.push(Box::new(Grayscale)),
                other => return Err(Error::unsupported(format!("unknown filter `{other}`"))),
            }
        }
        Ok(FilterChain { filters })
    }

    pub fn is_empty(&self) -> bool {
        self.filters.is_empty()
    }

    /// Insert a range conversion at the FRONT of the chain, so every later
    /// filter (notably a colour conversion) sees full-range input.
    pub fn prepend_range_conversion(&mut self, to_full: bool) {
        self.filters.insert(0, Box::new(SetRange { to_full }));
    }

    /// Declare the range of the frames entering the chain, so colour
    /// conversions interpret Y'CbCr correctly instead of assuming full-range.
    pub fn set_source_color_range(&mut self, range: ColorRange) {
        for f in &mut self.filters {
            f.set_source_color_range(range);
        }
    }

    /// The colour range the chain's output is in, if any filter in it decides.
    /// Later filters win, matching evaluation order.
    pub fn output_color_range(&self) -> Option<ColorRange> {
        self.filters
            .iter()
            .rev()
            .find_map(|f| f.output_color_range())
    }

    /// Run every filter in order.
    pub fn apply(&mut self, mut frame: VideoFrame) -> Result<VideoFrame> {
        for filter in &mut self.filters {
            frame = filter.filter(frame)?;
        }
        Ok(frame)
    }

    /// The dimensions a frame of `(w, h)` ends up with after the whole chain.
    pub fn output_dims(&self, mut w: u32, mut h: u32) -> (u32, u32) {
        for filter in &self.filters {
            (w, h) = filter.output_dims(w, h);
        }
        (w, h)
    }
}

// ---------------------------------------------------------------------------
// filter_complex (multi-input graphs)
// ---------------------------------------------------------------------------

/// A `-filter_complex` graph. For now it models the most-used multi-input
/// operation: **overlay** — compositing a second input over the first (logo /
/// watermark / picture-in-picture). The labels (`[0:v][1:v]...`) are parsed but
/// the wiring is fixed: input 0 is the base, input 1 the overlay.
pub struct FilterComplex {
    /// `(x, y)` placement of the overlay's top-left on the base, or `None` if
    /// the graph has no overlay.
    pub overlay: Option<(u32, u32)>,
}

impl FilterComplex {
    /// Parse a filter_complex spec. Recognizes `overlay=X:Y` (numeric, plus the
    /// common corner shorthands `W-w`, `H-h` resolved against the base size at
    /// apply time — for now numeric offsets only).
    pub fn parse(spec: &str) -> Result<FilterComplex> {
        if let Some(pos) = spec.find("overlay") {
            let after = spec[pos + "overlay".len()..].trim_start_matches('=');
            // Stop at the next filter (`,`) or output label (`[`).
            let args = after.split([',', '[', ';']).next().unwrap_or("");
            let mut parts = args.split(':');
            let x = parts
                .next()
                .and_then(|s| s.trim().parse().ok())
                .unwrap_or(0);
            let y = parts
                .next()
                .and_then(|s| s.trim().parse().ok())
                .unwrap_or(0);
            return Ok(FilterComplex {
                overlay: Some((x, y)),
            });
        }
        Err(Error::unsupported(format!(
            "filter_complex: unsupported graph `{spec}` (only `overlay` so far)"
        )))
    }
}

/// Composite `over` onto a copy of `base` at `(x, y)`, both 8-bit planar YUV of
/// the same format. Overlay pixels replace the base (YUV carries no alpha);
/// the overlay is clipped to the base bounds and `(x, y)` snaps down to the
/// chroma grid so the planes stay aligned.
pub fn overlay(base: VideoFrame, over: &VideoFrame, x: u32, y: u32) -> Result<VideoFrame> {
    ensure_planar_yuv(&base, "overlay")?;
    ensure_planar_yuv(over, "overlay")?;
    if base.format != over.format {
        return Err(Error::unsupported(format!(
            "overlay: base {} vs overlay {} — convert with the `format` filter first",
            base.format.name(),
            over.format.name()
        )));
    }
    let (sx, sy) = subsampling(base.format)?;
    let (x, y) = (x - x % sx, y - y % sy);
    let mut base = base;
    for i in 0..3 {
        let (div_x, div_y) = if i == 0 { (1, 1) } else { (sx, sy) };
        let (ox, oy) = ((x / div_x) as usize, (y / div_y) as usize);
        let (ow, oh) = plane_dims(over.format, over.width, over.height, i)?;
        let (bw, bh) = plane_dims(base.format, base.width, base.height, i)?;
        let (bw, bh) = (bw as usize, bh as usize);
        let (bstride, ostride) = (base.strides[i], over.strides[i]);
        for row in 0..oh as usize {
            let by = oy + row;
            if by >= bh {
                break;
            }
            let copy_w = (ow as usize).min(bw.saturating_sub(ox));
            if copy_w == 0 {
                break;
            }
            let bstart = by * bstride + ox;
            let ostart = row * ostride;
            base.planes[i][bstart..bstart + copy_w]
                .copy_from_slice(&over.planes[i][ostart..ostart + copy_w]);
        }
    }
    Ok(base)
}

// ---------------------------------------------------------------------------
// Pixel-format helpers
// ---------------------------------------------------------------------------

/// Chroma subsampling factors `(x, y)` for a planar YUV format.
fn subsampling(format: PixelFormat) -> Result<(u32, u32)> {
    match format {
        PixelFormat::Yuv420p => Ok((2, 2)),
        PixelFormat::Yuv422p => Ok((2, 1)),
        PixelFormat::Yuv444p => Ok((1, 1)),
        other => Err(Error::unsupported(format!(
            "filter: pixel format `{}` (only 8-bit planar YUV is supported)",
            other.name()
        ))),
    }
}

/// Width/height of plane `index` for `format` at frame size `(w, h)`.
fn plane_dims(format: PixelFormat, w: u32, h: u32, index: usize) -> Result<(u32, u32)> {
    if index == 0 {
        Ok((w, h))
    } else {
        let (sx, sy) = subsampling(format)?;
        Ok((w.div_ceil(sx), h.div_ceil(sy)))
    }
}

fn ensure_planar_yuv(frame: &VideoFrame, op: &str) -> Result<()> {
    subsampling(frame.format)?; // rejects non-planar / 10-bit
    if frame.planes.len() < 3 || frame.strides.len() < 3 {
        return Err(Error::invalid(format!(
            "{op}: expected 3 planes, got {}",
            frame.planes.len()
        )));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// scale (bilinear)
// ---------------------------------------------------------------------------

/// `scale=W:H` — resize to an exact width and height (bilinear). Either
/// dimension may be `-1` to preserve the aspect ratio (rounded to an even size
/// so chroma stays aligned); both `-1` is rejected.
struct Scale {
    width: i32,
    height: i32,
}

impl Scale {
    fn parse(args: &[&str]) -> Result<Scale> {
        let [w, h] = args else {
            return Err(Error::Option("scale: expected scale=W:H".into()));
        };
        let parse = |s: &str| {
            s.trim()
                .parse::<i32>()
                .ok()
                .filter(|&v| v == -1 || v > 0)
                .ok_or_else(|| Error::Option(format!("scale: bad dimension `{s}`")))
        };
        let (width, height) = (parse(w)?, parse(h)?);
        if width == -1 && height == -1 {
            return Err(Error::Option(
                "scale: at least one of W/H must be a fixed size".into(),
            ));
        }
        Ok(Scale { width, height })
    }

    /// Resolve target dimensions, filling a `-1` from the source aspect ratio.
    fn resolve(&self, in_w: u32, in_h: u32) -> (u32, u32) {
        let even = |v: u32| {
            let v = v.max(2);
            if v % 2 == 0 {
                v
            } else {
                v + 1
            }
        };
        match (self.width, self.height) {
            (w, h) if w > 0 && h > 0 => (w as u32, h as u32),
            (-1, h) => {
                let h = h as u32;
                let w = (in_w as u64 * h as u64 / in_h.max(1) as u64) as u32;
                (even(w), h)
            }
            (w, _) => {
                let w = w as u32;
                let h = (in_h as u64 * w as u64 / in_w.max(1) as u64) as u32;
                (w, even(h))
            }
        }
    }
}

impl Filter for Scale {
    fn name(&self) -> &'static str {
        "scale"
    }

    fn output_dims(&self, in_w: u32, in_h: u32) -> (u32, u32) {
        self.resolve(in_w, in_h)
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        ensure_planar_yuv(&src, "scale")?;
        let (out_w, out_h) = self.resolve(src.width, src.height);
        let mut planes = Vec::with_capacity(src.planes.len());
        let mut strides = Vec::with_capacity(src.planes.len());
        for (i, plane) in src.planes.iter().enumerate() {
            let (sw, sh) = plane_dims(src.format, src.width, src.height, i)?;
            let (dw, dh) = plane_dims(src.format, out_w, out_h, i)?;
            planes.push(bilinear(plane, src.strides[i], sw, sh, dw, dh));
            strides.push(dw as usize);
        }
        Ok(VideoFrame {
            width: out_w,
            height: out_h,
            format: src.format,
            planes,
            strides,
            pts: src.pts,
        })
    }
}

/// Bilinear-resample one 8-bit plane from `(sw, sh)` to `(dw, dh)`. Uses
/// half-pixel-centered sampling and edge clamping; output is tightly packed.
fn bilinear(src: &[u8], src_stride: usize, sw: u32, sh: u32, dw: u32, dh: u32) -> Vec<u8> {
    let mut out = vec![0u8; (dw * dh) as usize];
    if sw == 0 || sh == 0 || dw == 0 || dh == 0 {
        return out;
    }
    let x_ratio = sw as f32 / dw as f32;
    let y_ratio = sh as f32 / dh as f32;
    let at = |x: u32, y: u32| src[y as usize * src_stride + x as usize] as f32;

    for dy in 0..dh {
        let fy = (((dy as f32 + 0.5) * y_ratio) - 0.5).max(0.0);
        let y0 = fy.floor() as u32;
        let y1 = (y0 + 1).min(sh - 1);
        let wy = fy - y0 as f32;
        for dx in 0..dw {
            let fx = (((dx as f32 + 0.5) * x_ratio) - 0.5).max(0.0);
            let x0 = fx.floor() as u32;
            let x1 = (x0 + 1).min(sw - 1);
            let wx = fx - x0 as f32;

            let top = at(x0, y0) * (1.0 - wx) + at(x1, y0) * wx;
            let bottom = at(x0, y1) * (1.0 - wx) + at(x1, y1) * wx;
            let value = top * (1.0 - wy) + bottom * wy;
            out[(dy * dw + dx) as usize] = value.round().clamp(0.0, 255.0) as u8;
        }
    }
    out
}

// ---------------------------------------------------------------------------
// crop
// ---------------------------------------------------------------------------

/// `crop=W:H:X:Y` — extract a rectangle. Offsets/size must align to the chroma
/// grid (e.g. even for 4:2:0) so the chroma planes stay sample-aligned.
struct Crop {
    w: u32,
    h: u32,
    x: u32,
    y: u32,
}

impl Crop {
    fn parse(args: &[&str]) -> Result<Crop> {
        let [w, h, x, y] = args else {
            return Err(Error::Option("crop: expected crop=W:H:X:Y".into()));
        };
        let num = |s: &str| {
            s.trim()
                .parse::<u32>()
                .map_err(|_| Error::Option(format!("crop: bad value `{s}`")))
        };
        Ok(Crop {
            w: num(w)?,
            h: num(h)?,
            x: num(x)?,
            y: num(y)?,
        })
    }
}

impl Filter for Crop {
    fn name(&self) -> &'static str {
        "crop"
    }

    fn output_dims(&self, _in_w: u32, _in_h: u32) -> (u32, u32) {
        (self.w, self.h)
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        ensure_planar_yuv(&src, "crop")?;
        if self.x + self.w > src.width || self.y + self.h > src.height {
            return Err(Error::Option(format!(
                "crop: rectangle {}x{}+{}+{} exceeds frame {}x{}",
                self.w, self.h, self.x, self.y, src.width, src.height
            )));
        }
        let (sx, sy) = subsampling(src.format)?;
        if self.x % sx != 0 || self.w % sx != 0 || self.y % sy != 0 || self.h % sy != 0 {
            return Err(Error::Option(
                "crop: offset/size must align to the chroma grid".into(),
            ));
        }

        let mut planes = Vec::with_capacity(src.planes.len());
        let mut strides = Vec::with_capacity(src.planes.len());
        for (i, plane) in src.planes.iter().enumerate() {
            // Plane 0 uses full-res geometry; chroma planes scale by subsampling.
            let (div_x, div_y) = if i == 0 { (1, 1) } else { (sx, sy) };
            let (px, py) = (self.x / div_x, self.y / div_y);
            let (pw, ph) = (self.w / div_x, self.h / div_y);

            let mut out = Vec::with_capacity((pw * ph) as usize);
            for row in 0..ph {
                let start = (py + row) as usize * src.strides[i] + px as usize;
                out.extend_from_slice(&plane[start..start + pw as usize]);
            }
            planes.push(out);
            strides.push(pw as usize);
        }
        Ok(VideoFrame {
            width: self.w,
            height: self.h,
            format: src.format,
            planes,
            strides,
            pts: src.pts,
        })
    }
}

// ---------------------------------------------------------------------------
// hflip / vflip
// ---------------------------------------------------------------------------

/// `hflip` — mirror each row left-to-right. Dimensions and format unchanged.
struct HFlip;

impl Filter for HFlip {
    fn name(&self) -> &'static str {
        "hflip"
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        ensure_planar_yuv(&src, "hflip")?;
        let mut planes = Vec::with_capacity(src.planes.len());
        let mut strides = Vec::with_capacity(src.planes.len());
        for (i, plane) in src.planes.iter().enumerate() {
            let (pw, ph) = plane_dims(src.format, src.width, src.height, i)?;
            let (pw, ph, stride) = (pw as usize, ph as usize, src.strides[i]);
            let mut out = vec![0u8; pw * ph];
            for y in 0..ph {
                let row = &plane[y * stride..y * stride + pw];
                let dst = &mut out[y * pw..(y + 1) * pw];
                for x in 0..pw {
                    dst[x] = row[pw - 1 - x];
                }
            }
            planes.push(out);
            strides.push(pw);
        }
        Ok(VideoFrame {
            width: src.width,
            height: src.height,
            format: src.format,
            planes,
            strides,
            pts: src.pts,
        })
    }
}

/// `vflip` — mirror rows top-to-bottom. Dimensions and format unchanged.
struct VFlip;

impl Filter for VFlip {
    fn name(&self) -> &'static str {
        "vflip"
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        ensure_planar_yuv(&src, "vflip")?;
        let mut planes = Vec::with_capacity(src.planes.len());
        let mut strides = Vec::with_capacity(src.planes.len());
        for (i, plane) in src.planes.iter().enumerate() {
            let (pw, ph) = plane_dims(src.format, src.width, src.height, i)?;
            let (pw, ph, stride) = (pw as usize, ph as usize, src.strides[i]);
            let mut out = vec![0u8; pw * ph];
            for y in 0..ph {
                let src_row = &plane[(ph - 1 - y) * stride..(ph - 1 - y) * stride + pw];
                out[y * pw..(y + 1) * pw].copy_from_slice(src_row);
            }
            planes.push(out);
            strides.push(pw);
        }
        Ok(VideoFrame {
            width: src.width,
            height: src.height,
            format: src.format,
            planes,
            strides,
            pts: src.pts,
        })
    }
}

// ---------------------------------------------------------------------------
// transpose (90° rotations)
// ---------------------------------------------------------------------------

/// `transpose=DIR` — a 90° rotation (output dimensions are swapped). `DIR` is
/// `0`/`cclock_flip`, `1`/`clock`, `2`/`cclock`, `3`/`clock_flip` (default
/// `clock`). Requires symmetric chroma (4:2:0 or 4:4:4) so the layout survives.
struct Transpose {
    dir: u8,
}

impl Transpose {
    fn parse(args: &[&str]) -> Result<Transpose> {
        let dir = match args.first().map(|s| s.trim()) {
            None | Some("") => 1, // default: clockwise
            Some("cclock_flip") | Some("0") => 0,
            Some("clock") | Some("1") => 1,
            Some("cclock") | Some("2") => 2,
            Some("clock_flip") | Some("3") => 3,
            Some(other) => {
                return Err(Error::Option(format!(
                    "transpose: unknown direction `{other}`"
                )))
            }
        };
        Ok(Transpose { dir })
    }

    /// Map a destination coordinate back to its source `(x, y)` for plane size
    /// `(w, h)` (the *source* plane dimensions).
    fn source(&self, dx: u32, dy: u32, w: u32, h: u32) -> (u32, u32) {
        match self.dir {
            0 => (dy, dx),                 // transpose (cclock + vflip)
            1 => (dy, h - 1 - dx),         // 90° clockwise
            2 => (w - 1 - dy, dx),         // 90° counter-clockwise
            _ => (w - 1 - dy, h - 1 - dx), // clockwise + vflip
        }
    }
}

impl Filter for Transpose {
    fn name(&self) -> &'static str {
        "transpose"
    }

    fn output_dims(&self, in_w: u32, in_h: u32) -> (u32, u32) {
        (in_h, in_w)
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        ensure_planar_yuv(&src, "transpose")?;
        let (sx, sy) = subsampling(src.format)?;
        if sx != sy {
            return Err(Error::unsupported(
                "transpose: needs symmetric chroma (4:2:0 or 4:4:4)",
            ));
        }
        let mut planes = Vec::with_capacity(src.planes.len());
        let mut strides = Vec::with_capacity(src.planes.len());
        for (i, plane) in src.planes.iter().enumerate() {
            let (pw, ph) = plane_dims(src.format, src.width, src.height, i)?;
            let (dw, dh) = (ph, pw); // dimensions swap
            let stride = src.strides[i];
            let mut out = vec![0u8; (dw * dh) as usize];
            for dy in 0..dh {
                for dx in 0..dw {
                    let (mx, my) = self.source(dx, dy, pw, ph);
                    out[(dy * dw + dx) as usize] = plane[my as usize * stride + mx as usize];
                }
            }
            planes.push(out);
            strides.push(dw as usize);
        }
        Ok(VideoFrame {
            width: src.height,
            height: src.width,
            format: src.format,
            planes,
            strides,
            pts: src.pts,
        })
    }
}

// ---------------------------------------------------------------------------
// pad
// ---------------------------------------------------------------------------

/// `pad=W:H:X:Y` — place the input on a `W×H` black canvas at offset `(X, Y)`.
/// Offsets/size must align to the chroma grid. Fill is full-range black
/// (luma 0, chroma 128).
struct Pad {
    w: u32,
    h: u32,
    x: u32,
    y: u32,
}

impl Pad {
    fn parse(args: &[&str]) -> Result<Pad> {
        let [w, h, x, y] = args else {
            return Err(Error::Option("pad: expected pad=W:H:X:Y".into()));
        };
        let num = |s: &str| {
            s.trim()
                .parse::<u32>()
                .map_err(|_| Error::Option(format!("pad: bad value `{s}`")))
        };
        Ok(Pad {
            w: num(w)?,
            h: num(h)?,
            x: num(x)?,
            y: num(y)?,
        })
    }
}

impl Filter for Pad {
    fn name(&self) -> &'static str {
        "pad"
    }

    fn output_dims(&self, _in_w: u32, _in_h: u32) -> (u32, u32) {
        (self.w, self.h)
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        ensure_planar_yuv(&src, "pad")?;
        if self.x + src.width > self.w || self.y + src.height > self.h {
            return Err(Error::Option(format!(
                "pad: {}x{} input at +{}+{} doesn't fit a {}x{} canvas",
                src.width, src.height, self.x, self.y, self.w, self.h
            )));
        }
        let (sx, sy) = subsampling(src.format)?;
        if self.x % sx != 0 || self.w % sx != 0 || self.y % sy != 0 || self.h % sy != 0 {
            return Err(Error::Option(
                "pad: offset/size must align to the chroma grid".into(),
            ));
        }

        let mut planes = Vec::with_capacity(src.planes.len());
        let mut strides = Vec::with_capacity(src.planes.len());
        for (i, plane) in src.planes.iter().enumerate() {
            let (cw, ch) = plane_dims(src.format, self.w, self.h, i)?; // canvas
            let (sw, sh) = plane_dims(src.format, src.width, src.height, i)?; // source
            let (div_x, div_y) = if i == 0 { (1, 1) } else { (sx, sy) };
            let (px, py) = (self.x / div_x, self.y / div_y);
            let fill = if i == 0 { 0u8 } else { 128u8 }; // black: Y=0, chroma=128

            let (cw, ch) = (cw as usize, ch as usize);
            let mut out = vec![fill; cw * ch];
            for row in 0..sh as usize {
                let dst_start = (py as usize + row) * cw + px as usize;
                let src_start = row * src.strides[i];
                out[dst_start..dst_start + sw as usize]
                    .copy_from_slice(&plane[src_start..src_start + sw as usize]);
            }
            planes.push(out);
            strides.push(cw);
        }
        Ok(VideoFrame {
            width: self.w,
            height: self.h,
            format: src.format,
            planes,
            strides,
            pts: src.pts,
        })
    }
}

// ---------------------------------------------------------------------------
// format (pixel-format / colorspace conversion)
// ---------------------------------------------------------------------------

/// Colour matrix + quantisation range for YUV↔RGB. Coefficients derive from the
/// luma weights `(Kr, Kb)`: BT.601 = (0.299, 0.114), BT.709 = (0.2126, 0.0722).
/// Limited ("TV", Y 16–235 / C 16–240) vs full ("PC", 0–255) range scales Y and
/// chroma accordingly. H.264/AVC video is BT.709 for HD and BT.601 for SD, almost
/// always limited-range — so the BT.601/full default is correct only for full-range
/// sources (PNG/JPEG bridges); pick the right one with `format=rgb24:bt709:limited`.
#[derive(Clone, Copy)]
struct ColorSpec {
    kr: f32,
    kb: f32,
    limited: bool,
}
impl Default for ColorSpec {
    fn default() -> Self {
        ColorSpec {
            kr: 0.299,
            kb: 0.114,
            limited: false,
        } // BT.601 full-range (legacy)
    }
}
impl ColorSpec {
    #[inline]
    fn kg(&self) -> f32 {
        1.0 - self.kr - self.kb
    }
}

/// `format=PIXFMT[:MATRIX][:RANGE]` — convert between `rgb24` and `yuv420p`.
/// MATRIX ∈ {`bt601`, `bt709`}; RANGE ∈ {`full`/`pc`, `limited`/`tv`}. Defaults to
/// BT.601 full range for backward compatibility.
struct FormatConv {
    target: PixelFormat,
    spec: ColorSpec,
    /// Did the spec string pin the range explicitly? If not, the chain fills it
    /// in from the source stream — assuming full-range for everything was a
    /// silent 8 dB error on limited-range YUV sources.
    range_explicit: bool,
}

impl FormatConv {
    fn parse(args: &[&str]) -> Result<FormatConv> {
        let name = args.first().copied().unwrap_or("").trim();
        let target = match name {
            "yuv420p" => PixelFormat::Yuv420p,
            "rgb24" => PixelFormat::Rgb24,
            other => {
                return Err(Error::unsupported(format!(
                    "format: target `{other}` (only yuv420p and rgb24)"
                )))
            }
        };
        let mut spec = ColorSpec::default();
        let mut range_explicit = false;
        for opt in args.iter().skip(1).map(|s| s.trim()) {
            match opt {
                "" => {}
                "bt601" | "601" | "smpte170m" => {
                    spec.kr = 0.299;
                    spec.kb = 0.114;
                }
                "bt709" | "709" => {
                    spec.kr = 0.2126;
                    spec.kb = 0.0722;
                }
                "full" | "pc" | "jpeg" => {
                    spec.limited = false;
                    range_explicit = true;
                }
                "limited" | "tv" | "mpeg" => {
                    spec.limited = true;
                    range_explicit = true;
                }
                other => {
                    return Err(Error::unsupported(format!(
                        "format: option `{other}` (matrix bt601/bt709, range full/limited)"
                    )))
                }
            }
        }
        Ok(FormatConv {
            target,
            spec,
            range_explicit,
        })
    }
}

impl Filter for FormatConv {
    fn name(&self) -> &'static str {
        "format"
    }

    fn set_source_color_range(&mut self, range: ColorRange) {
        // `spec.limited` always describes the Y'CbCr side of the conversion,
        // whichever direction it runs, so one flag serves both.
        if !self.range_explicit {
            match range {
                ColorRange::Limited => self.spec.limited = true,
                ColorRange::Full => self.spec.limited = false,
                ColorRange::Unspecified => {}
            }
        }
    }

    /// Only meaningful when the target is Y'CbCr — RGB has no limited/full
    /// distinction, so converting *to* RGB leaves the question to whoever
    /// converts back.
    fn output_color_range(&self) -> Option<ColorRange> {
        match self.target {
            PixelFormat::Yuv420p | PixelFormat::Yuv422p | PixelFormat::Yuv444p => {
                Some(if self.spec.limited {
                    ColorRange::Limited
                } else {
                    ColorRange::Full
                })
            }
            _ => None,
        }
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        if src.format == self.target {
            return Ok(src);
        }
        match (src.format, self.target) {
            (PixelFormat::Rgb24, PixelFormat::Yuv420p) => rgb_to_yuv420(&src, 3, self.spec),
            (PixelFormat::Rgba, PixelFormat::Yuv420p) => rgb_to_yuv420(&src, 4, self.spec),
            (PixelFormat::Rgba, PixelFormat::Rgb24) => rgba_to_rgb(&src),
            (PixelFormat::Yuv420p, PixelFormat::Rgb24) => yuv420_to_rgb(&src, self.spec),
            (PixelFormat::Yuv422p, PixelFormat::Rgb24)
            | (PixelFormat::Yuv444p, PixelFormat::Rgb24) => yuv_planar_to_rgb(&src, self.spec),
            (PixelFormat::Yuv422p, PixelFormat::Yuv420p)
            | (PixelFormat::Yuv444p, PixelFormat::Yuv420p) => yuv_planar_to_420(&src),
            // High-bit-depth Y'CbCr (HEVC Main 10, VP9 profile 2, ...) is
            // narrowed to 8 bits first, then converted like any 8-bit frame.
            (from, to) if from.bit_depth() > 8 && to.bit_depth() == 8 => {
                let narrowed = narrow_to_8(&src)?;
                if narrowed.format == to {
                    Ok(narrowed)
                } else {
                    self.filter(narrowed)
                }
            }
            (from, to) => Err(Error::unsupported(format!(
                "format: {} → {} not supported",
                from.name(),
                to.name()
            ))),
        }
    }
}

fn clamp_u8(v: f32) -> u8 {
    v.round().clamp(0.0, 255.0) as u8
}

/// Packed RGB(A) → planar 4:2:0 (chroma averaged over each 2×2 block).
fn rgb_to_yuv420(src: &VideoFrame, bpp: usize, spec: ColorSpec) -> Result<VideoFrame> {
    let (w, h) = (src.width as usize, src.height as usize);
    let stride = src.strides[0];
    let rgb = &src.planes[0];
    let px = |i: usize, j: usize| {
        let p = j * stride + i * bpp;
        (rgb[p] as f32, rgb[p + 1] as f32, rgb[p + 2] as f32)
    };

    // Forward coeffs from (Kr, Kb): Y = yoff + yscale·(Kr·R+Kg·G+Kb·B),
    // U = 128 + cscale·(ur·R+ug·G+0.5·B), V = 128 + cscale·(0.5·R+vg·G+vb·B).
    let (kr, kb, kg) = (spec.kr, spec.kb, spec.kg());
    let (yoff, yscale, cscale) = if spec.limited {
        (16.0, 219.0 / 255.0, 224.0 / 255.0)
    } else {
        (0.0, 1.0, 1.0)
    };
    let (ur, ug) = (-0.5 * kr / (1.0 - kb), -0.5 * kg / (1.0 - kb));
    let (vg, vb) = (-0.5 * kg / (1.0 - kr), -0.5 * kb / (1.0 - kr));

    let mut y = vec![0u8; w * h];
    for j in 0..h {
        for i in 0..w {
            let (r, g, b) = px(i, j);
            y[j * w + i] = clamp_u8(yoff + yscale * (kr * r + kg * g + kb * b));
        }
    }

    let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
    let (mut u, mut v) = (vec![0u8; cw * ch], vec![0u8; cw * ch]);
    for cj in 0..ch {
        for ci in 0..cw {
            // Average the (up to) 2×2 RGB block, then convert once.
            let (mut sr, mut sg, mut sb, mut n) = (0.0, 0.0, 0.0, 0.0);
            for dy in 0..2 {
                for dx in 0..2 {
                    let (i, j) = (ci * 2 + dx, cj * 2 + dy);
                    if i < w && j < h {
                        let (r, g, b) = px(i, j);
                        sr += r;
                        sg += g;
                        sb += b;
                        n += 1.0;
                    }
                }
            }
            let (r, g, b) = (sr / n, sg / n, sb / n);
            u[cj * cw + ci] = clamp_u8(128.0 + cscale * (ur * r + ug * g + 0.5 * b));
            v[cj * cw + ci] = clamp_u8(128.0 + cscale * (0.5 * r + vg * g + vb * b));
        }
    }

    Ok(VideoFrame {
        width: src.width,
        height: src.height,
        format: PixelFormat::Yuv420p,
        planes: vec![y, u, v],
        strides: vec![w, cw, cw],
        pts: src.pts,
    })
}

/// Planar 4:2:0 → packed RGB (chroma upsampled nearest-neighbour).
/// Chroma subsampling `(horizontal, vertical)` of a planar 8-bit Y'CbCr format.
fn planar_subsampling(format: PixelFormat) -> Option<(usize, usize)> {
    match format {
        PixelFormat::Yuv444p | PixelFormat::Yuv444p10 | PixelFormat::Yuv444p12 => Some((1, 1)),
        PixelFormat::Yuv422p | PixelFormat::Yuv422p10 | PixelFormat::Yuv422p12 => Some((2, 1)),
        PixelFormat::Yuv420p | PixelFormat::Yuv420p10 | PixelFormat::Yuv420p12 => Some((2, 2)),
        _ => None,
    }
}

/// Planar Y'CbCr (4:2:0 / 4:2:2 / 4:4:4) → packed RGB24.
///
/// Chroma is upsampled by replication. That is what the nearest-neighbour
/// reading of a subsampled plane means, and it keeps this exactly invertible
/// against the encoder's point-sampling.
fn yuv_planar_to_rgb(src: &VideoFrame, spec: ColorSpec) -> Result<VideoFrame> {
    let (sh, sv) = planar_subsampling(src.format).ok_or_else(|| {
        Error::unsupported(format!(
            "format: {} is not planar Y'CbCr",
            src.format.name()
        ))
    })?;
    let (w, h) = (src.width as usize, src.height as usize);
    let (ys, us, vs) = (src.strides[0], src.strides[1], src.strides[2]);
    let (yp, up, vp) = (&src.planes[0], &src.planes[1], &src.planes[2]);

    let kg = spec.kg();
    let (yoff, yscale, cscale) = if spec.limited {
        (16.0, 255.0 / 219.0, 255.0 / 224.0)
    } else {
        (0.0, 1.0, 1.0)
    };
    let kr_c = 2.0 * (1.0 - spec.kr) * cscale;
    let kb_c = 2.0 * (1.0 - spec.kb) * cscale;
    let kgv = -2.0 * spec.kr * (1.0 - spec.kr) / kg * cscale;
    let kgu = -2.0 * spec.kb * (1.0 - spec.kb) / kg * cscale;

    let mut out = vec![0u8; w * h * 3];
    for j in 0..h {
        for i in 0..w {
            let ya = yscale * (yp[j * ys + i] as f32 - yoff);
            let cu = up[(j / sv) * us + i / sh] as f32 - 128.0;
            let cv = vp[(j / sv) * vs + i / sh] as f32 - 128.0;
            let o = (j * w + i) * 3;
            out[o] = clamp_u8(ya + kr_c * cv);
            out[o + 1] = clamp_u8(ya + kgu * cu + kgv * cv);
            out[o + 2] = clamp_u8(ya + kb_c * cu);
        }
    }
    Ok(VideoFrame {
        width: src.width,
        height: src.height,
        format: PixelFormat::Rgb24,
        planes: vec![out],
        strides: vec![w * 3],
        pts: src.pts,
    })
}

/// Narrows a planar Y'CbCr frame with 10- or 12-bit samples (little-endian
/// `u16`) to its 8-bit sibling, rounding rather than truncating.
fn narrow_to_8(src: &VideoFrame) -> Result<VideoFrame> {
    let (target, shift) = match src.format {
        PixelFormat::Yuv420p10 => (PixelFormat::Yuv420p, 2),
        PixelFormat::Yuv422p10 => (PixelFormat::Yuv422p, 2),
        PixelFormat::Yuv444p10 => (PixelFormat::Yuv444p, 2),
        PixelFormat::Yuv420p12 => (PixelFormat::Yuv420p, 4),
        PixelFormat::Yuv422p12 => (PixelFormat::Yuv422p, 4),
        PixelFormat::Yuv444p12 => (PixelFormat::Yuv444p, 4),
        other => {
            return Err(Error::unsupported(format!(
                "format: {} cannot be narrowed to 8 bits",
                other.name()
            )))
        }
    };
    let (sh, sv) = planar_subsampling(src.format).unwrap_or((1, 1));
    let (w, h) = (src.width as usize, src.height as usize);
    let round = 1u32 << (shift - 1);
    let mut planes = Vec::with_capacity(3);
    let mut strides = Vec::with_capacity(3);
    for (i, plane) in src.planes.iter().enumerate().take(3) {
        let (pw, ph) = if i == 0 { (w, h) } else { (w.div_ceil(sh), h.div_ceil(sv)) };
        let stride = src.strides.get(i).copied().unwrap_or(pw * 2);
        let mut out = Vec::with_capacity(pw * ph);
        for y in 0..ph {
            let row = plane.get(y * stride..y * stride + pw * 2).ok_or_else(|| {
                Error::invalid("narrow_to_8: plane shorter than its declared geometry")
            })?;
            out.extend(row.chunks_exact(2).map(|c| {
                let v = u16::from_le_bytes([c[0], c[1]]) as u32;
                ((v + round) >> shift).min(255) as u8
            }));
        }
        strides.push(pw);
        planes.push(out);
    }
    Ok(VideoFrame {
        width: src.width,
        height: src.height,
        format: target,
        planes,
        strides,
        pts: src.pts,
    })
}


/// Planar Y'CbCr → planar 4:2:0, **averaging** the chroma it drops.
///
/// Averaging rather than point-sampling matters: dropping 3 of every 4 chroma
/// samples without a low-pass aliases, and the artefacts land on exactly the
/// saturated edges people look at.
fn yuv_planar_to_420(src: &VideoFrame) -> Result<VideoFrame> {
    if src.format.bit_depth() > 8 {
        return Err(Error::unsupported(format!(
            "format: {} must be narrowed to 8 bits first",
            src.format.name()
        )));
    }
    let (sh, sv) = planar_subsampling(src.format).ok_or_else(|| {
        Error::unsupported(format!(
            "format: {} is not planar Y'CbCr",
            src.format.name()
        ))
    })?;
    if (sh, sv) == (2, 2) {
        return Ok(src.clone());
    }
    let (w, h) = (src.width as usize, src.height as usize);
    let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
    // Source chroma plane dimensions.
    let (scw, sch) = (w.div_ceil(sh), h.div_ceil(sv));

    // Luma is untouched; repack it to a tight stride.
    let ys = src.strides[0];
    let mut luma = Vec::with_capacity(w * h);
    for j in 0..h {
        luma.extend_from_slice(&src.planes[0][j * ys..j * ys + w]);
    }

    let mut out_planes = vec![luma];
    for plane_idx in 1..3 {
        let stride = src.strides[plane_idx];
        let plane = &src.planes[plane_idx];
        let mut dst = vec![0u8; cw * ch];
        // How many source chroma samples collapse into one output sample.
        let (fx, fy) = (2 / sh, 2 / sv);
        for j in 0..ch {
            for i in 0..cw {
                let mut sum = 0u32;
                let mut n = 0u32;
                for dy in 0..fy.max(1) {
                    let sy = (j * fy + dy).min(sch - 1);
                    for dx in 0..fx.max(1) {
                        let sx = (i * fx + dx).min(scw - 1);
                        sum += plane[sy * stride + sx] as u32;
                        n += 1;
                    }
                }
                dst[j * cw + i] = ((sum + n / 2) / n) as u8;
            }
        }
        out_planes.push(dst);
    }
    Ok(VideoFrame {
        width: src.width,
        height: src.height,
        format: PixelFormat::Yuv420p,
        planes: out_planes,
        strides: vec![w, cw, cw],
        pts: src.pts,
    })
}

fn yuv420_to_rgb(src: &VideoFrame, spec: ColorSpec) -> Result<VideoFrame> {
    let (w, h) = (src.width as usize, src.height as usize);
    let (ys, us, vs) = (src.strides[0], src.strides[1], src.strides[2]);
    let (yp, up, vp) = (&src.planes[0], &src.planes[1], &src.planes[2]);

    // Derive from (Kr, Kb): R = ya + kr_c·cv, G = ya + kgu·cu + kgv·cv,
    // B = ya + kb_c·cu, where ya = yscale·(Y − yoff), cu = Cu−128, cv = Cv−128.
    let kg = spec.kg();
    let (yoff, yscale, cscale) = if spec.limited {
        (16.0, 255.0 / 219.0, 255.0 / 224.0)
    } else {
        (0.0, 1.0, 1.0)
    };
    let kr_c = 2.0 * (1.0 - spec.kr) * cscale;
    let kb_c = 2.0 * (1.0 - spec.kb) * cscale;
    let kgv = -2.0 * spec.kr * (1.0 - spec.kr) / kg * cscale;
    let kgu = -2.0 * spec.kb * (1.0 - spec.kb) / kg * cscale;

    let mut out = vec![0u8; w * h * 3];
    for j in 0..h {
        for i in 0..w {
            let ya = yscale * (yp[j * ys + i] as f32 - yoff);
            let cu = up[(j / 2) * us + i / 2] as f32 - 128.0;
            let cv = vp[(j / 2) * vs + i / 2] as f32 - 128.0;
            let o = (j * w + i) * 3;
            out[o] = clamp_u8(ya + kr_c * cv);
            out[o + 1] = clamp_u8(ya + kgu * cu + kgv * cv);
            out[o + 2] = clamp_u8(ya + kb_c * cu);
        }
    }
    Ok(VideoFrame {
        width: src.width,
        height: src.height,
        format: PixelFormat::Rgb24,
        planes: vec![out],
        strides: vec![w * 3],
        pts: src.pts,
    })
}

/// Drop the alpha channel: packed RGBA → packed RGB.
fn rgba_to_rgb(src: &VideoFrame) -> Result<VideoFrame> {
    let (w, h) = (src.width as usize, src.height as usize);
    let stride = src.strides[0];
    let rgba = &src.planes[0];
    let mut out = vec![0u8; w * h * 3];
    for j in 0..h {
        for i in 0..w {
            let s = j * stride + i * 4;
            let d = (j * w + i) * 3;
            out[d..d + 3].copy_from_slice(&rgba[s..s + 3]);
        }
    }
    Ok(VideoFrame {
        width: src.width,
        height: src.height,
        format: PixelFormat::Rgb24,
        planes: vec![out],
        strides: vec![w * 3],
        pts: src.pts,
    })
}

// ---------------------------------------------------------------------------
// negate / grayscale
// ---------------------------------------------------------------------------

/// Repack a plane into a tight buffer, applying `f` to every sample.
fn map_plane(plane: &[u8], stride: usize, pw: usize, ph: usize, f: impl Fn(u8) -> u8) -> Vec<u8> {
    let mut out = vec![0u8; pw * ph];
    for y in 0..ph {
        let row = &plane[y * stride..y * stride + pw];
        let dst = &mut out[y * pw..(y + 1) * pw];
        for x in 0..pw {
            dst[x] = f(row[x]);
        }
    }
    out
}

/// `negate` — invert every sample (`255 - v`), luma and chroma.
struct Negate;

impl Filter for Negate {
    fn name(&self) -> &'static str {
        "negate"
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        ensure_planar_yuv(&src, "negate")?;
        let mut planes = Vec::with_capacity(src.planes.len());
        let mut strides = Vec::with_capacity(src.planes.len());
        for (i, plane) in src.planes.iter().enumerate() {
            let (pw, ph) = plane_dims(src.format, src.width, src.height, i)?;
            planes.push(map_plane(
                plane,
                src.strides[i],
                pw as usize,
                ph as usize,
                |v| 255 - v,
            ));
            strides.push(pw as usize);
        }
        Ok(VideoFrame {
            planes,
            strides,
            ..src
        })
    }
}

/// `grayscale` — keep luma, neutralize chroma (set both chroma planes to 128).
/// `setrange=full|limited` — rescale planar Y'CbCr between limited ("TV",
/// Y 16–235 / C 16–240) and full ("PC", 0–255) range.
///
/// This is a value rescale only: no colour-space change, no chroma resampling,
/// planes keep their dimensions. It exists because JPEG is defined on full-range
/// samples while most video is limited-range, so handing a limited-range plane
/// straight to a JPEG encoder encodes the wrong signal. The transcode pipeline
/// inserts this automatically when the target codec needs full range; the CLI
/// name is exposed for when you need to override that.
///
/// RGB frames pass through untouched — the distinction is a Y'CbCr one.
struct SetRange {
    to_full: bool,
}

impl SetRange {
    fn parse(args: &[&str]) -> Result<SetRange> {
        match args.first().copied().unwrap_or("").trim() {
            "full" | "pc" | "jpeg" => Ok(SetRange { to_full: true }),
            "limited" | "tv" | "mpeg" => Ok(SetRange { to_full: false }),
            other => Err(Error::unsupported(format!(
                "setrange: `{other}` (want full/pc/jpeg or limited/tv/mpeg)"
            ))),
        }
    }

    /// 256-entry map for one component. Luma and chroma differ: limited luma is
    /// 16–235, limited chroma 16–240.
    fn lut(&self, chroma: bool) -> [u8; 256] {
        let (lo, span) = if chroma { (16.0, 224.0) } else { (16.0, 219.0) };
        let mut lut = [0u8; 256];
        for (v, out) in lut.iter_mut().enumerate() {
            let v = v as f32;
            let mapped = if self.to_full {
                (v - lo) * 255.0 / span
            } else {
                v * span / 255.0 + lo
            };
            *out = mapped.round().clamp(0.0, 255.0) as u8;
        }
        lut
    }
}

impl Filter for SetRange {
    fn name(&self) -> &'static str {
        "setrange"
    }

    fn output_color_range(&self) -> Option<ColorRange> {
        Some(if self.to_full {
            ColorRange::Full
        } else {
            ColorRange::Limited
        })
    }

    fn filter(&mut self, mut frame: VideoFrame) -> Result<VideoFrame> {
        // Only planar Y'CbCr has a range to convert.
        if ensure_planar_yuv(&frame, "setrange").is_err() {
            return Ok(frame);
        }
        let luma = self.lut(false);
        let chroma = self.lut(true);
        for (i, plane) in frame.planes.iter_mut().enumerate() {
            let lut = if i == 0 { &luma } else { &chroma };
            for b in plane.iter_mut() {
                *b = lut[*b as usize];
            }
        }
        Ok(frame)
    }
}

struct Grayscale;

impl Filter for Grayscale {
    fn name(&self) -> &'static str {
        "grayscale"
    }

    fn filter(&mut self, src: VideoFrame) -> Result<VideoFrame> {
        ensure_planar_yuv(&src, "grayscale")?;
        let mut planes = Vec::with_capacity(src.planes.len());
        let mut strides = Vec::with_capacity(src.planes.len());
        for (i, plane) in src.planes.iter().enumerate() {
            let (pw, ph) = plane_dims(src.format, src.width, src.height, i)?;
            let (pw, ph) = (pw as usize, ph as usize);
            if i == 0 {
                planes.push(map_plane(plane, src.strides[i], pw, ph, |v| v));
            } else {
                planes.push(vec![128u8; pw * ph]);
            }
            strides.push(pw);
        }
        Ok(VideoFrame {
            planes,
            strides,
            ..src
        })
    }
}

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

    /// A W×H 4:2:0 frame with a per-pixel luma function and flat chroma.
    fn frame(w: u32, h: u32, luma: impl Fn(u32, u32) -> u8) -> VideoFrame {
        let (wi, hi) = (w as usize, h as usize);
        let mut y = vec![0u8; wi * hi];
        for row in 0..h {
            for col in 0..w {
                y[row as usize * wi + col as usize] = luma(col, row);
            }
        }
        let chroma = vec![128u8; (wi / 2) * (hi / 2)];
        VideoFrame {
            width: w,
            height: h,
            format: PixelFormat::Yuv420p,
            planes: vec![y, chroma.clone(), chroma],
            strides: vec![wi, wi / 2, wi / 2],
            pts: Some(0),
        }
    }

    #[test]
    fn scale_changes_dimensions_and_keeps_planes_consistent() {
        let mut chain = FilterChain::parse("scale=32:16").unwrap();
        assert_eq!(chain.output_dims(64, 64), (32, 16));
        let out = chain.apply(frame(64, 64, |x, _| x as u8)).unwrap();
        assert_eq!((out.width, out.height), (32, 16));
        // Y plane is dw*dh; chroma is half each way.
        assert_eq!(out.planes[0].len(), 32 * 16);
        assert_eq!(out.planes[1].len(), 16 * 8);
        assert_eq!(out.strides, vec![32, 16, 16]);
    }

    #[test]
    fn scale_preserves_a_flat_field_exactly() {
        // A constant plane must resample to the same constant (no ringing).
        let mut chain = FilterChain::parse("scale=20:30").unwrap();
        let out = chain.apply(frame(64, 48, |_, _| 200)).unwrap();
        assert!(out.planes[0].iter().all(|&v| v == 200));
    }

    #[test]
    fn crop_extracts_the_right_rectangle() {
        // Luma encodes the column index, so a crop at x=8 should start at 8.
        let mut chain = FilterChain::parse("crop=16:16:8:4").unwrap();
        assert_eq!(chain.output_dims(64, 64), (16, 16));
        let out = chain.apply(frame(64, 64, |x, _| x as u8)).unwrap();
        assert_eq!((out.width, out.height), (16, 16));
        assert_eq!(out.planes[0][0], 8); // top-left came from source column 8
        assert_eq!(out.planes[0][15], 23); // 8 + 15
    }

    #[test]
    fn crop_rejects_out_of_bounds_and_misalignment() {
        let mut oob = FilterChain::parse("crop=64:64:8:8").unwrap();
        assert!(oob.apply(frame(64, 64, |_, _| 0)).is_err());
        let mut odd = FilterChain::parse("crop=15:15:1:1").unwrap();
        assert!(odd.apply(frame(64, 64, |_, _| 0)).is_err());
    }

    #[test]
    fn rejects_unknown_filter() {
        assert!(FilterChain::parse("frobnicate=1").is_err());
    }

    #[test]
    fn negate_inverts_samples() {
        let mut chain = FilterChain::parse("negate").unwrap();
        let out = chain.apply(frame(4, 4, |x, _| x as u8)).unwrap();
        assert_eq!(out.planes[0][0], 255); // 255 - 0
        assert_eq!(out.planes[0][3], 252); // 255 - 3
        assert_eq!(out.planes[1][0], 127); // chroma 128 → 127
    }

    #[test]
    fn grayscale_neutralizes_chroma() {
        // Frame with saturated chroma; grayscale must flatten it to 128.
        let mut f = frame(8, 8, |x, _| x as u8);
        for c in [1, 2] {
            f.planes[c].iter_mut().for_each(|p| *p = 200);
        }
        let luma_before = f.planes[0].clone();
        let mut chain = FilterChain::parse("grayscale").unwrap();
        let out = chain.apply(f).unwrap();
        assert_eq!(out.planes[0], luma_before); // luma untouched
        assert!(out.planes[1].iter().all(|&v| v == 128));
        assert!(out.planes[2].iter().all(|&v| v == 128));
    }

    #[test]
    fn scale_minus_one_preserves_aspect() {
        let chain = FilterChain::parse("scale=-1:32").unwrap();
        // 64×48 → width = 64*32/48 = 42 (rounded even), height = 32.
        assert_eq!(chain.output_dims(64, 48), (42, 32));
        assert!(FilterChain::parse("scale=-1:-1").is_err());
    }

    #[test]
    fn hflip_mirrors_columns() {
        let mut chain = FilterChain::parse("hflip").unwrap();
        let out = chain.apply(frame(8, 4, |x, _| x as u8)).unwrap();
        assert_eq!((out.width, out.height), (8, 4));
        assert_eq!(out.planes[0][0], 7); // first column came from the last
        assert_eq!(out.planes[0][7], 0);
    }

    #[test]
    fn vflip_mirrors_rows() {
        let mut chain = FilterChain::parse("vflip").unwrap();
        let out = chain.apply(frame(4, 8, |_, y| y as u8)).unwrap();
        assert_eq!(out.planes[0][0], 7); // top row came from the bottom
        assert_eq!(out.planes[0][7 * 4], 0);
    }

    #[test]
    fn transpose_clock_then_cclock_is_identity() {
        // A unique value per pixel; clockwise then counter-clockwise must
        // restore the original exactly (no interpolation involved).
        let original = frame(8, 4, |x, y| (x * 4 + y) as u8);
        let expected = original.planes[0].clone();
        let mut chain = FilterChain::parse("transpose=clock,transpose=cclock").unwrap();
        let out = chain.apply(original).unwrap();
        assert_eq!((out.width, out.height), (8, 4));
        assert_eq!(out.planes[0], expected);
    }

    #[test]
    fn transpose_swaps_dimensions() {
        let chain = FilterChain::parse("transpose=1").unwrap();
        assert_eq!(chain.output_dims(96, 64), (64, 96));
    }

    #[test]
    fn format_rgb_yuv_roundtrip_is_close() {
        // A smooth RGB gradient survives RGB→YUV420→RGB within tolerance.
        let (w, h) = (32usize, 32usize);
        let mut rgb = vec![0u8; w * h * 3];
        for j in 0..h {
            for i in 0..w {
                let o = (j * w + i) * 3;
                rgb[o] = (i * 255 / (w - 1)) as u8; // R ramps across
                rgb[o + 1] = (j * 255 / (h - 1)) as u8; // G ramps down
                rgb[o + 2] = 96;
            }
        }
        let src = VideoFrame {
            width: w as u32,
            height: h as u32,
            format: PixelFormat::Rgb24,
            planes: vec![rgb.clone()],
            strides: vec![w * 3],
            pts: Some(0),
        };

        let mut to_yuv = FilterChain::parse("format=yuv420p").unwrap();
        let yuv = to_yuv.apply(src).unwrap();
        assert_eq!(yuv.format, PixelFormat::Yuv420p);
        assert_eq!(yuv.planes.len(), 3);

        let mut to_rgb = FilterChain::parse("format=rgb24").unwrap();
        let back = to_rgb.apply(yuv).unwrap();
        assert_eq!(back.format, PixelFormat::Rgb24);

        let total: u64 = rgb
            .iter()
            .zip(&back.planes[0])
            .map(|(a, b)| (*a as i16 - *b as i16).unsigned_abs() as u64)
            .sum();
        let mean = total as f64 / (w * h * 3) as f64;
        assert!(mean < 8.0, "rgb↔yuv round-trip drifted too far: {mean:.2}");
    }

    #[test]
    fn colorspace_matrices_and_range() {
        // A 2×2 solid RGB frame (chroma-subsample averages to the same value → exact).
        let solid = |r: u8, g: u8, b: u8| VideoFrame {
            width: 2,
            height: 2,
            format: PixelFormat::Rgb24,
            planes: vec![[r, g, b].repeat(4)],
            strides: vec![6],
            pts: Some(0),
        };
        let to_yuv = |opts: &str, f: VideoFrame| {
            let mut c = FilterChain::parse(&format!("format=yuv420p{opts}")).unwrap();
            let y = c.apply(f).unwrap();
            (y.planes[0][0], y.planes[1][0], y.planes[2][0])
        };
        // Range anchors (matrix-independent): limited white→235/black→16; full→255/0.
        assert_eq!(to_yuv(":limited", solid(255, 255, 255)).0, 235);
        assert_eq!(to_yuv(":limited", solid(0, 0, 0)).0, 16);
        assert_eq!(to_yuv(":full", solid(255, 255, 255)).0, 255);
        assert_eq!(to_yuv(":full", solid(0, 0, 0)).0, 0);
        // Matrix matters: pure-red luma is higher in BT.601 (0.299) than BT.709 (0.2126).
        let y601 = to_yuv(":bt601:full", solid(255, 0, 0)).0;
        let y709 = to_yuv(":bt709:full", solid(255, 0, 0)).0;
        assert!(y601 > y709, "601 red-luma {y601} should exceed 709 {y709}");
        // Greyscale is chroma-neutral (U=V=128) in every mode (luma scales with range).
        for m in [":full", ":limited", ":bt709:limited"] {
            let (_, u, v) = to_yuv(m, solid(128, 128, 128));
            assert_eq!((u, v), (128, 128), "grey chroma ({m})");
        }
        // Each colorspace round-trips tightly (the decode-display path).
        for m in [":bt709:limited", ":bt601:limited", ":bt709:full"] {
            let mut to_y = FilterChain::parse(&format!("format=yuv420p{m}")).unwrap();
            let mut to_r = FilterChain::parse(&format!("format=rgb24{m}")).unwrap();
            let src = solid(200, 100, 50);
            let back = to_r.apply(to_y.apply(src.clone()).unwrap()).unwrap();
            let drift: u32 = src.planes[0]
                .iter()
                .zip(&back.planes[0])
                .map(|(a, b)| (*a as i16 - *b as i16).unsigned_abs() as u32)
                .sum::<u32>()
                / 12;
            assert!(drift < 6, "round-trip drift for {m}: {drift}");
        }
    }

    #[test]
    fn pad_centers_input_on_black_canvas() {
        let mut chain = FilterChain::parse("pad=16:16:4:4").unwrap();
        assert_eq!(chain.output_dims(8, 8), (16, 16));
        let out = chain.apply(frame(8, 8, |_, _| 200)).unwrap();
        assert_eq!((out.width, out.height), (16, 16));
        assert_eq!(out.planes[0][0], 0); // border luma is black
        assert_eq!(out.planes[0][4 * 16 + 4], 200); // input top-left at (4,4)
        assert_eq!(out.planes[1][0], 128); // border chroma is neutral
        assert!(chain.apply(frame(64, 64, |_, _| 0)).is_err()); // doesn't fit
    }

    #[test]
    fn filter_complex_parses_overlay_offset() {
        let fc = FilterComplex::parse("[0:v][1:v]overlay=16:8[out]").unwrap();
        assert_eq!(fc.overlay, Some((16, 8)));
        // Bare overlay (no offset) defaults to the top-left corner.
        assert_eq!(
            FilterComplex::parse("overlay").unwrap().overlay,
            Some((0, 0))
        );
        assert!(FilterComplex::parse("[0][1]hstack").is_err());
    }

    #[test]
    fn overlay_composites_at_offset() {
        // Base luma = 10 everywhere; overlay luma = 200 everywhere. After an
        // overlay at (8, 4), the 8×8 patch there must read 200, elsewhere 10.
        let base = frame(32, 32, |_, _| 10);
        let over = frame(8, 8, |_, _| 200);
        let out = overlay(base, &over, 8, 4).unwrap();
        assert_eq!((out.width, out.height), (32, 32));
        assert_eq!(out.planes[0][4 * 32 + 8], 200); // top-left of the patch
        assert_eq!(out.planes[0][11 * 32 + 15], 200); // bottom-right of the patch
        assert_eq!(out.planes[0][0], 10); // outside, untouched
        assert_eq!(out.planes[0][12 * 32 + 8], 10); // one row below the patch
    }

    #[test]
    fn overlay_clips_to_base_bounds() {
        // An overlay placed near the corner spills past the edge; the copy must
        // clip rather than panic, and the in-bounds corner still lands.
        let base = frame(16, 16, |_, _| 0);
        let over = frame(8, 8, |_, _| 99);
        let out = overlay(base, &over, 12, 12).unwrap();
        assert_eq!(out.planes[0][12 * 16 + 12], 99); // the 4×4 visible corner
        assert_eq!(out.planes[0][15 * 16 + 15], 99);
    }
}

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

    fn planar(y: Vec<u8>, u: Vec<u8>, v: Vec<u8>) -> VideoFrame {
        VideoFrame {
            width: 2,
            height: 2,
            format: PixelFormat::Yuv420p,
            planes: vec![y, u, v],
            strides: vec![2, 1, 1],
            pts: None,
        }
    }

    #[test]
    fn limited_to_full_hits_the_anchors() {
        let mut f = SetRange { to_full: true };
        // Limited black/white (16/235) must land on full black/white (0/255).
        let out = f
            .filter(planar(vec![16, 235, 16, 235], vec![16], vec![240]))
            .unwrap();
        assert_eq!(out.planes[0], vec![0, 255, 0, 255]);
        // Limited chroma spans 16..240.
        assert_eq!(out.planes[1], vec![0]);
        assert_eq!(out.planes[2], vec![255]);
    }

    #[test]
    fn full_to_limited_hits_the_anchors() {
        let mut f = SetRange { to_full: false };
        let out = f
            .filter(planar(vec![0, 255, 0, 255], vec![0], vec![255]))
            .unwrap();
        assert_eq!(out.planes[0], vec![16, 235, 16, 235]);
        assert_eq!(out.planes[1], vec![16]);
        assert_eq!(out.planes[2], vec![240]);
    }

    #[test]
    fn out_of_range_values_clamp_not_wrap() {
        // Below limited black / above limited white must saturate, not wrap.
        let mut f = SetRange { to_full: true };
        let out = f
            .filter(planar(vec![0, 255, 8, 240], vec![0], vec![255]))
            .unwrap();
        assert_eq!(out.planes[0][0], 0);
        assert_eq!(out.planes[0][1], 255);
    }

    #[test]
    fn rgb_frames_pass_through_untouched() {
        let mut f = SetRange { to_full: true };
        let rgb = VideoFrame {
            width: 1,
            height: 1,
            format: PixelFormat::Rgb24,
            planes: vec![vec![10, 20, 30]],
            strides: vec![3],
            pts: None,
        };
        let out = f.filter(rgb).unwrap();
        assert_eq!(out.planes[0], vec![10, 20, 30]);
    }

    #[test]
    fn reports_the_range_it_produces() {
        assert_eq!(
            SetRange { to_full: true }.output_color_range(),
            Some(ColorRange::Full)
        );
        assert_eq!(
            SetRange { to_full: false }.output_color_range(),
            Some(ColorRange::Limited)
        );
    }

    #[test]
    fn format_conv_takes_the_source_range_unless_pinned() {
        // Not pinned: the chain's declared source range wins.
        let mut chain = FilterChain::parse("format=rgb24").unwrap();
        chain.set_source_color_range(ColorRange::Limited);
        // Pinned in the spec: the declaration must NOT override it.
        let mut pinned = FilterChain::parse("format=rgb24:full").unwrap();
        pinned.set_source_color_range(ColorRange::Limited);

        // Limited black (16,128,128) is true black only under the limited reading.
        let frame = || VideoFrame {
            width: 2,
            height: 2,
            format: PixelFormat::Yuv420p,
            planes: vec![vec![16; 4], vec![128], vec![128]],
            strides: vec![2, 1, 1],
            pts: None,
        };
        let a = chain.apply(frame()).unwrap();
        let b = pinned.apply(frame()).unwrap();
        assert_eq!(a.planes[0][0], 0, "limited reading maps 16 -> 0");
        assert!(b.planes[0][0] > 0, "full reading leaves 16 above black");
    }
}