ez-ffmpeg 0.16.0

A safe and ergonomic Rust interface for FFmpeg integration, designed for ease of use.
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
//! Classification corpus: real-world commands swept through the full public
//! pipeline, each pinned to its EXACT disposition.
//!
//! Three dispositions exist — and only three:
//! - `runs_verified`: classification passes and the shape is golden-backed;
//!   `from_cli` proceeds past every gate (proven here by reaching the
//!   pipeline-build stage, which fails on the deliberately nonexistent
//!   fixture path — a `CliError::Build` is the success signal on a verified
//!   linked profile, the typed `UnverifiedRuntimeProfile` on any other; real
//!   execution is `cli::golden_tests`' job);
//! - `emit_only`: parses completely, but no golden covers the shape;
//!   `from_cli` refuses with `NotVerified`, the emitter labels its output
//!   "unverified scaffolding";
//! - `rejected`: some token fails to classify; run AND emit fail with the
//!   same typed, token-anchored diagnostic.
//!
//! A common command silently doing the wrong thing is a release-blocking
//! bug; a common command clearly rejected with the right reason is CORRECT
//! behavior. This file is the executable form of that rule.

use super::error::CliError;
use super::{emit_rust_code, from_cli};

/// The command must pass classification, shape verification and the profile
/// gate. It then fails at pipeline build (nonexistent input) — precisely the
/// proof that no CLI-layer gate stopped it.
#[track_caller]
fn runs_verified(cmd: &str) {
    // Profile-aware: on a verified linked profile the command passes every
    // CLI gate and fails at pipeline build (nonexistent fixture); on a
    // non-verified profile the typed profile failure is the CORRECT runtime
    // behavior. Emission is profile-independent either way.
    match from_cli(cmd) {
        Ok(_) => panic!("corpus fixtures must not exist, yet {cmd:?} built"),
        Err(CliError::Build(_)) if super::linked_profile_verified() => {}
        Err(CliError::UnverifiedRuntimeProfile { .. }) if !super::linked_profile_verified() => {}
        Err(other) => panic!("{cmd:?} should reach the build stage (or the typed profile failure on a non-verified line), got: {other}"),
    }
    let code = emit_rust_code(cmd).unwrap();
    assert!(
        code.contains("// status: verified shape"),
        "verified command must emit verified code: {cmd:?}"
    );
}

#[track_caller]
fn emit_only(cmd: &str) {
    match from_cli(cmd) {
        Ok(_) => panic!("{cmd:?} must not execute"),
        Err(CliError::NotVerified { .. }) => {}
        Err(other) => panic!("{cmd:?} should be NotVerified, got: {other}"),
    }
    let code = emit_rust_code(cmd).unwrap();
    assert!(
        code.contains("UNVERIFIED SCAFFOLDING"),
        "emit-only command must carry the scaffolding banner: {cmd:?}"
    );
}

/// `expect` names the variant; `fragment` must appear in the Display output
/// (the reason a user actually reads).
#[track_caller]
fn rejected(cmd: &str, expect: &str, fragment: &str) {
    let err = match from_cli(cmd) {
        Ok(_) => panic!("{cmd:?} must be rejected"),
        Err(err) => err,
    };
    let variant = match &err {
        CliError::Tokenize { .. } => "Tokenize",
        CliError::UnsupportedOption { .. } => "UnsupportedOption",
        CliError::UnsupportedValue { .. } => "UnsupportedValue",
        CliError::UnsupportedLayout { .. } => "UnsupportedLayout",
        CliError::ConflictingOptions { .. } => "ConflictingOptions",
        CliError::MissingOverwriteFlag => "MissingOverwriteFlag",
        CliError::NotVerified { .. } => "NotVerified",
        CliError::UnmatchedShape { .. } => "UnmatchedShape",
        CliError::AmbiguousFilterSource { .. } => "AmbiguousFilterSource",
        CliError::UnverifiedRuntimeProfile { .. } => "UnverifiedRuntimeProfile",
        CliError::Build(_) => "Build",
    };
    assert_eq!(
        variant, expect,
        "{cmd:?} rejected with the wrong variant: {err}"
    );
    let display = err.to_string();
    assert!(
        display.contains(fragment),
        "{cmd:?}: diagnostic should mention {fragment:?}, got:\n{display}"
    );
    // Emit must fail identically — rejection is a property of the command,
    // not of the consumer.
    let emit_err = emit_rust_code(cmd).unwrap_err();
    assert_eq!(err.to_string(), emit_err.to_string());
}

// ---------------------------------------------------------------------------
// The six verified commands — the exact spellings of the goldens.
// ---------------------------------------------------------------------------

#[test]
fn corpus_v1_transcode() {
    runs_verified(
        "ffmpeg -i no_such_fixture.mkv -c:v libx264 -crf 23 -preset fast -c:a aac -y out.mp4",
    );
}

