remade-ffmpeg 0.9.4

Remade FFmpeg (Rust): the engine facade — registers built-in codecs/formats and exposes the high-level transcode & probe API.
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
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
//! Transcoding — the engine side of `ffmpeg`.
//!
//! The pipeline is the classic FFmpeg shape:
//!
//! ```text
//!   demuxer ─▶ decoder ─▶ [filters] ─▶ encoder ─▶ muxer
//!   (input)    (raw frames pass through the middle)      (output)
//! ```
//!
//! [`TranscodeSpec`] is the declarative description of a job — inputs, an
//! output, and the codecs to use. [`run`] resolves that spec against an
//! [`Engine`] (finding the demuxer, decoders, encoders, and muxer) and then
//! drives the loop to completion.
//!
//! Each input stream is either **transcoded** (decode → re-encode) when an
//! output codec is requested for its media type, or **stream-copied**
//! (remuxed packet-for-packet) when none is — the same `-c:v copy` distinction
//! FFmpeg draws. Video runs through the `-vf` filter graph (scale/crop); audio
//! is automatically resampled to a rate the target encoder accepts (FFmpeg's
//! implicit `aresample`).

use std::path::PathBuf;

use rff_codec::{CodecParams, Decoder, Encoder};
use rff_core::{
    AudioFrame, CodecId, ColorRange, Dictionary, Error, Frame, MediaType, Packet, PixelFormat,
    Result, SampleFormat, VideoFrame,
};
use rff_filter::{FilterChain, FilterComplex};

use rff_format::{Chapter, Muxer, Stream, TrackReference};
use rff_resample::Resampler;

use crate::Engine;

/// `RFF_PHASES=1`: wall time per phase of the transcode loop, on stderr at the
/// end of [`run`] -- the outside-the-codec view (demux, decode, the conform
/// chain, encode, mux) that a codec's own stage profiler cannot see. A gap
/// between a codec's core throughput and the CLI's is plumbing, and this is
/// what locates it (codec-memory-copies step 0). Off by default: one cached
/// flag test per call, and `Instant` is never touched unless it is set.
mod phases {
    use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
    use std::sync::OnceLock;

    pub static OPEN: AtomicU64 = AtomicU64::new(0);
    pub static DEMUX: AtomicU64 = AtomicU64::new(0);
    pub static DECODE: AtomicU64 = AtomicU64::new(0);
    pub static CONFORM: AtomicU64 = AtomicU64::new(0);
    pub static ENCODE: AtomicU64 = AtomicU64::new(0);
    pub static MUX: AtomicU64 = AtomicU64::new(0);

    pub fn on() -> bool {
        static ON: OnceLock<bool> = OnceLock::new();
        *ON.get_or_init(|| std::env::var_os("RFF_PHASES").is_some())
    }

    /// Run `f`, charging its wall time to `acc` when phases are on.
    pub fn time<T>(acc: &AtomicU64, f: impl FnOnce() -> T) -> T {
        if !on() {
            return f();
        }
        let t = std::time::Instant::now();
        let r = f();
        acc.fetch_add(t.elapsed().as_nanos() as u64, Relaxed);
        r
    }

    pub fn report(total: std::time::Duration) {
        let total_ns = total.as_nanos().max(1) as f64;
        eprintln!("--- rff phases (total {:.1} ms) ---", total_ns / 1e6);
        let mut sum = 0u64;
        for (name, acc) in [
            ("open", &OPEN),
            ("demux", &DEMUX),
            ("decode", &DECODE),
            ("conform", &CONFORM),
            ("encode", &ENCODE),
            ("mux", &MUX),
        ] {
            let ns = acc.swap(0, Relaxed);
            sum += ns;
            eprintln!(
                "  {name:<8} {:>9.1} ms  {:>5.1}%",
                ns as f64 / 1e6,
                100.0 * ns as f64 / total_ns
            );
        }
        let rest = total_ns - sum as f64;
        eprintln!(
            "  {:<8} {:>9.1} ms  {:>5.1}%",
            "other",
            rest / 1e6,
            100.0 * rest / total_ns
        );
    }
}

/// Codecs whose decoded output is inherently full-range (they decode to RGB, or
/// are defined on 0-255 samples). JPEG is the canonical case: the standard has
/// no limited-range mode, which is why FFmpeg calls its pixel formats `yuvj*`.
fn is_full_range_codec(codec: CodecId) -> bool {
    matches!(
        codec,
        CodecId::Jpeg | CodecId::Png | CodecId::Gif | CodecId::Webp | CodecId::Exr
    )
}

/// Codecs whose decoders hand out packed RGB(A) frames.
fn decodes_to_rgb(codec: CodecId) -> bool {
    matches!(
        codec,
        CodecId::Png | CodecId::Gif | CodecId::Webp | CodecId::Jxl | CodecId::Exr
    )
}

/// What range this stream's decoded frames are actually in.
///
/// An `Unspecified` stream is not "unknown, do nothing" — every consumer has to
/// pick something, so pick it here, once, explicitly:
/// full-range for codecs that are defined that way, limited-range otherwise
/// (the video convention, and what an untagged y4m means).
///
/// Before the codec default, an untagged H.264 stream's own SPS is asked: its
/// VUI carries `video_full_range_flag`, which is how a full-range stream in a
/// container without colour metadata (FLV, a Matroska file without `Colour`)
/// still round-trips.
fn effective_color_range(stream: &Stream) -> ColorRange {
    match stream.color_range {
        ColorRange::Unspecified => match extradata_color_range(stream) {
            Some(range) => range,
            None if is_full_range_codec(stream.codec_id) => ColorRange::Full,
            None => ColorRange::Limited,
        },
        explicit => explicit,
    }
}

/// The range signalled by the codec configuration in a stream's extradata
/// (the SPS of an H.264 `avcC` or Annex-B header), if it signals one.
fn extradata_color_range(stream: &Stream) -> Option<ColorRange> {
    let x = &stream.extradata;
    let full = match stream.codec_id {
        CodecId::H264 => {
            let annexb = rff_format::avc::parse_avcc(x).map(|c| c.headers_annexb);
            let headers = annexb.as_deref().unwrap_or(x);
            rff_format::avc::sps_full_range(rff_format::avc::find_sps_annexb(headers)?)?
        }
        _ => return None,
    };
    Some(if full {
        ColorRange::Full
    } else {
        ColorRange::Limited
    })
}

/// One input file for a job.
#[derive(Debug, Clone)]
pub struct InputSpec {
    pub path: PathBuf,
    /// Force a container format instead of guessing from the extension
    /// (`ffmpeg -f <fmt> -i ...`).
    pub format: Option<String>,
}

/// Per-stream codec selection for the output.
#[derive(Debug, Clone)]
pub struct StreamCodec {
    pub codec: CodecId,
    /// Codec options (`-b:v 2M`, `-crf 23`, ...).
    pub options: Dictionary,
    /// Output sample format pinned by the codec NAME (`-c:a pcm_s16le`) or by
    /// `-sample_fmt`. `None` = take whatever the decoder emits. Without this,
    /// raw-PCM output silently ignored the format half of its own codec name.
    pub sample_format: Option<SampleFormat>,
}

/// Which input stream(s) a `-map` entry selects.
#[derive(Debug, Clone)]
pub enum MapSelector {
    /// All streams of the input (`-map 0`).
    All,
    /// All streams of a media kind (`-map 0:v` / `0:a`).
    Kind(MediaType),
    /// One stream by index within the input (`-map 0:2`).
    Index(usize),
}

/// One `-map` entry: pick stream(s) from input `input`.
#[derive(Debug, Clone)]
pub struct MapSpec {
    pub input: usize,
    pub selector: MapSelector,
}

/// The output file for a job.
#[derive(Debug, Clone, Default)]
pub struct OutputSpec {
    pub path: PathBuf,
    /// Force a container format instead of guessing from the extension
    /// (`ffmpeg -f <fmt> ...`).
    pub format: Option<String>,
    /// Video codec for the output, if a video stream is produced.
    pub video_codec: Option<StreamCodec>,
    /// Audio codec for the output, if an audio stream is produced.
    pub audio_codec: Option<StreamCodec>,
    /// Subtitle codec (`-c:s subrip|webvtt`). Text-subtitle packets share one
    /// contract (plain text + ms timing), so this relabels the stream for the
    /// muxer rather than re-encoding anything.
    pub subtitle_codec: Option<CodecId>,
    /// Video filter graph (`-vf`), e.g. `scale=320:240,crop=...`. Applied to
    /// decoded video frames before re-encoding (transcode streams only).
    pub video_filters: Option<String>,
    /// Multi-input filter graph (`-filter_complex`). Currently models `overlay`:
    /// the last input is composited over input #0's video.
    pub filter_complex: Option<String>,
    /// Explicit stream selection (`-map`). Empty = default (all video + audio,
    /// in input/stream order).
    pub maps: Vec<MapSpec>,
    /// Media kinds dropped from the output whatever selected them (`-vn`,
    /// `-an`, `-sn`, `-dn`).
    pub disabled: Vec<MediaType>,
    /// Overwrite the output if it exists (`-y`); otherwise fail (`-n`).
    pub overwrite: bool,
    /// Stop after this many VIDEO frames (`-frames:v N`). `None` = whole input.
    ///
    /// This is a measurement-critical option: without it a harness that thinks
    /// it is encoding a 50-frame prefix silently encodes the whole clip, and any
    /// rate-vs-quality pairing computed against a prefix is then wrong.
    pub max_video_frames: Option<u64>,
    /// Output trim window start, in seconds (`-ss`). Decoded frames (or copied
    /// packets) before this point are dropped; timestamps are shifted so the
    /// output starts at zero.
    pub trim_start: Option<f64>,
    /// Output trim window end, in seconds (`-to`, or `-ss` + `-t`). Exclusive.
    pub trim_end: Option<f64>,
    /// Constant output frame rate (`-r`), as `(num, den)` — e.g. `(30000, 1001)`.
    /// Frames are duplicated/dropped to hit it (FFmpeg's `fps` filter).
    pub frame_rate: Option<(u32, u32)>,
    /// Target audio sample rate (`-ar`). The encoder's accepted-rate list still
    /// wins if it cannot take this exact rate (nearest accepted is used).
    pub audio_rate: Option<u32>,
    /// Target audio channel count (`-ac`): 1↔2 downmix/upmix.
    pub audio_channels: Option<u16>,
    /// Audio filter chain (`-af` / `-filter:a`), e.g. `volume=-6dB,atrim=...`.
    pub audio_filters: Option<String>,
    /// Output metadata (`-metadata title=...`), handed to muxers that carry it.
    pub metadata: Dictionary,
    /// Muxer options (`-hls_time 6` → `{"hls_time": "6"}`), for formats that
    /// take them (HLS/DASH segmenting).
    pub format_options: Dictionary,
    /// Pixel format handed to the video encoder (`-pix_fmt`). `None` = the
    /// encoder's best accepted format for the source (FFmpeg's automatic
    /// format negotiation). A format the encoder does not accept falls back to
    /// that automatic choice with a warning, as FFmpeg does.
    pub pixel_format: Option<PixelFormat>,
}