#[test]
fn corpus_v2_clip() {
    runs_verified(
        "ffmpeg -ss 10 -i no_such_fixture.mp4 -t 20 -c:v libx264 -crf 23 -c:a aac -y clip.mp4",
    );
}

#[test]
fn corpus_v3_audio_extract() {
    runs_verified("ffmpeg -i no_such_fixture.mp4 -vn -c:a aac -b:a 192k -y out.m4a");
}

#[test]
fn corpus_v4_thumbnail() {
    runs_verified("ffmpeg -ss 5 -i no_such_fixture.mp4 -an -c:v mjpeg -frames:v 1 -y thumb.jpg");
}

#[test]
fn corpus_v5_scale() {
    runs_verified(
        "ffmpeg -i no_such_fixture.mp4 -vf scale=1280:-2 -c:v libx264 -crf 23 -preset fast -c:a aac -y scaled.mp4",
    );
}

#[test]
fn corpus_v6_hls() {
    runs_verified(
        "ffmpeg -i no_such_fixture.mp4 -c:v libx264 -crf 23 -c:a aac -f hls -hls_time 6 -hls_playlist_type vod -hls_list_size 0 -hls_segment_filename 'seg_%03d.ts' -y out.m3u8",
    );
}

#[test]
fn corpus_verified_with_trailing_y_and_noops() {
    runs_verified(
        "ffmpeg -hide_banner -loglevel error -stats -i no_such_fixture.mkv -c:v libx264 -crf 23 -preset fast -c:a aac out.mp4 -y",
    );
}

// ---------------------------------------------------------------------------
// Cookbook recipes (the 15-entry CLI-to-API article), as pasted.
// ---------------------------------------------------------------------------

#[test]
fn corpus_cookbook_1_transcode_without_y() {
    // The article's spelling has no -y: the CLI would prompt; we reject.
    rejected(
        "ffmpeg -i input.mkv -c:v libx264 -crf 23 -preset fast -c:a aac output.mp4",
        "MissingOverwriteFlag",
        "requires an explicit -y",
    );
}

#[test]
fn corpus_cookbook_2_input_trim() {
    // Input-side -ss AND -t: parses, but no golden covers the shape.
    emit_only("ffmpeg -ss 10 -t 5 -i input.mp4 -y clip.mp4");
}

#[test]
fn corpus_cookbook_3_unsplit_c_copy() {
    rejected(
        "ffmpeg -i input.mp4 -c copy -movflags +faststart -y faststart.mp4",
        "UnsupportedOption",
        "did you mean `-c:v` and/or `-c:a`?",
    );
}

#[test]
fn corpus_cookbook_3_respelled_faststart_remux() {
    // The manifest-admitted spelling: explicit per-media copy. Emit-only —
    // faststart is not one of the six verified shapes, so the command is
    // accepted by the grammar but has no golden.
    emit_only("ffmpeg -i input.mp4 -c:v copy -c:a copy -movflags +faststart -y faststart.mp4");
}

#[test]
fn corpus_cookbook_4_scale_with_audio_copy() {
    emit_only("ffmpeg -i input.mp4 -vf scale=1280:-2 -c:a copy -y resized.mp4");
}

#[test]
fn corpus_cookbook_5_thumbnail_recipe_shape() {
    // The article's thumbnail spelling (scale + -frames:v, no -an/-c:v):
    // parses, not the golden V4 shape.
    emit_only("ffmpeg -ss 3 -i input.mp4 -frames:v 1 -vf scale=320:-2 -y thumb.jpg");
}

#[test]
fn corpus_cookbook_6_fps_extraction() {
    rejected(
        "ffmpeg -i input.mp4 -vf fps=1 -y frame_%04d.jpg",
        "UnsupportedValue",
        "single simple scale filter",
    );
}

#[test]
fn corpus_cookbook_7_overlay_multi_input() {
    rejected(
        "ffmpeg -i input.mp4 -i logo.png -filter_complex overlay=10:10 -y watermarked.mp4",
        "UnsupportedLayout",
        "single-input",
    );
}

#[test]
fn corpus_cookbook_8_audio_copy_extract() {
    emit_only("ffmpeg -i input.mp4 -vn -c:a copy -y audio.aac");
}

#[test]
fn corpus_cookbook_8b_segment_muxer() {
    rejected(
        "ffmpeg -i input.mp4 -f segment -segment_time 10 -y chunk_%03d.wav",
        "UnsupportedOption",
        "segment muxer is planned for a future release",
    );
}

#[test]
fn corpus_cookbook_9_whisper_pcm() {
    emit_only("ffmpeg -i input.mp4 -ar 16000 -ac 1 -c:a pcm_s16le -y audio.wav");
}

#[test]
fn corpus_cookbook_10_concat_filter() {
    rejected(
        "ffmpeg -i part1.mp4 -i part2.mp4 -i part3.mp4 -filter_complex concat=n=3:v=1:a=1 -y joined.mp4",
        "UnsupportedLayout",
        "single-input",
    );
}

#[test]
fn corpus_cookbook_11_gif_palette() {
    rejected(
        "ffmpeg -i input.mp4 -vf 'fps=12,scale=480:-1:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse' -y output.gif",
        "UnsupportedValue",
        "single simple scale filter",
    );
}

#[test]
fn corpus_cookbook_12_hls_without_the_full_option_set() {
    // The article's HLS spelling lacks -crf/-hls_list_size/-hls_segment_filename:
    // parses, but only the exact V6 set is golden-backed.
    emit_only(
        "ffmpeg -i input.mp4 -c:v libx264 -c:a aac -f hls -hls_time 6 -hls_playlist_type vod -y playlist.m3u8",
    );
}

#[test]
fn corpus_cookbook_13_rtmp_readrate() {
    rejected(
        "ffmpeg -re -i input.mp4 -c:v libx264 -c:a aac -f flv -y rtmp://localhost/live/stream",
        "UnsupportedOption",
        "readrate streaming is planned for a future release",
    );
}

#[test]
fn corpus_cookbook_14_pasted_ffprobe_line() {
    // An ffprobe line is not an ffmpeg command; the leading token is not
    // stripped and lands in output position before any -i.
    rejected(
        "ffprobe -v error -show_format -show_streams input.mp4",
        "UnsupportedLayout",
        "before any -i input",
    );
}

#[test]
fn corpus_cookbook_15_two_pass() {
    rejected(
        "ffmpeg -y -i input.mp4 -c:v libx264 -b:v 2600k -pass 1 -an -f null /dev/null",
        "UnsupportedOption",
        "two-pass encoding",
    );
}

// ---------------------------------------------------------------------------
// Common patterns the evaluation catalogs (typed rejections).
// ---------------------------------------------------------------------------

#[test]
fn corpus_subtitle_burn_in() {
    rejected(
        "ffmpeg -i input.mp4 -vf subtitles=subs.srt -y out.mp4",
        "UnsupportedValue",
        "single simple scale filter",
    );
}

#[test]
fn corpus_shortest() {
    rejected(
        "ffmpeg -i input.mp4 -shortest -y out.mp4",
        "UnsupportedOption",
        "Output::set_shortest",
    );
}

#[test]
fn corpus_loudnorm_audio_filter() {
    rejected(
        "ffmpeg -i input.mp4 -af loudnorm -y out.mp4",
        "UnsupportedOption",
        "per-output audio filter API",
    );
}

#[test]
fn corpus_map_metadata() {
    rejected(
        "ffmpeg -i input.mp4 -map_metadata 0 -y out.mp4",
        "UnsupportedOption",
        "metadata mapping is planned for a future release",
    );
}

#[test]
fn corpus_fps_mode_and_vsync_all_forms() {
    rejected(
        "ffmpeg -i input.mp4 -fps_mode cfr -y out.mp4",
        "UnsupportedOption",
        "permanently excluded",
    );
    rejected(
        "ffmpeg -i input.mp4 -vsync 0 -y out.mp4",
        "UnsupportedOption",
        "permanently excluded",
    );
    rejected(
        "ffmpeg -i input.mp4 -fps_mode:v cfr -y out.mp4",
        "UnsupportedOption",
        "not in the CLI-compat subset",
    );
}

#[test]
fn corpus_hardware_accel() {
    rejected(
        "ffmpeg -hwaccel cuda -i input.mp4 -y out.mp4",
        "UnsupportedOption",
        "hardware acceleration is planned for a future release",
    );
}

#[test]
fn corpus_frame_rate_and_size() {
    rejected(
        "ffmpeg -i input.mp4 -r 30 -y out.mp4",
        "UnsupportedOption",
        "not in the current supported subset",
    );
    rejected(
        "ffmpeg -i input.mp4 -s 1280x720 -y out.mp4",
        "UnsupportedOption",
        "did you mean `-vf scale=W:H`?",
    );
}

#[test]
fn corpus_quality_scale_and_unsplit_bitrate() {
    rejected(
        "ffmpeg -i input.mp4 -q:v 2 -y out.mp4",
        "UnsupportedOption",
        "fixed-quality",
    );
    rejected(
        "ffmpeg -i input.mp4 -b 2M -y out.mp4",
        "UnsupportedOption",
        "did you mean `-b:v` or `-b:a`?",
    );
}

#[test]
fn corpus_threads_and_progress() {
    rejected(
        "ffmpeg -i in.mp4 -threads 4 -y out.mp4",
        "UnsupportedOption",
        "auto threading",
    );
    rejected(
        "ffmpeg -i in.mp4 -progress p.txt -y out.mp4",
        "UnsupportedOption",
        "FfmpegScheduler::progress_handle",
    );
}

#[test]
fn corpus_codec_tags_and_never_overwrite() {
    rejected(
        "ffmpeg -i in.mp4 -tag:v hvc1 -y out.mp4",
        "UnsupportedOption",
        "documented gap",
    );
    rejected(
        "ffmpeg -n -i in.mp4 -y out.mp4",
        "UnsupportedOption",
        "never-overwrite",
    );
}