/// A complete, declarative transcoding job.
#[derive(Debug, Clone, Default)]
pub struct TranscodeSpec {
    pub inputs: Vec<InputSpec>,
    pub outputs: Vec<OutputSpec>,
}

/// A successful run's summary (frames/packets moved, etc.). Fields will grow as
/// the pipeline does.
#[derive(Debug, Clone, Default)]
pub struct TranscodeReport {
    pub packets_written: u64,
    pub frames_decoded: u64,
    /// Non-fatal notices raised while encoding (an incompatible `-pix_fmt`
    /// that was replaced, an alpha channel the encoder cannot carry, ...).
    pub warnings: Vec<String>,
}

/// Output trim window (`-ss` / `-t` / `-to`), in seconds.
#[derive(Clone, Copy)]
struct Trim {
    start: f64,
    end: Option<f64>,
}

impl Trim {
    fn from_spec(o: &OutputSpec) -> Option<Trim> {
        if o.trim_start.is_none() && o.trim_end.is_none() {
            return None;
        }
        Some(Trim {
            start: o.trim_start.unwrap_or(0.0).max(0.0),
            end: o.trim_end,
        })
    }

    fn keeps(&self, t: f64) -> bool {
        t >= self.start - 1e-9 && self.end.is_none_or(|e| t < e - 1e-9)
    }
}

/// CFR conversion state (`-r`): input frames are snapped onto a fixed
/// `num/den` fps grid, duplicating the previous frame across gaps and dropping
/// frames that land on an already-filled slot. Emitted frames carry their slot
/// index as pts (time base `den/num`).
struct FpsConv {
    num: u32,
    den: u32,
    next_slot: i64,
    last: Option<VideoFrame>,
}

impl FpsConv {
    fn new(num: u32, den: u32) -> FpsConv {
        FpsConv {
            num: num.max(1),
            den: den.max(1),
            next_slot: 0,
            last: None,
        }
    }

    fn slot_time(&self, slot: i64) -> f64 {
        slot as f64 * self.den as f64 / self.num as f64
    }

    /// Feed one input frame at time `t` (seconds); returns the frames due
    /// strictly before `t`, each stamped with its slot pts.
    fn push(&mut self, frame: VideoFrame, t: f64) -> Vec<VideoFrame> {
        let mut out = Vec::new();
        while let Some(last) = &self.last {
            if self.slot_time(self.next_slot) < t - 1e-9 {
                let mut f = last.clone();
                f.pts = Some(self.next_slot);
                out.push(f);
                self.next_slot += 1;
            } else {
                break;
            }
        }
        self.last = Some(frame);
        out
    }

    /// End of stream: emit the held frame in its slot.
    fn finish(&mut self) -> Option<VideoFrame> {
        self.last.take().map(|mut f| {
            f.pts = Some(self.next_slot);
            self.next_slot += 1;
            f
        })
    }
}

/// What to do with one input stream on its way to the output.
enum StreamOp {
    /// Not selected (or a media type we can't route): drop its packets.
    Skip,
    /// Remux packets unchanged into the output.
    Copy(CopyOp),
    /// Decode, filter, re-encode.
    Transcode(Box<TranscodeOp>),
}

/// Stream-copy: forward packets, applying the trim window at packet level.
/// Video cuts on the first keyframe inside the window (a copy can't split a
/// GOP); timestamps shift so the output starts at zero.
struct CopyOp {
    out_index: usize,
    is_video: bool,
    /// Trim window in stream ticks (`None` = no trimming).
    start_ticks: i64,
    end_ticks: Option<i64>,
    trimming: bool,
    /// Video: set once the first in-window keyframe has passed.
    started: bool,
}

impl CopyOp {
    /// Apply trim/shift; `None` = drop the packet.
    fn process(&mut self, mut packet: Packet) -> Option<Packet> {
        if self.trimming {
            let ts = packet.pts.or(packet.dts).unwrap_or(0);
            if ts < self.start_ticks {
                return None;
            }
            if let Some(end) = self.end_ticks {
                if ts >= end {
                    return None;
                }
            }
            if self.is_video && !self.started {
                if !packet.flags.keyframe {
                    return None; // wait for a clean random-access point
                }
                self.started = true;
            }
            packet.pts = packet.pts.map(|p| p - self.start_ticks);
            packet.dts = packet.dts.map(|d| d - self.start_ticks);
        }
        packet.stream_index = self.out_index;
        Some(packet)
    }
}

/// Decode → trim → fps → filters/overlay → audio conform → encode → mux.
struct TranscodeOp {
    decoder: Box<dyn Decoder>,
    encoder: Box<dyn Encoder>,
    filters: FilterChain,
    /// `-filter_complex` overlay: a pre-decoded frame composited onto each
    /// of this stream's frames at `(x, y)` (after `filters`). Video only.
    overlay: Option<(VideoFrame, u32, u32)>,
    /// The input stream's time base (frame pts are in these ticks).
    in_time_base: rff_core::Rational,
    is_video: bool,
    /// Output trim window; pts are shifted by `shift_ticks` after it.
    trim: Option<Trim>,
    shift_ticks: i64,
    /// Fallback clock for trimming audio whose frames carry no pts.
    audio_clock_samples: u64,
    /// `-r`: CFR duplicate/drop stage.
    fps: Option<FpsConv>,
    /// `-af`: the audio filter chain (volume/atrim/...).
    audio_chain: rff_filter::AudioFilterChain,
    /// `-ac`: mix to this many channels before everything else (0 = keep).
    target_channels: u16,
    /// Sample rate the encoder needs (0 = no audio resampling required).
    target_rate: u32,
    /// Sample format the output pins (`-c:a pcm_s16le`), if any.
    target_sample_format: Option<SampleFormat>,
    /// Lazily built once the first audio frame reveals the input rate.
    resampler: Option<Resampler>,
    /// Pixel-format negotiation + conversion in front of the encoder.
    pixels: PixelConform,
    /// Full → limited conversion for an encoder that cannot signal full
    /// range (applied after `pixels`).
    range_fix: Option<FilterChain>,
    /// Range of the frames reaching the encoder, for that conversion.
    source_range: ColorRange,
    /// Warnings raised mid-stream, handed to the report as they appear.
    warnings: Vec<String>,
    out_index: usize,
    /// `-frames:v` limit for this output, and how many we have sent.
    max_video_frames: Option<u64>,
    video_frames_sent: u64,
    /// pts of video frames handed to the encoder, FIFO. Video encoders that
    /// don't timestamp their packets (VP9, H.264) get these stamped on in
    /// [`TranscodeOp::drain`] — without it every Matroska block lands at t=0.
    pending_pts: std::collections::VecDeque<Option<i64>>,
}

/// Composite the `-filter_complex` overlay onto a video frame, if one is set.
/// Audio frames and the no-overlay case pass through untouched.
fn apply_overlay(overlay: &Option<(VideoFrame, u32, u32)>, frame: Frame) -> Result<Frame> {
    match (overlay, frame) {
        (Some((over, x, y)), Frame::Video(v)) => {
            Ok(Frame::Video(rff_filter::overlay(v, over, *x, *y)?))
        }
        (_, frame) => Ok(frame),
    }
}

/// Apply a video filter chain to a frame. Filters are video-only; audio passes
/// through untouched, and an empty chain is a no-op.
fn apply_filters(filters: &mut FilterChain, frame: Frame) -> Result<Frame> {
    if filters.is_empty() {
        return Ok(frame);
    }
    match frame {
        Frame::Video(v) => Ok(Frame::Video(filters.apply(v)?)),
        other => Ok(other),
    }
}

/// Pick the accepted rate closest to `target`.
fn nearest_rate(rates: &[u32], target: u32) -> u32 {
    rates
        .iter()
        .copied()
        .min_by_key(|r| (*r as i64 - target as i64).abs())
        .unwrap_or(target)
}

/// Read interleaved `s16`/`f32` plane 0 of an audio frame into `f32` samples.
fn audio_to_f32(af: &AudioFrame) -> Result<Vec<f32>> {
    match af.format {
        SampleFormat::F32 => Ok(af.planes[0]
            .chunks_exact(4)
            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
            .collect()),
        SampleFormat::S16 => Ok(af.planes[0]
            .chunks_exact(2)
            .map(|b| i16::from_le_bytes([b[0], b[1]]) as f32 / 32768.0)
            .collect()),
        other => Err(Error::unsupported(format!(
            "resample: sample format `{}` (need interleaved s16/f32)",
            other.name()
        ))),
    }
}