#[test]
fn corpus_legacy_aliases_get_hints() {
    rejected(
        "ffmpeg -i in.mp4 -vcodec libx264 -y out.mp4",
        "UnsupportedOption",
        "did you mean `-c:v`?",
    );
    rejected(
        "ffmpeg -i in.mp4 -acodec aac -y out.mp4",
        "UnsupportedOption",
        "did you mean `-c:a`?",
    );
    rejected(
        "ffmpeg -i in.mp4 -vframes 1 -y out.jpg",
        "UnsupportedOption",
        "did you mean `-frames:v 1`?",
    );
}

// ---------------------------------------------------------------------------
// Map grammar.
// ---------------------------------------------------------------------------

#[test]
fn corpus_map_optional_suffix() {
    // Quoted: reaches the map grammar and gets the dedicated diagnostic.
    rejected(
        "ffmpeg -i in.mp4 -map '0:a:1?' -y out.mp4",
        "UnsupportedValue",
        "fails loudly if the stream is missing",
    );
    // Unquoted: the trailing metacharacter is a glob and dies in the
    // tokenizer with the quoting hint.
    rejected(
        "ffmpeg -i in.mp4 -map 0:a:1? -y out.mp4",
        "Tokenize",
        "glob",
    );
}

#[test]
fn corpus_map_negative() {
    rejected(
        "ffmpeg -i in.mp4 -map -0:a -y out.mp4",
        "UnsupportedValue",
        "negative mappings",
    );
}

#[test]
fn corpus_map_label() {
    rejected(
        "ffmpeg -i in.mp4 -map '[vout]' -y out.mp4",
        "UnsupportedValue",
        "basic index maps",
    );
}

#[test]
fn corpus_map_second_input_index() {
    rejected(
        "ffmpeg -i in.mp4 -map 1:a -y out.mp4",
        "UnsupportedValue",
        "single-input",
    );
}

#[test]
fn corpus_map_subtitles() {
    rejected(
        "ffmpeg -i in.mkv -map 0:s -y out.mkv",
        "UnsupportedValue",
        "subtitle/data",
    );
}

#[test]
fn corpus_map_metadata_selector() {
    rejected(
        "ffmpeg -i in.mp4 -map 0:m:language:eng -y out.mp4",
        "UnsupportedValue",
        "basic index maps",
    );
}

#[test]
fn corpus_basic_maps_parse_in_filterless_commands() {
    emit_only("ffmpeg -i in.mp4 -map 0:v:0 -map 0:a:0 -c:v libx264 -c:a aac -y out.mp4");
}

#[test]
fn corpus_media_qualified_copy_maps_parse() {
    emit_only("ffmpeg -i in.mp4 -map 0:a:0 -c:a copy -y audio.m4a");
}

#[test]
fn corpus_bare_map_with_copy_is_untypeable() {
    rejected(
        "ffmpeg -i in.mp4 -map 0 -c:v copy -c:a aac -y out.mp4",
        "ConflictingOptions",
        "media-qualified maps",
    );
}

#[test]
fn corpus_map_against_disabled_stream() {
    rejected(
        "ffmpeg -i in.mp4 -map 0:a -an -c:v libx264 -y out.mp4",
        "ConflictingOptions",
        "-an removes",
    );
}

#[test]
fn corpus_map_with_filter() {
    rejected(
        "ffmpeg -i in.mp4 -map 0:v -vf scale=640:360 -c:v libx264 -y out.mp4",
        "ConflictingOptions",
        "labeled graphs",
    );
}

// ---------------------------------------------------------------------------
// Per-stream indexed variants and complex graphs.
// ---------------------------------------------------------------------------

#[test]
fn corpus_indexed_per_stream_variants() {
    rejected(
        "ffmpeg -i in.mp4 -b:v:1 500k -y out.mp4",
        "UnsupportedOption",
        "per-stream indexed",
    );
    rejected(
        "ffmpeg -i in.mp4 -crf:v:0 23 -y out.mp4",
        "UnsupportedOption",
        "per-stream indexed",
    );
    rejected(
        "ffmpeg -i in.mp4 -c:v:0 libx264 -y out.mp4",
        "UnsupportedOption",
        "per-stream indexed",
    );
}

#[test]
fn corpus_filter_complex_single_input() {
    rejected(
        "ffmpeg -i in.mp4 -filter_complex '[0:v]hue=s=0[v]' -map '[v]' -y out.mp4",
        "UnsupportedOption",
        "complex filtergraphs are planned for a future release",
    );
}

// ---------------------------------------------------------------------------
// Trim grammar: scope layering.
// ---------------------------------------------------------------------------

#[test]
fn corpus_t_and_to_same_input_scope() {
    rejected(
        "ffmpeg -ss 1 -t 5 -to 8 -i in.mp4 -y out.mp4",
        "ConflictingOptions",
        "SAME scope",
    );
}

#[test]
fn corpus_t_and_to_same_output_scope() {
    rejected(
        "ffmpeg -i in.mp4 -t 5 -to 8 -y out.mp4",
        "ConflictingOptions",
        "SAME scope",
    );
}

#[test]
fn corpus_cross_scope_trim_pair_is_legal() {
    emit_only("ffmpeg -t 5 -i in.mp4 -to 8 -y out.mp4");
}

#[test]
fn corpus_output_side_seek() {
    emit_only(
        "ffmpeg -i in.mp4 -ss 10 -t 20 -c:v libx264 -crf 23 -preset fast -c:a aac -y out.mp4",
    );
}

#[test]
fn corpus_time_value_grammar() {
    rejected(
        "ffmpeg -ss 00:01:30 -i in.mp4 -y out.mp4",
        "UnsupportedValue",
        "decimal seconds",
    );
    rejected(
        "ffmpeg -ss -5 -i in.mp4 -y out.mp4",
        "UnsupportedValue",
        "signed times",
    );
    rejected(
        "ffmpeg -i in.mp4 -t 10s -y out.mp4",
        "UnsupportedValue",
        "decimal seconds",
    );
}

// ---------------------------------------------------------------------------
// Value whitelists.
// ---------------------------------------------------------------------------

#[test]
fn corpus_crf_range() {
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -crf 99 -y out.mp4",
        "UnsupportedValue",
        "0..=51",
    );
}

#[test]
fn corpus_preset_whitelist() {
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -preset turbo -y out.mp4",
        "UnsupportedValue",
        "x264 presets",
    );
}

#[test]
fn corpus_crf_requires_x264() {
    rejected(
        "ffmpeg -i in.mp4 -c:v mpeg4 -crf 23 -y out.mp4",
        "ConflictingOptions",
        "libx264",
    );
    rejected(
        "ffmpeg -i in.mp4 -crf 23 -y out.mp4",
        "ConflictingOptions",
        "libx264",
    );
}

#[test]
fn corpus_hls_pins() {
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -crf 23 -c:a aac -f hls -hls_time 6 -hls_playlist_type event -hls_list_size 0 -hls_segment_filename s_%03d.ts -y out.m3u8",
        "UnsupportedValue",
        "vod",
    );
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -crf 23 -c:a aac -f hls -hls_time 6 -hls_playlist_type vod -hls_list_size 5 -hls_segment_filename s_%03d.ts -y out.m3u8",
        "UnsupportedValue",
        "keep every segment",
    );
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -crf 23 -c:a aac -f hls -hls_time 6 -hls_playlist_type vod -hls_list_size 0 -hls_flags delete_segments -hls_segment_filename s_%03d.ts -y out.m3u8",
        "UnsupportedOption",
        "single-rendition VOD HLS",
    );
}

#[test]
fn corpus_hls_segment_filename_swallows_next_option() {
    // An omitted segment path makes the parser take the next token as the
    // value; `-hls_flags` must fail path validation instead of being
    // accepted as a filename on an otherwise verified HLS command.
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -crf 23 -c:a aac -f hls -hls_time 6 -hls_playlist_type vod -hls_list_size 0 -hls_segment_filename -hls_flags -y out.m3u8",
        "UnsupportedValue",
        "./-name",
    );
}

#[test]
fn corpus_hls_options_without_f_hls() {
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -crf 23 -c:a aac -hls_time 6 -y out.m3u8",
        "ConflictingOptions",
        "-f hls",
    );
}

#[test]
fn corpus_movflags_exact_form_only() {
    rejected(
        "ffmpeg -i in.mp4 -c:v copy -c:a copy -movflags +faststart+frag_keyframe -y out.mp4",
        "UnsupportedValue",
        "+faststart",
    );
}

#[test]
fn corpus_frames_v_only_one() {
    rejected(
        "ffmpeg -i in.mp4 -an -c:v mjpeg -frames:v 5 -y thumbs_%02d.jpg",
        "UnsupportedValue",
        "single-frame",
    );
}

// ---------------------------------------------------------------------------
// Layout and structure.
// ---------------------------------------------------------------------------

#[test]
fn corpus_multi_output() {
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -y out1.mp4 out2.mp4",
        "UnsupportedLayout",
        "single-output",
    );
}

#[test]
fn corpus_interleaved_input_after_output() {
    rejected(
        "ffmpeg -i a.mp4 -y out.mp4 -i b.mp4",
        "UnsupportedLayout",
        "inputs-then-outputs",
    );
}

#[test]
fn corpus_output_option_after_output_path() {
    rejected(
        "ffmpeg -i in.mp4 -y out.mp4 -c:v libx264",
        "UnsupportedLayout",
        "FOLLOWING output",
    );
}

#[test]
fn corpus_output_option_in_input_position() {
    rejected(
        "ffmpeg -crf 23 -i in.mp4 -y out.mp4",
        "UnsupportedLayout",
        "before -i",
    );
}