/// `f32` samples as little-endian bytes, in one sized pass. The
/// `iter().flat_map(to_le_bytes).collect()` this replaces is the pattern LLVM
/// handles worst -- an iterator of tiny arrays flattened into a growing `Vec`.
fn f32_le_bytes(samples: &[f32]) -> Vec<u8> {
    let mut bytes = vec![0u8; samples.len() * 4];
    for (d, s) in bytes.chunks_exact_mut(4).zip(samples) {
        d.copy_from_slice(&s.to_le_bytes());
    }
    bytes
}

/// The usual f32 -> s16 rule: round to nearest, then clamp. Truncation would
/// bias every sample toward zero.
fn f32_to_s16(s: f32) -> i16 {
    (s * 32768.0).round().clamp(-32768.0, 32767.0) as i16
}

/// Wrap interleaved `f32` samples as an `f32` [`AudioFrame`].
fn f32_frame(samples: Vec<f32>, rate: u32, channels: u16, pts: Option<i64>) -> Frame {
    let bytes = f32_le_bytes(&samples);
    Frame::Audio(AudioFrame {
        sample_rate: rate,
        channels,
        format: SampleFormat::F32,
        samples: samples.len() / channels.max(1) as usize,
        planes: vec![bytes],
        pts,
    })
}

/// Convert an audio frame to `target` sample format, if one is pinned and the
/// frame is not already in it. The audio analogue of `conform_video`: raw PCM
/// output declares its format in the container header, so the frames handed to
/// the muxer must actually BE that format, not merely be labelled it.
fn conform_sample_format(target: Option<SampleFormat>, frame: Frame) -> Result<Frame> {
    let Some(target) = target else {
        return Ok(frame);
    };
    let Frame::Audio(af) = frame else {
        return Ok(frame);
    };
    if af.format == target {
        return Ok(Frame::Audio(af));
    }
    // Bytes to bytes in ONE pass. This used to decode the whole plane into a
    // `Vec<f32>` and then re-encode it through `flat_map(..).collect()` -- an
    // extra full-frame copy (a WAV's worth, when the frame is a whole file) and
    // the iterator shape LLVM vectorises worst. The arithmetic per sample is
    // the same expression, so the output is byte-identical.
    let src = &af.planes[0];
    let plane = match (af.format, target) {
        (SampleFormat::F32, SampleFormat::S16) => {
            let mut out = vec![0u8; src.len() / 4 * 2];
            for (d, b) in out.chunks_exact_mut(2).zip(src.chunks_exact(4)) {
                let s = f32::from_le_bytes([b[0], b[1], b[2], b[3]]);
                d.copy_from_slice(&f32_to_s16(s).to_le_bytes());
            }
            out
        }
        (SampleFormat::S16, SampleFormat::F32) => {
            let mut out = vec![0u8; src.len() / 2 * 4];
            for (d, b) in out.chunks_exact_mut(4).zip(src.chunks_exact(2)) {
                let s = i16::from_le_bytes([b[0], b[1]]) as f32 / 32768.0;
                d.copy_from_slice(&s.to_le_bytes());
            }
            out
        }
        _ => {
            // Not a supported pair: report the source format first, as before.
            audio_to_f32(&af)?;
            return Err(Error::unsupported(format!(
                "sample format conversion to `{}` (only interleaved s16/f32)",
                target.name()
            )));
        }
    };
    let planes = vec![plane];
    Ok(Frame::Audio(AudioFrame {
        sample_rate: af.sample_rate,
        channels: af.channels,
        format: target,
        samples: af.samples,
        planes,
        pts: af.pts,
    }))
}

/// Resample an audio frame to `target_rate` if needed (the resampler is built
/// lazily from the first frame's rate/channels). `target_rate == 0` is a no-op.
fn conform_audio(
    resampler: &mut Option<Resampler>,
    target_rate: u32,
    frame: Frame,
) -> Result<Frame> {
    if target_rate == 0 {
        return Ok(frame);
    }
    let Frame::Audio(af) = frame else {
        return Ok(frame);
    };
    if af.sample_rate == target_rate {
        return Ok(Frame::Audio(af));
    }
    let rs =
        resampler.get_or_insert_with(|| Resampler::new(af.sample_rate, target_rate, af.channels));
    let out = rs.process(&audio_to_f32(&af)?);
    let pts = af
        .pts
        .map(|p| p * target_rate as i64 / af.sample_rate.max(1) as i64);
    Ok(f32_frame(out, target_rate, af.channels, pts))
}

/// Pick the pixel format to hand an encoder for a `src` frame — FFmpeg's
/// automatic format negotiation (`avcodec_find_best_pix_fmt_of_list` plus the
/// `-pix_fmt` override).
///
/// * `requested` (`-pix_fmt`) wins when the encoder accepts it. When it does
///   not, the automatic choice is used instead and a warning says so, worded
///   as FFmpeg words it ("Incompatible pixel format ...").
/// * A source the encoder already accepts passes through untouched.
/// * Otherwise: the encoder's most-preferred accepted format that the
///   pipeline can convert `src` into, keeping high bit depth when the
///   reference (the request, else the source) has it and the encoder takes it,
///   and staying at 8 bits otherwise.
///
/// Returns the chosen format plus any warnings. `accepted == None` means the
/// encoder takes anything.
fn negotiate_pixel_format(
    src: PixelFormat,
    accepted: Option<&[PixelFormat]>,
    requested: Option<PixelFormat>,
    codec: CodecId,
) -> Result<(PixelFormat, Vec<String>)> {
    let accepted = accepted.filter(|a| !a.is_empty());
    let accepts = |f: PixelFormat| accepted.is_none_or(|a| a.contains(&f));
    let mut warnings = Vec::new();
    let chosen = match requested {
        Some(req) if accepts(req) => req,
        Some(req) => {
            let best = best_pixel_format(src, req, accepted.unwrap_or_default())?;
            warnings.push(format!(
                "Incompatible pixel format '{}' for codec '{}', auto-selecting format '{}'",
                req.name(),
                codec.name(),
                best.name()
            ));
            best
        }
        None if accepts(src) => src,
        None => best_pixel_format(src, src, accepted.unwrap_or_default())?,
    };
    if chosen != src && !rff_filter::can_convert(src, chosen) {
        return Err(Error::unsupported(format!(
            "no conversion from `{}` to `{}`",
            src.name(),
            chosen.name()
        )));
    }
    if src.has_alpha() && !chosen.has_alpha() {
        warnings.push(format!(
            "codec '{}' has no alpha channel in `{}`: the alpha of the `{}` input is dropped",
            codec.name(),
            chosen.name(),
            src.name()
        ));
    }
    Ok((chosen, warnings))
}

/// The encoder's best accepted format for a `src` frame: candidates are the
/// accepted formats `src` converts into, in the encoder's preference order;
/// a high-bit-depth `reference` takes the first deep candidate, an 8-bit one
/// the first 8-bit candidate, and failing that the first candidate of any
/// depth.
fn best_pixel_format(
    src: PixelFormat,
    reference: PixelFormat,
    accepted: &[PixelFormat],
) -> Result<PixelFormat> {
    let candidates: Vec<PixelFormat> = accepted
        .iter()
        .copied()
        .filter(|&f| rff_filter::can_convert(src, f))
        .collect();
    let deep = reference.bit_depth() > 8;
    candidates
        .iter()
        .copied()
        .find(|f| (f.bit_depth() > 8) == deep)
        .or(candidates.first().copied())
        .ok_or_else(|| {
            let names: Vec<&str> = accepted.iter().map(|f| f.name()).collect();
            Error::unsupported(format!(
                "no conversion from `{}` to any format this encoder accepts ({})",
                src.name(),
                names.join(", ")
            ))
        })
}

/// Converts video frames into the pixel format negotiated with the encoder,
/// if they aren't already in it. The converting chain is built lazily from
/// the first frame that needs it, mirroring the audio resampler above.
///
/// This is what lets a decoder emit its cheapest native layout: the JPEG decoder
/// hands out planar Y'CbCr, and a PNG encoder downstream still gets the RGB it
/// requires because this inserts the conversion. Equally, a PNG's RGB reaches
/// an AVIF / H.264 / VP9 encoder as the planar Y'CbCr it needs.
struct PixelConform {
    /// Pixel formats the encoder accepts (`None` = anything).
    accepted: Option<Vec<PixelFormat>>,
    /// `-pix_fmt`, if given.
    requested: Option<PixelFormat>,
    /// The output codec, for messages.
    codec: CodecId,
    /// An RGB → Y'CbCr conversion produces limited range (FFmpeg's default,
    /// and what a video bitstream that carries no range flag is read as),
    /// rather than following the source's full range. True for the
    /// compressed video codecs; the full-range image codecs and raw video
    /// keep the source range.
    rgb_to_limited: bool,
    /// The range committed for the output stream (what the muxer labels and
    /// the encoder signals). An RGB → Y'CbCr conversion produces it, so a
    /// source only discovered to be RGB at the first frame (a progressive
    /// JPEG) still matches the label. `None`: decide by `rgb_to_limited`.
    out_range: Option<ColorRange>,
    /// Source format the converter below was built for, the target it
    /// converts to, and the converter (`None` when they are equal).
    state: Option<(PixelFormat, PixelFormat, Option<FilterChain>)>,
}

impl PixelConform {
    fn new(
        accepted: Option<Vec<PixelFormat>>,
        requested: Option<PixelFormat>,
        codec: CodecId,
    ) -> PixelConform {
        PixelConform {
            accepted,
            requested,
            codec,
            rgb_to_limited: !is_full_range_codec(codec) && codec != CodecId::RawVideo,
            out_range: None,
            state: None,
        }
    }

    fn negotiate(&self, src: PixelFormat) -> Result<(PixelFormat, Vec<String>)> {
        negotiate_pixel_format(src, self.accepted.as_deref(), self.requested, self.codec)
    }

    fn conform(
        &mut self,
        source_range: ColorRange,
        frame: Frame,
        warnings: &mut Vec<String>,
    ) -> Result<Frame> {
        if self.accepted.is_none() && self.requested.is_none() {
            return Ok(frame);
        }
        let Frame::Video(vf) = frame else {
            return Ok(frame);
        };
        let fresh = !matches!(&self.state, Some((src, _, _)) if *src == vf.format);
        if fresh {
            let (target, mut notes) = self.negotiate(vf.format)?;
            warnings.append(&mut notes);
            let converter = if target == vf.format {
                None
            } else {
                // Pin the range: `spec.limited` describes the Y'CbCr side
                // either way, and guessing it wrong is a silent several-dB
                // error.
                let limited = if vf.format.is_rgb() && !target.is_rgb() {
                    match self.out_range {
                        Some(range) => range != ColorRange::Full,
                        None => self.rgb_to_limited || source_range == ColorRange::Limited,
                    }
                } else {
                    source_range == ColorRange::Limited
                };
                Some(FilterChain::parse(&format!(
                    "format={}:bt601:{}",
                    target.name(),
                    if limited { "limited" } else { "full" }
                ))?)
            };
            self.state = Some((vf.format, target, converter));
        }
        match &mut self.state {
            Some((_, _, Some(chain))) => Ok(Frame::Video(chain.apply(vf)?)),
            _ => Ok(Frame::Video(vf)),
        }
    }
}

/// Mix an audio frame to `target` channels (0 = keep). Stereo↔mono only: a
/// downmix averages pairs, an upmix duplicates the channel.
fn conform_channels(target: u16, frame: Frame) -> Result<Frame> {
    if target == 0 {
        return Ok(frame);
    }
    let Frame::Audio(af) = frame else {
        return Ok(frame);
    };
    if af.channels == target {
        return Ok(Frame::Audio(af));
    }
    let samples = audio_to_f32(&af)?;
    let mixed: Vec<f32> = match (af.channels, target) {
        (2, 1) => samples
            .chunks_exact(2)
            .map(|p| 0.5 * (p[0] + p[1]))
            .collect(),
        (1, 2) => samples.iter().flat_map(|s| [*s, *s]).collect(),
        (from, to) => {
            return Err(Error::unsupported(format!(
                "-ac: only 1<->2 channel mixing supported (input {from} ch, requested {to})"
            )))
        }
    };
    Ok(f32_frame(mixed, af.sample_rate, target, af.pts))
}

impl TranscodeOp {
    /// A frame's start time in seconds (input timeline). Audio without pts
    /// falls back to a running sample clock; video without pts cannot be
    /// placed and errors — only called when trim/fps actually need the time.
    fn frame_time(&self, frame: &Frame) -> Result<f64> {
        let tb = self.in_time_base;
        let tick = if tb.num > 0 && tb.den > 0 {
            tb.num as f64 / tb.den as f64
        } else {
            0.001
        };
        match frame.pts() {
            Some(p) => Ok(p as f64 * tick),
            None => match frame {
                Frame::Audio(af) => {
                    Ok(self.audio_clock_samples as f64 / af.sample_rate.max(1) as f64)
                }
                Frame::Video(_) => Err(Error::unsupported(
                    "-ss/-t/-to/-r need timestamps and this video stream has none",
                )),
            },
        }
    }

    /// Decoded-frame entry point: trim window, timestamp shift, CFR stage,
    /// then the per-frame pipeline in [`TranscodeOp::emit`].
    fn handle_frame(
        &mut self,
        frame: Frame,
        muxer: &mut dyn Muxer,
        report: &mut TranscodeReport,
    ) -> Result<()> {
        report.frames_decoded += 1;
        let needs_time = self.trim.is_some() || (self.is_video && self.fps.is_some());
        let t = if needs_time {
            Some(self.frame_time(&frame)?)
        } else {
            None
        };
        // The sample clock tracks ALL input audio, kept or dropped.
        if let Frame::Audio(af) = &frame {
            self.audio_clock_samples += af.samples as u64;
        }
        let mut frame = frame;
        if let (Some(trim), Some(t)) = (self.trim, t) {
            match frame {
                // Audio frames can be arbitrarily long (a WAV decodes as one
                // frame), so the window slices samples instead of keep/drop.
                Frame::Audio(af) => {
                    match rff_filter::trim_audio_frame(af, Some(t), Some(trim.start), trim.end)? {
                        Some(af) => frame = Frame::Audio(af),
                        None => return Ok(()),
                    }
                }
                Frame::Video(_) => {
                    if !trim.keeps(t) {
                        return Ok(());
                    }
                }
            }
        }
        // Shift timestamps so the output timeline starts at zero.
        if self.shift_ticks != 0 {
            match &mut frame {
                Frame::Video(v) => v.pts = v.pts.map(|p| p - self.shift_ticks),
                Frame::Audio(a) => a.pts = a.pts.map(|p| p - self.shift_ticks),
            }
        }
        match frame {
            Frame::Video(v) if self.fps.is_some() => {
                let t_out = t.expect("fps requires time") - self.trim.map_or(0.0, |w| w.start);
                let mut fps = self.fps.take().expect("checked");
                let due = fps.push(v, t_out);
                self.fps = Some(fps);
                for f in due {
                    self.emit(Frame::Video(f), muxer, report)?;
                }
                Ok(())
            }
            other => self.emit(other, muxer, report),
        }
    }

    /// Post-fps pipeline: `-frames:v` gate, filters, overlay, audio conforms,
    /// encode, drain.
    fn emit(
        &mut self,
        frame: Frame,
        muxer: &mut dyn Muxer,
        report: &mut TranscodeReport,
    ) -> Result<()> {
        if let Some(limit) = self.max_video_frames {
            if matches!(frame, Frame::Video(_)) {
                if self.video_frames_sent >= limit {
                    return Ok(());
                }
                self.video_frames_sent += 1;
            }
        }
        let conformed = phases::time(&phases::CONFORM, || self.conform(frame));
        report.warnings.append(&mut self.warnings);
        let Some(frame) = conformed? else {
            return Ok(()); // atrim consumed the whole frame
        };
        if self.is_video {
            self.pending_pts.push_back(frame.pts());
        }
        phases::time(&phases::ENCODE, || self.encoder.send_frame(&frame))?;
        self.drain(muxer, report)
    }

    /// The per-frame conform chain between decode and encode: filters, overlay,
    /// channel/rate/sample-format/pixel conforms. `None` = atrim dropped it.
    fn conform(&mut self, frame: Frame) -> Result<Option<Frame>> {
        let frame = apply_filters(&mut self.filters, frame)?;
        let frame = apply_overlay(&self.overlay, frame)?;
        let frame = conform_channels(self.target_channels, frame)?;
        let frame = match frame {
            Frame::Audio(af) if !self.audio_chain.is_empty() => {
                let tb = self.in_time_base;
                let t = af
                    .pts
                    .map(|p| p as f64 * tb.num as f64 / tb.den.max(1) as f64);
                match self.audio_chain.apply(af, t)? {
                    Some(af) => Frame::Audio(af),
                    None => return Ok(None),
                }
            }
            other => other,
        };
        let frame = conform_audio(&mut self.resampler, self.target_rate, frame)?;
        let frame = conform_sample_format(self.target_sample_format, frame)?;
        let frame = self
            .pixels
            .conform(self.source_range, frame, &mut self.warnings)?;
        let frame = match (&mut self.range_fix, frame) {
            (Some(chain), Frame::Video(vf)) => Frame::Video(chain.apply(vf)?),
            (_, frame) => frame,
        };
        Ok(Some(frame))
    }