#[test]
fn corpus_missing_files() {
    rejected("ffmpeg -y -i in.mp4", "UnsupportedLayout", "no output path");
    rejected("ffmpeg -y out.mp4", "UnsupportedLayout", "before any -i");
    rejected("ffmpeg -i in.mp4 -c:v", "UnsupportedValue", "missing value");
}

#[test]
fn corpus_stdin_stdout_pipes() {
    rejected("ffmpeg -i - -y out.mp4", "UnsupportedLayout", "stdin");
    rejected(
        "ffmpeg -i in.mp4 -f mpegts -y -",
        "UnsupportedLayout",
        "stdout",
    );
}

#[test]
fn corpus_duplicate_option() {
    rejected(
        "ffmpeg -i in.mp4 -c:v libx264 -crf 23 -crf 30 -y out.mp4",
        "UnsupportedLayout",
        "more than once",
    );
}

#[test]
fn corpus_double_dash_is_an_unknown_option() {
    rejected(
        "ffmpeg -i in.mp4 -- -y out.mp4",
        "UnsupportedOption",
        "not in the CLI-compat subset",
    );
}

#[test]
fn corpus_unknown_option_with_hint() {
    rejected(
        "ffmpeg -i in.mp4 -vff scale=1:1 -y out.mp4",
        "UnsupportedOption",
        "did you mean `-vf`?",
    );
}

#[test]
fn corpus_unknown_option_without_hint() {
    rejected(
        "ffmpeg -i in.mp4 -totally_unknown_thing 1 -y out.mp4",
        "UnsupportedOption",
        "open an issue",
    );
}

// ---------------------------------------------------------------------------
// Diagnostic anchoring: errors point at the exact offending token, with the
// scope stated truthfully.
// ---------------------------------------------------------------------------

#[test]
fn corpus_value_errors_anchor_the_value_token() {
    // tokens: 0=-i 1=in.mp4 2=-t 3=10s 4=-y 5=out.mp4 — the BAD token is #3.
    let err = from_cli("ffmpeg -i in.mp4 -t 10s -y out.mp4")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::UnsupportedValue { option, index, .. } => {
            assert_eq!(option, "-t");
            assert_eq!(*index, 3, "value errors must anchor the value token");
        }
        other => panic!("expected UnsupportedValue, got {other}"),
    }

    // tokens: ... 4=-crf 5=99 — the bad token is #5.
    let err = from_cli("ffmpeg -i in.mp4 -c:v libx264 -crf 99 -y out.mp4")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::UnsupportedValue { option, index, .. } => {
            assert_eq!(option, "-crf");
            assert_eq!(*index, 5);
        }
        other => panic!("expected UnsupportedValue, got {other}"),
    }
}

#[test]
fn corpus_conflicts_carry_both_positions() {
    // tokens: 0=-i 1=in.mp4 2=-t 3=5 4=-to 5=8 …
    let err = from_cli("ffmpeg -i in.mp4 -t 5 -to 8 -y out.mp4")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::ConflictingOptions {
            first,
            second,
            first_index,
            second_index,
            ..
        } => {
            assert_eq!((first.as_str(), second.as_str()), ("-t", "-to"));
            assert_eq!(*first_index, Some(2));
            assert_eq!(*second_index, Some(4));
        }
        other => panic!("expected ConflictingOptions, got {other}"),
    }
    let display = err.to_string();
    assert!(display.contains("(token #2)"), "display: {display}");
    assert!(display.contains("(token #4)"), "display: {display}");

    // Post-parse combination conflicts resolve their anchors from the span
    // table: tokens 2=-vf 4=-c:v 5=copy.
    let err = from_cli("ffmpeg -i in.mp4 -vf scale=640:360 -c:v copy -y out.mp4")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::ConflictingOptions {
            first_index,
            second_index,
            ..
        } => {
            assert_eq!(*first_index, Some(2));
            assert_eq!(*second_index, Some(4));
        }
        other => panic!("expected ConflictingOptions, got {other}"),
    }
}