    /// Pull every ready packet out of the encoder and mux it. Video encoders
    /// that don't timestamp their packets (VP9, H.264 emit `pts: None`) get the
    /// corresponding source frame's pts stamped on, FIFO — without this every
    /// Matroska block would land at t=0.
    fn drain(&mut self, muxer: &mut dyn Muxer, report: &mut TranscodeReport) -> Result<()> {
        loop {
            match phases::time(&phases::ENCODE, || self.encoder.receive_packet()) {
                Ok(mut packet) => {
                    if self.is_video {
                        let queued = self.pending_pts.pop_front().flatten();
                        if packet.pts.is_none() {
                            packet.pts = queued;
                        }
                    }
                    packet.stream_index = self.out_index;
                    phases::time(&phases::MUX, || muxer.write_packet(&packet))?;
                    report.packets_written += 1;
                }
                Err(Error::Again) | Err(Error::Eof) => break,
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }

    /// End of input: flush the decoder, the CFR stage's held frame, the
    /// resampler's FIR tail, then the encoder.
    fn finish(&mut self, muxer: &mut dyn Muxer, report: &mut TranscodeReport) -> Result<()> {
        self.decoder.flush();
        loop {
            match phases::time(&phases::DECODE, || self.decoder.receive_frame()) {
                Ok(frame) => self.handle_frame(frame, muxer, report)?,
                Err(Error::Again) | Err(Error::Eof) => break,
                Err(e) => return Err(e),
            }
        }
        if let Some(mut fps) = self.fps.take() {
            let held = fps.finish();
            self.fps = Some(fps);
            if let Some(f) = held {
                self.emit(Frame::Video(f), muxer, report)?;
            }
        }
        if let Some(rs) = &mut self.resampler {
            let tail = rs.finish();
            if !tail.is_empty() {
                let frame = f32_frame(tail, rs.out_rate(), rs.channels(), None);
                let frame = conform_sample_format(self.target_sample_format, frame)?;
                self.encoder.send_frame(&frame)?;
                self.drain(muxer, report)?;
            }
        }
        phases::time(&phases::ENCODE, || self.encoder.flush());
        self.drain(muxer, report)
    }
}

/// Resolve and run a transcode job against `engine`.
///
/// Resolution (formats, decoders, encoders) happens up front so failures are
/// reported before any output file is touched; then the demux→decode→encode→mux
/// loop runs to completion.
pub fn run(engine: &Engine, spec: &TranscodeSpec) -> Result<TranscodeReport> {
    if spec.inputs.is_empty() {
        return Err(Error::Option("no input files specified".into()));
    }
    if spec.outputs.is_empty() {
        return Err(Error::Option("no output file specified".into()));
    }
    if spec.outputs.len() > 1 {
        return Err(Error::unsupported("multiple outputs are not supported yet"));
    }
    let output = &spec.outputs[0];

    // -filter_complex overlay: the last input is composited over input #0's
    // video. Resolve it up front so stream selection can exclude that input.
    let overlay_xy = output
        .filter_complex
        .as_deref()
        .map(FilterComplex::parse)
        .transpose()?
        .and_then(|fc| fc.overlay);
    let overlay_input = match overlay_xy {
        Some(_) if spec.inputs.len() >= 2 => Some(spec.inputs.len() - 1),
        Some(_) => {
            return Err(Error::Option(
                "filter_complex overlay needs a second input (the overlay image/video)".into(),
            ))
        }
        None => None,
    };

    // --- open every input demuxer and read its streams ---
    // (`open` is a phase of its own: demuxers read only their headers here and
    // stream packets after; MP4 from a pipe, which must buffer to reach a
    // trailing `moov`, is the one that still does all of its I/O at open.)
    let t_start = phases::on().then(std::time::Instant::now);
    // Timecode tracks are streams only when data streams are asked for by
    // kind (`-map 0:d`): otherwise stream numbers, and what `-map 0` selects,
    // stay as they are and the timecode travels as `Stream::timecode`.
    let timecode_streams = output
        .maps
        .iter()
        .any(|m| matches!(m.selector, MapSelector::Kind(MediaType::Data)));
    let mut demuxers: Vec<Box<dyn rff_format::Demuxer>> = Vec::new();
    let mut input_streams: Vec<Vec<Stream>> = Vec::new();
    for input in &spec.inputs {
        let (demuxer, streams) = phases::time(&phases::OPEN, || -> Result<_> {
            let (in_format, source) = open_input(engine, input)?;
            let mut demuxer = source.open_demuxer(engine, &in_format)?;
            if timecode_streams {
                demuxer.set_timecode_streams(true);
            }
            let streams = demuxer.read_header()?;
            Ok((demuxer, streams))
        })?;
        input_streams.push(streams);
        demuxers.push(demuxer);
    }

    // --- select which (input, stream) pairs go to the output, in order ---
    let mut selection = select_streams(&input_streams, output)?;
    // An MP4 chapter track is a data stream no muxer takes; its chapters are
    // carried as chapters, so `-map 0` and `-map 0:d` pass over it.
    selection.retain(|&(inp, i)| {
        input_streams[inp][i].media_type != MediaType::Data
            || !is_chapter_track(&*demuxers[inp], input_streams[inp].len(), i)
            || output
                .maps
                .iter()
                .any(|m| m.input == inp && matches!(m.selector, MapSelector::Index(n) if n == i))
    });
    // The overlay input is consumed by the filter, not muxed as its own stream.
    if let Some(oin) = overlay_input {
        selection.retain(|(inp, _)| *inp != oin);
    }
    if selection.is_empty() {
        return Err(Error::unsupported("no streams selected for the output"));
    }
    // A still-image output holds one picture. Without `-map`, keep one video
    // stream — the first one marked default (a JPEG MPF file's primary image,
    // not its gain map or thumbnails), else the first — as FFmpeg picks a
    // single best video stream. `-map 0:N` picks any other.
    if output.maps.is_empty() {
        let still = resolve_output_format(engine, output)
            .ok()
            .and_then(|name| engine.formats.by_name(&name))
            .is_some_and(|f| f.mux_caps.still_image);
        if still {
            let is_video =
                |&(inp, i): &(usize, usize)| input_streams[inp][i].media_type == MediaType::Video;
            let keep = selection
                .iter()
                .copied()
                .filter(is_video)
                .find(|&(inp, i)| input_streams[inp][i].disposition.default == Some(true))
                .or_else(|| selection.iter().copied().find(is_video));
            if let Some(keep) = keep {
                selection.retain(|s| !is_video(s) || *s == keep);
            }
        }
    }

    // Single-codec containers can't stream-copy a foreign codec, so an unset
    // `-c:v` must mean TRANSCODE to the container's one codec, not copy (which
    // the muxer would reject). y4m additionally can't carry anything compressed.
    // Mirrors ffmpeg picking the muxer's default codec (`out.webp` → webp).
    // When the source already IS that codec, `None` stays: stream-copy wins.
    let mut output_owned;
    let output = if output.video_codec.is_none() {
        let format_name = resolve_output_format(engine, output).ok();
        // y4m keeps its unconditional default: it can't carry anything
        // compressed, so even rawvideo input goes through the decode path.
        let required = match format_name.as_deref() {
            Some("yuv4mpegpipe") => Some((CodecId::RawVideo, true)),
            Some("webp") => Some((CodecId::Webp, false)),
            Some("png") => Some((CodecId::Png, false)),
            Some("jpeg") | Some("jpeg_mpf") => Some((CodecId::Jpeg, false)),
            Some("gif") => Some((CodecId::Gif, false)),
            Some("avif") => Some((CodecId::Avif, false)),
            Some("jpegxl") => Some((CodecId::Jxl, false)),
            Some("exr_pipe") => Some((CodecId::Exr, false)),
            _ => None,
        };
        let apply = match required {
            Some((_, true)) => true,
            // Image containers: only when the source codec differs — a matching
            // source keeps `None` and takes the stream-copy fast path.
            Some((codec, false)) => !selection.iter().any(|&(inp, local)| {
                let s = &input_streams[inp][local];
                s.media_type == MediaType::Video && s.codec_id == codec
            }),
            None => false,
        };
        if apply {
            output_owned = output.clone();
            output_owned.video_codec = Some(StreamCodec {
                codec: required.expect("apply implies required").0,
                options: Dictionary::default(),
                sample_format: None, // video: no audio sample format to pin
            });
            &output_owned
        } else {
            output
        }
    } else {
        output
    };

    // Per-input op tables (Skip for unselected streams) + ordered output streams.
    let mut per_input_ops: Vec<Vec<StreamOp>> = input_streams
        .iter()
        .map(|s| (0..s.len()).map(|_| StreamOp::Skip).collect())
        .collect();
    let mut out_streams: Vec<Stream> = Vec::new();
    for (out_index, &(inp, local)) in selection.iter().enumerate() {
        let (op, os) = build_op(engine, &input_streams[inp][local], output, out_index)?;
        per_input_ops[inp][local] = op;
        out_streams.push(os);
    }

    // --- filter_complex overlay: pre-decode the overlay frame and hand it to
    // input #0's video transcode op (which composites it onto every frame) ---
    if let (Some((x, y)), Some(oin)) = (overlay_xy, overlay_input) {
        let over = decode_overlay_frame(engine, &mut *demuxers[oin], &input_streams[oin])?;
        let vidx = input_streams[0]
            .iter()
            .position(|s| s.media_type == MediaType::Video)
            .ok_or_else(|| Error::Option("filter_complex overlay: input #0 has no video".into()))?;
        match &mut per_input_ops[0][vidx] {
            StreamOp::Transcode(op) => op.overlay = Some((over, x, y)),
            _ => {
                return Err(Error::unsupported(
                    "filter_complex overlay needs input #0's video re-encoded — pass -c:v",
                ))
            }
        }
    }

    // --- pick the muxer from the registry. Path-based formats (HLS/DASH: a
    // playlist plus many segment files) are built with the output path; every
    // other format writes one byte sink through rff-io (file, pipe, udp).
    let out_format = resolve_output_format(engine, output)?;
    let muxer_path_factory = engine
        .formats
        .by_name(&out_format)
        .filter(|fmt| fmt.can_mux())
        .ok_or_else(|| Error::MuxerNotFound(out_format.clone()))?
        .muxer_path;

    // --- refuse to clobber an existing file unless -y was given (pipes and
    // sockets have nothing to clobber) ---
    let out_path_str = output.path.to_str().unwrap_or_default();
    let is_sink_stream = rff_io::is_pipe(out_path_str)
        || rff_io::is_udp(out_path_str)
        || rff_io::is_rtmp(out_path_str);
    if !is_sink_stream && !output.overwrite && output.path.exists() {
        return Err(Error::Option(format!(
            "{} already exists (pass -y to overwrite)",
            output.path.display()
        )));
    }
    let mut muxer: Box<dyn Muxer> = match muxer_path_factory {
        Some(factory) => factory(&output.path, &output.format_options)?,
        // A local file is seekable: muxers that can stream and patch their
        // header afterwards take that path (#28); pipes and network sinks
        // keep the plain one.
        None => match rff_io::create_seekable(out_path_str)? {
            Some(file) => engine
                .formats
                .open_muxer_seekable(&out_format, Box::new(file))?,
            None => engine
                .formats
                .open_muxer(&out_format, rff_io::create(out_path_str)?)?,
        },
    };
    if !output.metadata.is_empty() {
        muxer.set_metadata(&output.metadata);
    }
    // Format options (`-movflags +faststart`) reach byte-sink muxers too; a
    // path muxer already took them in its factory.
    if muxer_path_factory.is_none() {
        for (key, value) in output.format_options.iter() {
            muxer.set_option(key, value);
        }
    }
    // Per-stream metadata rides along from the input stream (FFmpeg's default
    // `-map_metadata`): a JPEG MPF remux keeps each image's MP Type.
    for (out_index, &(inp, local)) in selection.iter().enumerate() {
        if let Some(md) = demuxers[inp].stream_metadata(local) {
            muxer.set_stream_metadata(out_index, md);
        }
    }
    // What a stream refers to (its timecode track) follows it, as far as the
    // targets are in the output too.
    for (out_index, &(inp, local)) in selection.iter().enumerate() {
        let refs: Vec<TrackReference> = demuxers[inp]
            .track_references(local)
            .iter()
            .filter_map(|r| {
                let to: Vec<usize> = r
                    .streams
                    .iter()
                    .filter_map(|&t| selection.iter().position(|&s| s == (inp, t)))
                    .collect();
                (!to.is_empty()).then(|| TrackReference::new(r.kind, to))
            })
            .collect();
        if !refs.is_empty() {
            muxer.set_track_references(out_index, &refs);
        }
    }
    let chapters = output_chapters(&demuxers, output)?;
    if !chapters.is_empty() {
        muxer.set_chapters(&chapters);
    }
    muxer.write_header(&out_streams)?;

    let mut report = TranscodeReport::default();

    // Streams every op skips (unmapped, -vn/-an, the overlay input once its
    // frame is decoded) are never needed: let each demuxer drop them at the
    // source instead of reading and converting packets only to discard them.
    for (demuxer, ops) in demuxers.iter_mut().zip(&per_input_ops) {
        let discard: Vec<bool> = ops.iter().map(|op| matches!(op, StreamOp::Skip)).collect();
        if discard.contains(&true) {
            demuxer.set_discard(&discard);
        }
    }

    // --- drive each input through its plan into the shared muxer ---
    for (demuxer, ops) in demuxers.iter_mut().zip(per_input_ops.iter_mut()) {
        loop {
            match phases::time(&phases::DEMUX, || demuxer.read_packet()) {
                Ok(packet) => process_packet(packet, ops, &mut *muxer, &mut report)?,
                Err(Error::Eof) => break,
                Err(e) => return Err(e),
            }
        }
        flush_streams(ops, &mut *muxer, &mut report)?;
    }
    phases::time(&phases::MUX, || muxer.write_trailer())?;
    if let Some(t) = t_start {
        phases::report(t.elapsed());
    }

    Ok(report)
}

/// The chapters of the output: those of the first input that has any, as
/// FFmpeg takes them by default, or of the input `map_chapters` names in the
/// format options (`-map_chapters N`; a negative number takes none), cut to
/// the trim window.
fn output_chapters(
    demuxers: &[Box<dyn rff_format::Demuxer>],
    output: &OutputSpec,
) -> Result<Vec<Chapter>> {
    let chapters = match output.format_options.get("map_chapters") {
        Some(v) => {
            let n: i64 = v
                .trim()
                .parse()
                .map_err(|_| Error::Option(format!("-map_chapters: not an input number: {v}")))?;
            match usize::try_from(n) {
                Ok(n) => demuxers
                    .get(n)
                    .ok_or_else(|| Error::Option(format!("-map_chapters: no input #{n}")))?
                    .chapters(),
                Err(_) => &[],
            }
        }
        None => demuxers
            .iter()
            .map(|d| d.chapters())
            .find(|c| !c.is_empty())
            .unwrap_or(&[]),
    };
    Ok(match Trim::from_spec(output) {
        Some(t) => rff_format::chapter::trim(chapters, t.start, t.end),
        None => chapters.to_vec(),
    })
}

/// Whether another of the `n` streams refers to `stream` as its chapters.
fn is_chapter_track(demuxer: &dyn rff_format::Demuxer, n: usize, stream: usize) -> bool {
    (0..n).any(|i| {
        demuxer
            .track_references(i)
            .iter()
            .any(|r| &r.kind == b"chap" && r.streams.contains(&stream))
    })
}

/// Resolve which `(input_index, stream_index)` pairs go to the output, in
/// output order. With no `-map`, defaults to every video + audio stream across
/// all inputs (input order, then stream order). Kinds in
/// [`OutputSpec::disabled`] are then dropped, mapped or not.
fn select_streams(inputs: &[Vec<Stream>], output: &OutputSpec) -> Result<Vec<(usize, usize)>> {
    let mut selection = mapped_streams(inputs, output)?;
    selection.retain(|&(ii, i)| !output.disabled.contains(&inputs[ii][i].media_type));
    Ok(selection)
}

fn mapped_streams(inputs: &[Vec<Stream>], output: &OutputSpec) -> Result<Vec<(usize, usize)>> {
    let mut selection = Vec::new();
    if output.maps.is_empty() {
        for (ii, streams) in inputs.iter().enumerate() {
            for (i, s) in streams.iter().enumerate() {
                if matches!(
                    s.media_type,
                    MediaType::Video | MediaType::Audio | MediaType::Subtitle
                ) {
                    selection.push((ii, i));
                }
            }
        }
    } else {
        for map in &output.maps {
            let streams = inputs
                .get(map.input)
                .ok_or_else(|| Error::Option(format!("-map: no input #{}", map.input)))?;
            for (i, s) in streams.iter().enumerate() {
                let hit = match &map.selector {
                    MapSelector::All => true,
                    MapSelector::Kind(k) => s.media_type == *k,
                    MapSelector::Index(idx) => i == *idx,
                };
                if hit {
                    selection.push((map.input, i));
                }
            }
        }
    }
    Ok(selection)
}

/// Build the [`StreamOp`] (transcode or copy) and matching output [`Stream`] for
/// one selected input stream at output position `out_index`.
fn build_op(
    engine: &Engine,
    stream: &Stream,
    output: &OutputSpec,
    out_index: usize,
) -> Result<(StreamOp, Stream)> {
    let requested = match stream.media_type {
        MediaType::Video => output.video_codec.as_ref(),
        MediaType::Audio => output.audio_codec.as_ref(),
        _ => None,
    };
    match requested {
        // Transcode: decode the input codec, re-encode to the requested one.
        Some(target) => {
            let mut decoder = engine.codecs.find_decoder(stream.codec_id)?;
            decoder.configure(&codec_params(stream))?;
            let mut encoder = engine.codecs.find_encoder(target.codec)?;
            encoder.configure(&target.options)?; // rate control: -crf / -preset / -b
                                                 // Video filter graph (`-vf`); applies to video streams only.
            let mut filters = if stream.media_type == MediaType::Video {
                FilterChain::parse(output.video_filters.as_deref().unwrap_or(""))?
            } else {
                FilterChain::default()
            };
            // Colour range has to be reconciled before any filter runs. JPEG (and
            // the other image codecs) are defined on full-range samples, so
            // handing them limited-range video encodes the wrong signal — it
            // measured 28.35 dB where it should have been 36.15 dB, a deficit
            // that looked exactly like poor encoder quality. Convert once, up
            // front, then tell the rest of the chain what it is now looking at.
            let mut source_range = ColorRange::Unspecified;
            if stream.media_type == MediaType::Video {
                source_range = effective_color_range(stream);
                if is_full_range_codec(target.codec) && source_range == ColorRange::Limited {
                    filters.prepend_range_conversion(true);
                    source_range = ColorRange::Full;
                }
                filters.set_source_color_range(source_range);
            }
            let (out_w, out_h) = filters.output_dims(stream.width, stream.height);
            let is_video = stream.media_type == MediaType::Video;
            let is_audio = stream.media_type == MediaType::Audio;

            // Audio filter chain (`-af`); audio streams only.
            let audio_chain = if is_audio {
                rff_filter::AudioFilterChain::parse(output.audio_filters.as_deref().unwrap_or(""))?
            } else {
                rff_filter::AudioFilterChain::default()
            };

            // `-ac`: validate up front — only mono/stereo mixing exists.
            let target_channels = match output.audio_channels {
                Some(c) if is_audio => {
                    if !(1..=2).contains(&c) {
                        return Err(Error::unsupported(format!(
                            "-ac {c}: only 1 or 2 channels supported"
                        )));
                    }
                    c
                }
                _ => 0,
            };

            // Output sample rate: `-ar` / `aresample=` wins, else the input
            // rate; either way the encoder's accepted-rate list has the last
            // word (nearest accepted).
            let mut target_rate = 0;
            let mut out_rate = stream.sample_rate;
            if is_audio && stream.sample_rate > 0 {
                let desired = output
                    .audio_rate
                    .or(audio_chain.resample_target())
                    .unwrap_or(stream.sample_rate);
                let desired = match encoder.accepted_sample_rates() {
                    Some(rates) if !rates.contains(&desired) => nearest_rate(&rates, desired),
                    _ => desired,
                };
                if desired != stream.sample_rate {
                    target_rate = desired;
                }
                out_rate = desired;
            }

            // Trim window and the tick shift that re-zeroes the output timeline.
            let trim = Trim::from_spec(output);
            let tb = stream.time_base;
            let shift_ticks = trim
                .map(|t| (t.start * tb.den as f64 / tb.num.max(1) as f64).round() as i64)
                .unwrap_or(0);

            // `-r`: CFR stage; the output stream ticks in 1/fps units.
            let fps = match output.frame_rate {
                Some((num, den)) if is_video => Some(FpsConv::new(num, den)),
                _ => None,
            };

            let mut accepted_formats = encoder.accepted_pixel_formats();
            let requested_format = if is_video { output.pixel_format } else { None };

            let mut os = Stream::new(out_index, target.codec);
            os.media_type = stream.media_type;
            os.time_base = stream.time_base;
            os.width = out_w;
            os.height = out_h;
            os.pixel_format = stream.pixel_format;
            // Raw output declares its pixel format in the container header,
            // which the muxer writes before a single frame has been seen. So the
            // format cannot be discovered later — pin it now and force frames to
            // match, or the header ends up describing data it does not have.
            // (A 4:4:4 JPEG decoded straight to planes under a `C420mpeg2`
            // header is silent corruption, not a mislabel.)
            if target.codec == CodecId::RawVideo && stream.media_type == MediaType::Video {
                let pinned = requested_format
                    .or(os.pixel_format)
                    .unwrap_or(PixelFormat::Yuv420p);
                os.pixel_format = Some(pinned);
                accepted_formats = Some(vec![pinned]);
            }
            // Colour range: a `format=` filter that converts to Y'CbCr decides
            // it; otherwise it rides through from the input. Decoders whose
            // native output is RGB (JPEG, PNG, GIF, WebP) are full-range by
            // definition, so an untagged input from one of those is Full, not
            // "unknown" — leaving it unspecified makes the muxer label the
            // samples limited-range and every reader then rescales them.
            // A colour conversion in the chain decides the output range;
            // otherwise it is whatever we reconciled the source to above.
            os.color_range = filters.output_color_range().unwrap_or(source_range);
            let mut pixels = PixelConform::new(accepted_formats, requested_format, target.codec);
            // The automatic conversion is the colour conversion when nothing in
            // the chain already is one: label the stream with the range it
            // will produce (limited for an RGB source into a Y'CbCr video
            // codec), and commit the pixel format the encoder will really see.
            // Image demuxers rarely declare a pixel format, but their decoders
            // are known to emit packed RGB(A): that is enough to know an RGB
            // → Y'CbCr conversion is coming.
            let src_format = stream
                .pixel_format
                .or_else(|| decodes_to_rgb(stream.codec_id).then_some(PixelFormat::Rgb24));
            if is_video && filters.output_color_range().is_none() {
                if let Some(src) = src_format {
                    if let Ok((fmt, _)) = pixels.negotiate(src) {
                        if pixels.rgb_to_limited && src.is_rgb() && !fmt.is_rgb() {
                            os.color_range = ColorRange::Limited;
                        }
                        if stream.pixel_format.is_some() && target.codec != CodecId::RawVideo {
                            os.pixel_format = Some(fmt);
                        }
                    }
                }
            }
            // Colour range at the encoder (#213), FFmpeg's way: the encoder
            // signals the range of its frames in the bitstream (AV1 / VP9
            // `color_range`, H.264 `video_full_range_flag`), or, when it
            // cannot signal full range, the frames are converted to limited.
            // Either way the samples, the bitstream and the container label
            // agree; before, full-range Y'CbCr went out under the bitstream's
            // default limited label (28 dB through dav1d instead of 40).
            let mut range_fix = None;
            if is_video {
                let range = match os.color_range {
                    ColorRange::Full => ColorRange::Full,
                    _ => ColorRange::Limited,
                };
                if !encoder.set_color_range(range) && range == ColorRange::Full {
                    range_fix = Some(FilterChain::parse("setrange=limited")?);
                    os.color_range = ColorRange::Limited;
                    encoder.set_color_range(ColorRange::Limited);
                }
                pixels.out_range = Some(os.color_range);
            }
            os.sample_rate = out_rate;
            os.channels = if target_channels > 0 {
                target_channels
            } else {
                stream.channels
            };
            // A CFR conversion re-times the stream: pts become slot indices.
            if let Some((num, den)) = output.frame_rate {
                if is_video {
                    os.time_base = rff_core::Rational::new(den as i32, num as i32);
                }
            }
            // A format pinned by the output codec NAME (`-c:a pcm_s16le`) wins:
            // it is an explicit request, and the muxer writes it into the
            // container header before any frame is seen. Otherwise compressed
            // decoders (AAC/Opus/Vorbis/FLAC/MP3) emit f32, so default to that
            // when the input doesn't declare a format.
            let target_sample_format = target.sample_format;
            os.sample_format = target_sample_format
                .or(stream.sample_format)
                .or(Some(SampleFormat::F32));
            // The muxer writes os.sample_format into the container header
            // BEFORE any frame is seen, so every frame must be conformed to
            // that committed format — decoders may legitimately emit either
            // layout (the FLAC decoder emits native s16 for 16-bit streams).
            let target_sample_format = target_sample_format.or(os.sample_format);
            // Audio encoders timestamp packets in per-channel samples, so the
            // output stream's time base is 1/sample_rate.
            if stream.media_type == MediaType::Audio && out_rate > 0 {
                os.time_base = rff_core::Rational::new(1, out_rate as i32);
            }
            Ok((
                StreamOp::Transcode(Box::new(TranscodeOp {
                    decoder,
                    encoder,
                    filters,
                    overlay: None,
                    in_time_base: stream.time_base,
                    is_video,
                    trim,
                    shift_ticks,
                    audio_clock_samples: 0,
                    fps,
                    audio_chain,
                    target_channels,
                    target_rate,
                    target_sample_format,
                    resampler: None,
                    pixels,
                    range_fix,
                    source_range,
                    warnings: Vec::new(),
                    out_index,
                    max_video_frames: output.max_video_frames,
                    video_frames_sent: 0,
                    pending_pts: std::collections::VecDeque::new(),
                })),
                os,
            ))
        }
        // Stream copy: carry the same codec/packets through unchanged (the trim
        // window still applies, cutting video on keyframes).
        None => {
            let mut os = stream.clone();
            os.index = out_index;
            // `-c:s`: text subtitles share one packet contract, so choosing a
            // subtitle codec relabels the stream (SubRip ↔ WebVTT) in place.
            if stream.media_type == MediaType::Subtitle {
                if let Some(target) = output.subtitle_codec {
                    if target.media_type() != MediaType::Subtitle {
                        return Err(Error::unsupported(format!(
                            "-c:s: `{}` is not a subtitle codec",
                            target.name()
                        )));
                    }
                    os.codec_id = target;
                }
            }
            let trim = Trim::from_spec(output);
            let tb = stream.time_base;
            let to_ticks = |s: f64| (s * tb.den as f64 / tb.num.max(1) as f64).round() as i64;
            Ok((
                StreamOp::Copy(CopyOp {
                    out_index,
                    is_video: stream.media_type == MediaType::Video,
                    start_ticks: trim.map(|t| to_ticks(t.start)).unwrap_or(0),
                    end_ticks: trim.and_then(|t| t.end).map(to_ticks),
                    trimming: trim.is_some(),
                    started: false,
                }),
                os,
            ))
        }
    }
}

/// Decode the first video frame of the overlay input and convert it to 4:2:0,
/// ready to composite onto the base's YUV frames.
fn decode_overlay_frame(
    engine: &Engine,
    demuxer: &mut dyn rff_format::Demuxer,
    streams: &[Stream],
) -> Result<VideoFrame> {
    let vidx = streams
        .iter()
        .position(|s| s.media_type == MediaType::Video)
        .ok_or_else(|| {
            Error::Option("filter_complex overlay: overlay input has no video".into())
        })?;
    let mut decoder = engine.codecs.find_decoder(streams[vidx].codec_id)?;
    decoder.configure(&codec_params(&streams[vidx]))?;
    let mut to_yuv = FilterChain::parse("format=yuv420p")?;
    let mut got_eof = false;
    loop {
        let frame = match demuxer.read_packet() {
            Ok(pkt) if pkt.stream_index != vidx => continue,
            Ok(pkt) => {
                decoder.send_packet(&pkt)?;
                decoder.receive_frame()
            }
            Err(Error::Eof) if !got_eof => {
                got_eof = true;
                decoder.flush();
                decoder.receive_frame()
            }
            Err(e) => return Err(e),
        };
        match frame {
            Ok(Frame::Video(v)) => return to_yuv.apply(v),
            Ok(_) => continue,
            Err(Error::Again) if !got_eof => continue,
            Err(Error::Again) | Err(Error::Eof) => {
                return Err(Error::Option(
                    "filter_complex overlay: no decodable frame in the overlay input".into(),
                ))
            }
            Err(e) => return Err(e),
        }
    }
}

/// Build the decoder configuration from a demuxed input stream.
fn codec_params(s: &Stream) -> CodecParams {
    CodecParams {
        codec_id: s.codec_id,
        width: s.width,
        height: s.height,
        pixel_format: s.pixel_format,
        sample_rate: s.sample_rate,
        channels: s.channels,
        sample_format: s.sample_format,
        extradata: s.extradata.clone(),
    }
}

/// Route one demuxed packet through its stream's plan.
fn process_packet(
    packet: Packet,
    ops: &mut [StreamOp],
    muxer: &mut dyn Muxer,
    report: &mut TranscodeReport,
) -> Result<()> {
    let Some(op) = ops.get_mut(packet.stream_index) else {
        return Ok(()); // packet for a stream we didn't plan — drop it
    };
    match op {
        StreamOp::Skip => Ok(()),
        StreamOp::Copy(copy) => {
            if let Some(packet) = copy.process(packet) {
                muxer.write_packet(&packet)?;
                report.packets_written += 1;
            }
            Ok(())
        }
        StreamOp::Transcode(op) => {
            phases::time(&phases::DECODE, || op.decoder.send_packet(&packet))?;
            loop {
                match phases::time(&phases::DECODE, || op.decoder.receive_frame()) {
                    Ok(frame) => op.handle_frame(frame, muxer, report)?,
                    Err(Error::Again) | Err(Error::Eof) => break,
                    Err(e) => return Err(e),
                }
            }
            Ok(())
        }
    }
}

/// At end of input, flush each transcoded stream's decoder, filter state, and
/// encoder, writing out anything still buffered.
fn flush_streams(
    ops: &mut [StreamOp],
    muxer: &mut dyn Muxer,
    report: &mut TranscodeReport,
) -> Result<()> {
    for op in ops.iter_mut() {
        if let StreamOp::Transcode(op) = op {
            op.finish(muxer, report)?;
        }
    }
    Ok(())
}

/// Open an input and decide its container format — local file (seekable) or
/// `http://` URL. Delegates to the shared [`crate::probe`] opener so ffmpeg and
/// ffprobe resolve inputs identically.
fn open_input(engine: &Engine, input: &InputSpec) -> Result<(String, crate::probe::Source)> {
    let path = input
        .path
        .to_str()
        .ok_or_else(|| Error::Option("input path is not valid UTF-8".into()))?;
    crate::probe::open_source(engine, path, input.format.as_deref())
}

/// Decide which container to mux an output as: explicit `-f`, else by
/// extension. An `rtmp://` target implies FLV — that is the payload RTMP
/// carries (matching FFmpeg's default for rtmp outputs).
fn resolve_output_format(engine: &Engine, output: &OutputSpec) -> Result<String> {
    if let Some(forced) = &output.format {
        return Ok(forced.clone());
    }
    if output.path.to_str().is_some_and(rff_io::is_rtmp) {
        return Ok("flv".to_string());
    }
    let ext = output
        .path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or_default();
    engine
        .formats
        .by_extension(ext)
        .map(|f| f.name.to_string())
        .ok_or_else(|| {
            Error::MuxerNotFound(format!(
                "{} (no format for this extension — pass -f)",
                output.path.display()
            ))
        })
}

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

    fn f32_af(samples: &[f32]) -> Frame {
        f32_frame(samples.to_vec(), 44_100, 1, Some(0))
    }

    /// `-c:a pcm_s16le` used to be silently ignored on decode: the codec NAME
    /// carries the format but `CodecId` does not, so raw output kept whatever
    /// the decoder emitted (f32), writing double the bytes under an s16 request.
    #[test]
    fn pinned_format_converts_f32_to_s16() {
        let src = [0.0f32, 0.5, -0.5, 1.0, -1.0];
        let out = conform_sample_format(Some(SampleFormat::S16), f32_af(&src)).unwrap();
        let Frame::Audio(af) = out else {
            unreachable!()
        };
        assert_eq!(af.format, SampleFormat::S16);
        assert_eq!(af.planes[0].len(), src.len() * 2, "s16 is 2 bytes/sample");
        let got: Vec<i16> = af.planes[0]
            .chunks_exact(2)
            .map(|b| i16::from_le_bytes([b[0], b[1]]))
            .collect();
        // Round-to-nearest, and full scale must CLAMP rather than wrap: 1.0 maps
        // to 32767, not to -32768 via overflow.
        assert_eq!(got, vec![0, 16384, -16384, 32767, -32768]);
    }

    /// No pin, or a frame already in the target format, must pass through
    /// untouched — the conversion is not allowed to cost anything when idle.
    #[test]
    fn unpinned_or_matching_format_is_a_passthrough() {
        let src = [0.25f32, -0.25];
        let Frame::Audio(a) = conform_sample_format(None, f32_af(&src)).unwrap() else {
            unreachable!()
        };
        assert_eq!(a.format, SampleFormat::F32);
        let Frame::Audio(b) = conform_sample_format(Some(SampleFormat::F32), f32_af(&src)).unwrap()
        else {
            unreachable!()
        };
        assert_eq!(b.format, SampleFormat::F32);
        assert_eq!(b.planes[0], a.planes[0]);
    }

    /// The codec name is the only place the format lives for raw PCM.
    #[test]
    fn codec_name_pins_the_sample_format() {
        assert_eq!(
            CodecId::sample_format_from_name("pcm_s16le"),
            Some(SampleFormat::S16)
        );
        assert_eq!(
            CodecId::sample_format_from_name("pcm_f32le"),
            Some(SampleFormat::F32)
        );
        // Bare `pcm` pins nothing, and compressed codecs never do.
        assert_eq!(CodecId::sample_format_from_name("pcm"), None);
        assert_eq!(CodecId::sample_format_from_name("mp3"), None);
    }
}

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

    const AVIF: &[PixelFormat] = &[Yuv420p, Yuv444p, Yuv422p, Yuv420p10, Yuv444p10, Yuv422p10];

    fn pick(
        src: PixelFormat,
        accepted: Option<&[PixelFormat]>,
        requested: Option<PixelFormat>,
    ) -> (PixelFormat, Vec<String>) {
        negotiate_pixel_format(src, accepted, requested, CodecId::Avif).unwrap()
    }

    #[test]
    fn rgb_into_a_yuv_encoder_takes_its_first_8_bit_format() {
        assert_eq!(pick(Rgb24, Some(AVIF), None), (Yuv420p, vec![]));
        assert_eq!(pick(Rgb24, Some(&[Yuv420p]), None), (Yuv420p, vec![]));
    }

    #[test]
    fn accepted_sources_pass_through() {
        for f in AVIF {
            assert_eq!(pick(*f, Some(AVIF), None), (*f, vec![]));
        }
        assert_eq!(pick(Rgba, None, None), (Rgba, vec![]));
    }

    #[test]
    fn high_bit_depth_is_kept_when_the_encoder_takes_it() {
        assert_eq!(pick(Yuv420p12, Some(AVIF), None).0, Yuv420p10);
        assert_eq!(pick(Yuv422p12, Some(AVIF), None).0, Yuv422p10);
        // ... and narrowed when it does not.
        assert_eq!(pick(Yuv420p10, Some(&[Yuv420p]), None).0, Yuv420p);
    }