#[test]
fn corpus_collective_conflict_names_anchor_the_earliest_occurrence() {
    // Synthetic `-c copy`: tokens 2=-map 3=0 4=-c:v 5=copy 6=-c:a 7=aac —
    // the collective anchors -c:v at token #4 (earliest of -c:v/-c:a).
    let err = from_cli("ffmpeg -i in.mp4 -map 0 -c:v copy -c:a aac -y out.mp4")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::ConflictingOptions {
            first,
            second,
            first_index,
            second_index,
            ..
        } => {
            assert_eq!((first.as_str(), second.as_str()), ("-map", "-c copy"));
            assert_eq!(*first_index, Some(2));
            assert_eq!(
                *second_index,
                Some(4),
                "collective -c must anchor its earliest member"
            );
        }
        other => panic!("expected ConflictingOptions, got {other}"),
    }

    // `-hls_*` aggregate: tokens ... -hls_playlist_type appears FIRST here,
    // so the aggregate must anchor it, not the fixed table order.
    let err = from_cli(
        "ffmpeg -i in.mp4 -c:v libx264 -crf 23 -c:a aac -hls_playlist_type vod -hls_time 6 -y out.m3u8",
    )
    .map(|_| ())
    .unwrap_err();
    match &err {
        CliError::ConflictingOptions {
            first, first_index, ..
        } => {
            assert_eq!(first, "-hls_*");
            // tokens: 0=-i 1=in.mp4 2=-c:v 3=libx264 4=-crf 5=23 6=-c:a
            // 7=aac 8=-hls_playlist_type 9=vod 10=-hls_time 11=6
            assert_eq!(
                *first_index,
                Some(8),
                "aggregate must anchor the earliest hls key"
            );
        }
        other => panic!("expected ConflictingOptions, got {other}"),
    }

    // Disabled-stream contradiction carries both sides too:
    // tokens 2=-an 3=-c:a 4=aac.
    let err = from_cli("ffmpeg -i in.mp4 -an -c:a aac -y out.mp4")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::ConflictingOptions {
            first_index,
            second_index,
            ..
        } => {
            assert_eq!(*first_index, Some(2));
            assert_eq!(*second_index, Some(3));
        }
        other => panic!("expected ConflictingOptions, got {other}"),
    }
}

#[test]
fn corpus_copy_side_anchor_is_value_aware_and_maps_anchor_their_occurrence() {
    // Command 1: tokens 2=-map 3=0 4=-c:v 5=libx264 6=-c:a 7=copy —
    // the conflicting copy is the -c:a occurrence at #6, NOT the earlier
    // non-copy -c:v at #4.
    let err = from_cli("ffmpeg -i in.mp4 -map 0 -c:v libx264 -c:a copy -y out.mp4")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::ConflictingOptions {
            first,
            second,
            first_index,
            second_index,
            ..
        } => {
            assert_eq!((first.as_str(), second.as_str()), ("-map", "-c copy"));
            assert_eq!(*first_index, Some(2));
            assert_eq!(
                *second_index,
                Some(6),
                "the anchor must be the occurrence whose value is copy"
            );
        }
        other => panic!("expected ConflictingOptions, got {other}"),
    }

    // Command 2: tokens 2=-map 3=0:v 4=-map 5=0 6=-c:a 7=copy —
    // the OFFENDING unqualified map is the second occurrence at #4; the
    // legal first map at #2 must not be blamed.
    let err = from_cli("ffmpeg -i in.mp4 -map 0:v -map 0 -c:a copy -y out.mp4")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::ConflictingOptions {
            first,
            first_index,
            second_index,
            ..
        } => {
            assert_eq!(first, "-map");
            assert_eq!(
                *first_index,
                Some(4),
                "the offending occurrence, not the first map, is the anchor"
            );
            assert_eq!(*second_index, Some(6));
        }
        other => panic!("expected ConflictingOptions, got {other}"),
    }
}

#[test]
fn corpus_unknown_after_output_names_the_following_output_scope() {
    // tokens: 0=-i 1=in.mp4 2=-y 3=out.mp4 4=-foo
    let err = from_cli("ffmpeg -i in.mp4 -y out.mp4 -foo")
        .map(|_| ())
        .unwrap_err();
    match &err {
        CliError::UnsupportedOption { index, scope, .. } => {
            assert_eq!(*index, 4);
            assert_eq!(
                scope.to_string(),
                "after output #0 (would apply to a following output)"
            );
        }
        other => panic!("expected UnsupportedOption, got {other}"),
    }
}

// ---------------------------------------------------------------------------
// Contradictions.
// ---------------------------------------------------------------------------

#[test]
fn corpus_disabled_stream_contradictions() {
    rejected(
        "ffmpeg -i in.mp4 -an -c:a aac -y out.mp4",
        "ConflictingOptions",
        "-an removes",
    );
    rejected(
        "ffmpeg -i in.mp4 -vn -crf 23 -y out.m4a",
        "ConflictingOptions",
        "-vn removes",
    );
    rejected(
        "ffmpeg -i in.mp4 -vn -an -y out.mp4",
        "ConflictingOptions",
        "no streams",
    );
}

#[test]
fn corpus_filter_with_copy_or_vn() {
    rejected(
        "ffmpeg -i in.mp4 -vf scale=640:360 -c:v copy -y out.mp4",
        "ConflictingOptions",
        "streamcopy",
    );
    rejected(
        "ffmpeg -i in.mp4 -vf scale=640:360 -vn -y out.m4a",
        "ConflictingOptions",
        "removes video",
    );
}

#[test]
fn corpus_copy_with_reencode_knobs() {
    rejected(
        "ffmpeg -i in.mp4 -c:v copy -pix_fmt yuv420p -y out.mp4",
        "ConflictingOptions",
        "does not decode",
    );
    rejected(
        "ffmpeg -i in.mp4 -c:a copy -ar 44100 -y out.m4a",
        "ConflictingOptions",
        "does not decode",
    );
}