    #[test]
    fn pix_fmt_wins_when_accepted() {
        assert_eq!(pick(Rgb24, Some(AVIF), Some(Yuv444p)), (Yuv444p, vec![]));
        assert_eq!(
            pick(Rgb24, Some(AVIF), Some(Yuv420p10)),
            (Yuv420p10, vec![])
        );
        // An encoder that takes anything takes the request too.
        assert_eq!(pick(Rgb24, None, Some(Yuv422p)), (Yuv422p, vec![]));
        // Even when the source is already acceptable as it is.
        assert_eq!(pick(Yuv420p, Some(AVIF), Some(Yuv420p10)).0, Yuv420p10);
    }

    #[test]
    fn unaccepted_pix_fmt_falls_back_with_ffmpegs_warning() {
        let (fmt, warnings) = pick(Rgb24, Some(AVIF), Some(Rgb24));
        assert_eq!(fmt, Yuv420p);
        assert_eq!(
            warnings,
            vec!["Incompatible pixel format 'rgb24' for codec 'avif', auto-selecting format 'yuv420p'"]
        );
        // A deep request falls back to a deep format.
        let (fmt, warnings) = pick(Rgb24, Some(AVIF), Some(Yuv420p12));
        assert_eq!(fmt, Yuv420p10);
        assert_eq!(warnings.len(), 1);
    }

    #[test]
    fn dropped_alpha_is_reported() {
        let (fmt, warnings) = pick(Rgba, Some(AVIF), None);
        assert_eq!(fmt, Yuv420p);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("alpha"), "{warnings:?}");
        // Kept alpha is not.
        assert_eq!(pick(Rgba, Some(&[Rgb24, Rgba]), None), (Rgba, vec![]));
    }

    /// The image encoders' choices are what they were before negotiation
    /// grew depth awareness: first convertible accepted format.
    #[test]
    fn existing_image_encoder_choices_are_unchanged() {
        let jpeg = &[Yuv420p, Yuv422p, Yuv444p, Rgb24, Rgba];
        for src in [Yuv420p10, Yuv422p10, Yuv444p10, Yuv420p12, Yuv444p12] {
            assert_eq!(pick(src, Some(jpeg), None).0, Yuv420p, "{}", src.name());
        }
        let png = &[Rgb24, Rgba];
        for src in [Yuv420p, Yuv422p, Yuv444p, Yuv420p10, Yuv444p12] {
            assert_eq!(pick(src, Some(png), None).0, Rgb24, "{}", src.name());
        }
    }

    #[test]
    fn impossible_conversions_are_errors() {
        // 8-bit 4:2:0 cannot be upsampled to 4:4:4 by the pipeline.
        assert!(negotiate_pixel_format(Yuv420p, Some(&[Yuv444p]), None, CodecId::Avif).is_err());
        assert!(negotiate_pixel_format(Yuv420p, Some(AVIF), Some(Yuv444p), CodecId::Avif).is_err());
    }

    /// The converter an RGB source gets in front of a Y'CbCr video encoder is
    /// BT.601 limited range (FFmpeg's default); in front of raw video it keeps
    /// following the source, as before.
    #[test]
    fn rgb_to_yuv_range_depends_on_the_codec() {
        let rgb = VideoFrame {
            width: 2,
            height: 2,
            format: Rgb24,
            planes: vec![vec![0u8; 12]],
            strides: vec![6],
            pts: None,
        };
        let luma_of_black = |codec| {
            let mut pc = PixelConform::new(Some(vec![Yuv420p]), None, codec);
            let mut w = Vec::new();
            match pc
                .conform(ColorRange::Full, Frame::Video(rgb.clone()), &mut w)
                .unwrap()
            {
                Frame::Video(v) => v.planes[0][0],
                Frame::Audio(_) => unreachable!(),
            }
        };
        assert_eq!(luma_of_black(CodecId::Avif), 16);
        assert_eq!(luma_of_black(CodecId::H264), 16);
        assert_eq!(luma_of_black(CodecId::RawVideo), 0);
    }

    /// Once the output range is committed, an RGB frame converts to it — a
    /// source only found to be RGB at the first frame (a progressive JPEG,
    /// committed Full like every JPEG) must not be converted to limited under
    /// a full-range label (#213).
    #[test]
    fn rgb_to_yuv_follows_the_committed_range() {
        let rgb = VideoFrame {
            width: 2,
            height: 2,
            format: Rgb24,
            planes: vec![vec![0u8; 12]],
            strides: vec![6],
            pts: None,
        };
        for (range, black) in [(ColorRange::Full, 0), (ColorRange::Limited, 16)] {
            let mut pc = PixelConform::new(Some(vec![Yuv420p]), None, CodecId::Avif);
            pc.out_range = Some(range);
            let mut w = Vec::new();
            match pc
                .conform(ColorRange::Full, Frame::Video(rgb.clone()), &mut w)
                .unwrap()
            {
                Frame::Video(v) => assert_eq!(v.planes[0][0], black, "{range:?}"),
                Frame::Audio(_) => unreachable!(),
            }
        }
    }
}