// ---------------------------------------------------------------------------
// Shell-level constructs arriving through the string form.
// ---------------------------------------------------------------------------

#[test]
fn corpus_shell_redirect_and_pipe() {
    rejected(
        "ffmpeg -i in.mp4 -y out.mp4 2>&1",
        "Tokenize",
        "shell operator",
    );
    rejected(
        "ffmpeg -i in.mp4 -y out.mp4 | cat",
        "Tokenize",
        "shell operator",
    );
}

#[test]
fn corpus_unquoted_glob_input() {
    rejected(
        "ffmpeg -i *.mkv -c:v libx264 -crf 23 -preset fast -c:a aac -y out.mp4",
        "Tokenize",
        "glob",
    );
}

#[test]
fn corpus_shell_variable() {
    rejected("ffmpeg -i $SRC -y out.mp4", "Tokenize", "expansion");
}

#[test]
fn corpus_empty_command() {
    rejected("", "UnsupportedLayout", "no -i input");
    rejected("ffmpeg", "UnsupportedLayout", "no -i input");
}

// ---------------------------------------------------------------------------
// Additional accepted-but-unverified spellings of the accept surface.
// ---------------------------------------------------------------------------

#[test]
fn corpus_bitrate_ladder_spelling() {
    emit_only("ffmpeg -i in.mp4 -c:v libx264 -b:v 2M -c:a aac -b:a 128k -y out.mp4");
}

#[test]
fn corpus_pix_fmt() {
    emit_only("ffmpeg -i in.mp4 -c:v libx264 -pix_fmt yuv420p -y out.mp4");
}

#[test]
fn corpus_input_format_override() {
    emit_only("ffmpeg -f lavfi -i testsrc2=size=320x240:rate=30 -c:v libx264 -y out.mp4");
}

#[test]
fn corpus_default_codecs_remux() {
    emit_only("ffmpeg -i in.mov -y out.mp4");
}

#[test]
fn corpus_unenumerated_shapes_are_rejected_not_scaffolded() {
    // Parses cleanly, but the fingerprint matches neither manifest table:
    // run AND emit refuse — no silent scaffolding class exists.
    rejected(
        "ffmpeg -i in.mp4 -ac 1 -y out.mp4",
        "UnmatchedShape",
        "not in the compatibility manifest",
    );
    rejected(
        "ffmpeg -i in.mp4 -f mp4 -y out2.mp4",
        "UnmatchedShape",
        "nothing is generated for unenumerated shapes",
    );
}

// ---------------------------------------------------------------------------
// No-panic property sweep (the fuzz obligation, deterministic form).
// ---------------------------------------------------------------------------

/// Every generated string must classify (Ok or a typed Err) — the tokenizer
/// and scoper must never panic, whatever byte salad arrives. The generator
/// is a seeded LCG over an alphabet chosen to stress quoting, escapes,
/// continuations, multi-byte characters and option-shaped fragments.
#[test]
fn corpus_no_panic_property_sweep() {
    const ALPHABET: &[&str] = &[
        " ", "-", "i", "c", ":", "v", "'", "\"", "\\", "\n", "^", "$", "0", "9", ".", "=", "",
        "🎬", "\t", "\r", "%", "?", "*", "[", "]", "y", "-i", "-y", "-c:v", "scale", "map", "~",
        "#",
    ];
    let mut state: u64 = 0x243F_6A88_85A3_08D3;
    let mut next = move || {
        state = state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (state >> 33) as usize
    };
    for _ in 0..500 {
        let len = next() % 24;
        let mut cmd = String::new();
        for _ in 0..len {
            cmd.push_str(ALPHABET[next() % ALPHABET.len()]);
        }
        // The property is totality, not acceptance.
        let _ = from_cli(&cmd).map(|_| ());
        let _ = emit_rust_code(&cmd);
    }
}

/// argv-form totality: raw token vectors (no tokenizer in front) with hostile
/// shapes must classify without panicking.
#[test]
fn corpus_no_panic_argv_sweep() {
    let hostile: &[&[&str]] = &[
        &[],
        &[""],
        &["-"],
        &["--"],
        &["-i"],
        &["-i", ""],
        &["-i", "-i"],
        &["-ss"],
        &["-ss", "-ss", "-i", "x", "-y", "y.mp4"],
        &["-c:v", "-c:a", "-i", "x", "-y", "y.mp4"],
        &["🎬", "-y"],
        &["-i", "🎬", "-y", "映画.mp4"],
        &["-map", "", "-i", "x", "-y", "y.mp4"],
        &["-vf", "", "-i", "x", "-y", "y.mp4"],
        &["-y", "-y", "-i", "x", "out.mp4"],
    ];
    for args in hostile {
        let _ = super::from_cli_args(args).map(|_| ());
        let _ = super::emit_rust_code_from_args(args);
    }
}