Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
5156 lines (4744 loc) · 168 KB
/
Copy pathcli.py
File metadata and controls
5156 lines (4744 loc) · 168 KB
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
"""Command-line shortcuts for common media jobs."""
from __future__ import annotations
import argparse
import glob
import json
import math
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
from collections.abc import Callable, Sequence
from dataclasses import asdict, dataclass, replace
from pathlib import Path
from typing import TextIO, cast
from flowmpeg import __version__, shortcuts
from flowmpeg.artifacts import (
FrameWorkflow,
SegmentWorkflow,
dash_package,
frame_sequence,
hls_package,
)
from flowmpeg.audit import (
AuditConstraints,
AuditExpectation,
AuditThreshold,
MediaAudit,
audit_media,
)
from flowmpeg.batch import BatchJob, BatchResult, run_batch
from flowmpeg.black import BlackReport, detect_black
from flowmpeg.catalog import CATEGORIES, COMMAND_CATALOG, TAGS, command_spec
from flowmpeg.comparison import MediaComparison, MediaSummary, compare_media
from flowmpeg.crop_detection import CropReport, detect_crop
from flowmpeg.demo import generate_demo_media
from flowmpeg.diagnostics import display_argv, redact_text
from flowmpeg.errors import (
BinaryNotFoundError,
BinaryUnusableError,
CompilationError,
ExecutionError,
FlowmpegError,
GraphError,
JobCancelledError,
JobTimeoutError,
OutputExistsError,
ProbeError,
)
from flowmpeg.loudness import LoudnessMeasurement, measure_loudness
from flowmpeg.plan import Plan
from flowmpeg.probe import (
AudioStreamInfo,
MediaInfo,
SubtitleStreamInfo,
VideoStreamInfo,
probe,
probe_raw,
)
from flowmpeg.processes import popen_group_options, stop_process_tree
from flowmpeg.progress import Progress
from flowmpeg.quality import QualityMetric, QualityReport, measure_quality
from flowmpeg.scenes import SceneReport, detect_scenes
from flowmpeg.shortcuts import AudioCodec
from flowmpeg.silence import SilenceReport, detect_silence
from flowmpeg.workflows import normalize_loudness_two_pass
_Factory = Callable[..., Plan]
_ArtifactFactory = Callable[..., SegmentWorkflow]
_FrameFactory = Callable[..., FrameWorkflow]
_Handler = Callable[[argparse.Namespace], int]
_JSON_SCHEMA_VERSION = 1
_VIDEO_INPUT_SUFFIXES = frozenset(
{
".3gp",
".avi",
".flv",
".m2ts",
".m4v",
".mkv",
".mov",
".mp4",
".mpeg",
".mpg",
".mts",
".ts",
".webm",
".wmv",
}
)
_CONTROL_NAMES = {
"command",
"dry_run",
"expected_duration",
"explain",
"ffmpeg",
"ffprobe",
"handler",
"media_factory",
"positionals",
"progress",
"probe_timeout",
"timeout",
}
@dataclass(frozen=True, slots=True)
class _Example:
category: str
command: str
tags: tuple[str, ...] = ()
_BASE_EXAMPLES = (
_Example("video", "flowmpeg convert recording.mov -o recording.mp4"),
_Example("video", 'flowmpeg batch "recordings/*.mov" -o converted'),
_Example("video", 'flowmpeg shrink-batch "clips/*.MOV" -o small-clips'),
_Example("video", "flowmpeg webm recording.mov -o recording.webm"),
_Example("video", "flowmpeg hevc recording.mov -o recording-hevc.mp4"),
_Example("video", "flowmpeg av1 recording.mov -o recording-av1.webm"),
_Example(
"video",
"flowmpeg shrink IMG_9357.MOV --max-height 720 --fps 30 -o IMG_9357.mp4",
),
_Example("video", "flowmpeg hls recording.mov -o hls-delivery"),
_Example("video", "flowmpeg dash recording.mov -o dash-delivery"),
_Example("video", "flowmpeg convert animation.mov --no-audio -o animation.mp4"),
_Example("video", "flowmpeg cut input.mp4 --start 5 --duration 12 -o clip.mp4"),
_Example("video", "flowmpeg loop logo-motion.mp4 --duration 30 -o background.mp4"),
_Example("video", "flowmpeg resize input.mp4 --width 1280 -o smaller.mp4"),
_Example("video", "flowmpeg rotate sideways.mp4 --degrees 90 -o upright.mp4"),
_Example("video", "flowmpeg mute input.mp4 -o silent.mp4"),
_Example(
"video", "flowmpeg reframe screen.mp4 --width 720 --height 1280 -o short.mp4"
),
_Example("video", "flowmpeg fps phone.mp4 --fps 30 -o constant.mp4"),
_Example("video", "flowmpeg deinterlace tape.mpg --mode yadif -o progressive.mp4"),
_Example("video", "flowmpeg mirror selfie.mp4 -o normal-view.mp4"),
_Example(
"video", "flowmpeg crop wide.mp4 --width 1080 --height 1080 -o square.mp4"
),
_Example("video", "flowmpeg speed lesson.mp4 --factor 1.5 -o faster.mp4"),
_Example("video", "flowmpeg freeze announcement.mp4 --seconds 3 -o held.mp4"),
_Example(
"video",
"flowmpeg silence-section meeting.mp4 --start 73 --end 81 -o redacted.mp4",
),
_Example("audio", "flowmpeg audio input.mp4 -o track.mp3"),
_Example("audio", "flowmpeg swap-audio video.mp4 narration.wav -o narrated.mp4"),
_Example("audio", "flowmpeg mix host.wav guest.wav -o conversation.wav"),
_Example("audio", "flowmpeg normalize voice.wav --integrated -23 -o broadcast.wav"),
_Example(
"audio",
"flowmpeg normalize-exact voice.wav --target-integrated -16 -o exact.wav",
),
_Example("audio", "flowmpeg denoise room.wav --reduction 10 -o clean.wav"),
_Example("audio", "flowmpeg dynamics uneven.wav --ratio 4 -o controlled.wav"),
_Example(
"audio",
"flowmpeg desilence take.wav --duration 120 --threshold-db -45 -o tight.wav",
),
_Example(
"audio",
"flowmpeg cut-audio interview.wav --start 30 --duration 12 -o answer.wav",
),
_Example("audio", "flowmpeg mono interview.wav --codec mp3 -o interview.mp3"),
_Example(
"audio",
"flowmpeg resample interview.wav --sample-rate 48000 --layout mono -o standard.wav",
),
_Example("audio", "flowmpeg gain quiet.wav --gain-db 6 -o louder.wav"),
_Example(
"audio",
"flowmpeg audio-fade music.wav --duration 120 --fade-in 2 --fade-out 4 -o faded.wav",
),
_Example("audio", "flowmpeg sync-audio narration.wav --seconds 0.35 -o synced.wav"),
_Example("audio", "flowmpeg tempo lesson.wav --factor 1.5 -o lesson-fast.wav"),
_Example(
"audio", "flowmpeg crossfade intro.wav main.wav --duration 2 -o program.wav"
),
_Example("audio", "flowmpeg audio-join intro.wav body.wav outro.wav -o show.wav"),
_Example("audio", "flowmpeg music talk.mp4 music.mp3 -o scored.mp4"),
_Example("audio", "flowmpeg duck talk.mp4 music.mp3 -o ducked.mp4"),
_Example("audio", 'flowmpeg tag episode.m4a --title "Episode 12" -o tagged.m4a'),
_Example("composition", "flowmpeg pip main.mp4 inset.mp4 -o result.mp4"),
_Example("composition", "flowmpeg mark video.mp4 logo.png -o branded.mp4"),
_Example("composition", "flowmpeg join part-1.mp4 part-2.mp4 -o joined.mp4"),
_Example(
"composition",
"flowmpeg join-any phone.mp4 camera.mp4 --width 1280 --height 720 -o joined.mp4",
),
_Example("composition", "flowmpeg grid cam-1.mp4 cam-2.mp4 -o grid.mp4"),
_Example("composition", "flowmpeg fit portrait.mp4 -o portrait-wide.mp4"),
_Example(
"composition",
"flowmpeg blurred-background portrait.mp4 -o portrait-wide.mp4",
),
_Example(
"composition", "flowmpeg still-video cover.jpg episode.mp3 -o episode.mp4"
),
_Example("images", "flowmpeg gif input.mp4 --start 3 --duration 4 -o preview.gif"),
_Example("images", "flowmpeg frames input.mp4 --interval 2 -o review-frames"),
_Example("images", "flowmpeg thumb video.mp4 --at 12 -o moment.jpg"),
_Example("images", "flowmpeg waveform song.mp3 -o waveform.png"),
_Example("images", "flowmpeg spectrum song.mp3 -o spectrum.png"),
_Example("images", "flowmpeg sheet input.mp4 --interval 8 -o sheet.jpg"),
_Example("effects", "flowmpeg reverse input.mp4 --duration 6 -o reversed.mp4"),
_Example("effects", "flowmpeg fade video.mp4 --duration 12 -o faded.mp4"),
_Example("effects", "flowmpeg color flat.mp4 --contrast 1.12 -o graded.mp4"),
_Example("effects", "flowmpeg sharpen soft.mp4 --amount 1.2 -o sharp.mp4"),
_Example(
"effects",
"flowmpeg privacy-blur street.mp4 --x 20 --y 20 --width 200 --height 80 -o private.mp4",
),
_Example("video", "flowmpeg bounce jump.mp4 --duration 2 -o jump-bounce.mp4"),
_Example("video", "flowmpeg compress input.mov -o smaller.mp4"),
_Example("video", "flowmpeg social input.mp4 --target vertical -o vertical.mp4"),
_Example("audio", "flowmpeg voice recording.wav -o finished.wav"),
_Example("subtitles", "flowmpeg captions movie.mp4 subtitles.srt -o captioned.mp4"),
_Example(
"subtitles",
"flowmpeg burn-captions movie.mp4 subtitles.srt -o open-captioned.mp4",
),
_Example("subtitles", "flowmpeg subtitles film.mkv -o captions.srt"),
_Example("subtitles", "flowmpeg strip-subtitles film.mkv -o clean.mp4"),
_Example("metadata", "flowmpeg clean-metadata camera.mkv -o share.mkv"),
_Example("metadata", "flowmpeg remux camera.mp4 -o camera.mkv"),
_Example(
"metadata",
'flowmpeg tag-media camera.mp4 --title "Camera master" -o tagged.mp4',
),
_Example("images", "flowmpeg timelapse frames/frame-%04d.png -o timelapse.mp4"),
_Example("composition", "flowmpeg audiogram episode.wav cover.jpg -o episode.mp4"),
_Example("inspect", "flowmpeg probe input.mp4"),
_Example("inspect", "flowmpeg audit input.mp4 --expect av"),
_Example("inspect", "flowmpeg compare original.mp4 smaller.mp4"),
_Example("inspect", "flowmpeg quality reference.mp4 candidate.mp4"),
_Example("inspect", "flowmpeg loudness episode.wav"),
_Example("inspect", "flowmpeg find-silence interview.wav"),
_Example("inspect", "flowmpeg find-black tape.mp4"),
_Example("inspect", "flowmpeg scenes interview.mp4"),
_Example("inspect", "flowmpeg crop-report letterboxed.mp4 --duration 30"),
_Example("inspect", "flowmpeg doctor"),
_Example("inspect", "flowmpeg setup"),
_Example("help", "flowmpeg errors"),
_Example("help", "flowmpeg explain-error FMG610"),
_Example("help", "flowmpeg examples --category video"),
_Example("help", "flowmpeg commands --category audio"),
_Example("help", "flowmpeg demo-media flowmpeg-demo"),
_Example("help", "flowmpeg ui --no-browser"),
)
def _tag_example(example: _Example) -> _Example:
command = example.command.split(maxsplit=2)[1]
spec = command_spec(command)
if spec is None:
return example
return replace(example, tags=spec.tags)
_EXAMPLES = tuple(_tag_example(example) for example in _BASE_EXAMPLES)
_DURATION_FACTORIES = (
shortcuts.trim,
shortcuts.boomerang,
shortcuts.make_gif,
shortcuts.fade_edges,
shortcuts.reverse_clip,
)
_EXAMPLE_CATEGORIES = tuple(dict.fromkeys(example.category for example in _EXAMPLES))
_AUDIO_CODEC_CHOICES = ("mp3", "aac", "opus", "wav", "flac")
_FEATURE_REQUIREMENTS = {
"web-video": (
"encoder:aac",
"encoder:libx264",
"muxer:mp4",
),
"webm-video": (
"encoder:libopus",
"encoder:libvpx-vp9",
"muxer:webm",
),
"hevc-video": (
"encoder:aac",
"encoder:libx265",
"muxer:mp4",
),
"av1-video": (
"encoder:libopus",
"encoder:libsvtav1",
"muxer:webm",
),
"size-video": (
"encoder:aac",
"encoder:libopus",
"encoder:libx264",
"encoder:libx265",
"filter:fps",
"filter:scale",
"muxer:mp4",
),
"segmented-video": (
"encoder:aac",
"encoder:libx264",
"muxer:dash",
"muxer:hls",
),
"audio-files": (
"encoder:aac",
"encoder:flac",
"encoder:libmp3lame",
"encoder:libopus",
"encoder:pcm_s16le",
"muxer:flac",
"muxer:ipod",
"muxer:mp3",
"muxer:opus",
"muxer:wav",
),
"composition": (
"filter:aformat",
"filter:aresample",
"encoder:aac",
"encoder:libx264",
"filter:concat",
"filter:crop",
"filter:fps",
"filter:gblur",
"filter:overlay",
"filter:pad",
"filter:scale",
"filter:setpts",
"filter:setsar",
"filter:split",
"filter:xstack",
"muxer:mp4",
),
"video-effects": (
"encoder:aac",
"encoder:libx264",
"filter:colorchannelmixer",
"filter:fade",
"filter:format",
"filter:gblur",
"filter:hflip",
"filter:transpose",
"filter:vflip",
"muxer:mp4",
),
"animated-gif": (
"encoder:gif",
"filter:fps",
"filter:palettegen",
"filter:paletteuse",
"filter:scale",
"filter:split",
"muxer:gif",
),
"analysis-images": (
"encoder:libwebp",
"encoder:mjpeg",
"encoder:png",
"filter:fps",
"filter:pad",
"filter:scale",
"filter:setsar",
"filter:showspectrumpic",
"filter:showwavespic",
"filter:tile",
"muxer:image2",
),
"quality-analysis": (
"filter:psnr",
"filter:ssim",
),
"vmaf-analysis": ("filter:libvmaf",),
"audio-processing": (
"filter:acrossfade",
"filter:adelay",
"filter:afade",
"filter:amix",
"filter:apad",
"filter:aresample",
"filter:asplit",
"filter:atempo",
"filter:loudnorm",
"filter:sidechaincompress",
"filter:volume",
),
"reverse": (
"encoder:aac",
"encoder:libx264",
"filter:areverse",
"filter:asetpts",
"filter:reverse",
"filter:setpts",
"muxer:mp4",
),
"creator-video": (
"encoder:aac",
"encoder:libx264",
"filter:boxblur",
"filter:bwdif",
"filter:eq",
"filter:fps",
"filter:tpad",
"filter:unsharp",
"filter:yadif",
"muxer:mp4",
),
"voice-cleanup": (
"filter:acompressor",
"filter:afftdn",
"filter:aformat",
"filter:areverse",
"filter:highpass",
"filter:lowpass",
"filter:loudnorm",
"filter:aresample",
"filter:silenceremove",
"encoder:pcm_s16le",
"muxer:wav",
),
"subtitles": (
"encoder:aac",
"encoder:ass",
"encoder:libx264",
"encoder:mov_text",
"encoder:srt",
"encoder:webvtt",
"filter:subtitles",
"muxer:mp4",
),
"audiogram": (
"encoder:aac",
"encoder:libx264",
"filter:asplit",
"filter:colorkey",
"filter:overlay",
"filter:pad",
"filter:scale",
"filter:setsar",
"filter:showwaves",
"muxer:mp4",
),
}
_ERROR_GUIDE = {
"FMG200": (
"Invalid media plan",
"A path, option, stream selection, or graph connection is invalid.",
"Read the message, correct the command arguments, then use --dry-run.",
),
"FMG300": (
"FFmpeg missing",
"Flowmpeg could not start the FFmpeg executable.",
"Run flowmpeg setup, install FFmpeg, then open a new terminal.",
),
"FMG301": (
"FFprobe missing",
"Flowmpeg could not start the FFprobe executable.",
"Run flowmpeg setup and confirm FFprobe is on PATH.",
),
"FMG302": (
"Media tool unusable",
"A media executable exists but could not be run.",
"Check execute permission, antivirus rules, and the configured path.",
),
"FMG303": (
"Installer unavailable",
"No supported package manager was found.",
"Install FFmpeg from ffmpeg.org, then run flowmpeg doctor.",
),
"FMG304": (
"Install failed",
"The selected package manager returned a failure.",
"Read its output, fix permissions or network access, then try again.",
),
"FMG400": (
"Output exists",
"The destination exists and replacement was not enabled.",
"Choose another output or add --overwrite.",
),
"FMG500": (
"Probe failed",
"FFprobe could not read the requested input.",
"Check the path, file permissions, URL access, and file integrity.",
),
"FMG600": (
"FFmpeg failed",
"FFmpeg stopped while processing the command.",
"Read the reported reason and rerun with --dry-run to inspect the command.",
),
"FMG610": (
"Encoder missing",
"This FFmpeg build does not contain the requested encoder.",
"Run flowmpeg doctor and install a build with the listed encoder.",
),
"FMG611": (
"Decoder missing",
"FFmpeg cannot decode one of the input streams.",
"Install a build with the required decoder or convert the input elsewhere.",
),
"FMG612": (
"Filter missing",
"This FFmpeg build does not contain the requested filter.",
"Run flowmpeg doctor and install a build with the listed filter.",
),
"FMG620": (
"Permission denied",
"FFmpeg could not read an input or write the output.",
"Check file permissions and write access to the output folder.",
),
"FMG621": (
"Storage full",
"The output device ran out of free space.",
"Free space, remove the partial output, then run the command again.",
),
"FMG630": (
"Network input failed",
"A remote input could not be opened or authorized.",
"Check the URL, credentials, connection, and protocol support.",
),
"FMG700": (
"Job timed out",
"The configured timeout ended FFmpeg before it finished.",
"Increase --timeout or omit it for long media jobs.",
),
}
@dataclass(frozen=True, slots=True)
class _Installer:
manager: str
commands: tuple[tuple[str, ...], ...]
note: str
def build_parser() -> argparse.ArgumentParser:
"""Build the public command parser."""
parser = argparse.ArgumentParser(
prog="flowmpeg",
description=(
"Run common FFmpeg jobs with readable one-line commands. "
"Editing commands run immediately. Use --dry-run on a command to "
"preview it, and --overwrite to replace an existing output. "
"FFmpeg and FFprobe must be installed separately."
),
allow_abbrev=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--version",
action="version",
version=f"flowmpeg {__version__}",
)
commands = parser.add_subparsers(dest="command", metavar="COMMAND")
_add_transcode(commands)
_add_batch_transcode(commands)
_add_batch_shrink(commands)
_add_transcode_webm(commands)
_add_transcode_hevc(commands)
_add_transcode_av1(commands)
_add_hls(commands)
_add_dash(commands)
_add_frame_sequence(commands)
_add_trim(commands)
_add_loop_video(commands)
_add_resize(commands)
_add_remove_audio(commands)
_add_extract_audio(commands)
_add_replace_audio(commands)
_add_watermark(commands)
_add_add_music(commands)
_add_join(commands)
_add_join_normalized(commands)
_add_mix_audio(commands)
_add_grid(commands)
_add_thumbnail(commands)
_add_gif(commands)
_add_rotate(commands)
_add_crop(commands)
_add_speed(commands)
_add_normalize(commands)
_add_two_pass_normalize(commands)
_add_fit_canvas(commands)
_add_picture_in_picture(commands)
_add_waveform(commands)
_add_spectrum(commands)
_add_still_image_video(commands)
_add_contact_sheet(commands)
_add_duck_music(commands)
_add_fade_edges(commands)
_add_blurred_background(commands)
_add_reverse(commands)
_add_compress_video(commands)
_add_shrink_video(commands)
_add_reframe(commands)
_add_social_video(commands)
_add_frame_rate(commands)
_add_deinterlace(commands)
_add_flip(commands)
_add_adjust_colors(commands)
_add_sharpen(commands)
_add_freeze_end(commands)
_add_mute_section(commands)
_add_blur_region(commands)
_add_boomerang(commands)
_add_denoise_audio(commands)
_add_compress_audio(commands)
_add_podcast_voice(commands)
_add_trim_silence(commands)
_add_trim_audio(commands)
_add_mono_audio(commands)
_add_resample_audio(commands)
_add_volume_audio(commands)
_add_fade_audio(commands)
_add_delay_audio(commands)
_add_speed_audio(commands)
_add_crossfade_audio(commands)
_add_join_audio(commands)
_add_extract_subtitles(commands)
_add_add_subtitles(commands)
_add_burn_subtitles(commands)
_add_remove_subtitles(commands)
_add_image_sequence(commands)
_add_podcast_audiogram(commands)
_add_strip_metadata(commands)
_add_remux(commands)
_add_tag_media(commands)
_add_tag_audio(commands)
_add_probe(commands)
_add_audit(commands)
_add_compare(commands)
_add_quality(commands)
_add_loudness(commands)
_add_silence_detection(commands)
_add_black_detection(commands)
_add_scene_detection(commands)
_add_crop_detection(commands)
_add_doctor(commands)
_add_setup(commands)
_add_demo_media(commands)
_add_ui(commands)
_add_errors(commands)
_add_explain_error(commands)
_add_examples(commands)
_add_commands(commands)
return parser
def main(argv: Sequence[str] | None = None) -> int:
"""Run the CLI and return a process exit code."""
values = list(sys.argv[1:] if argv is None else argv)
parser = build_parser()
if not values:
parser.print_help()
return 0
args = parser.parse_args(values)
handler_value = getattr(args, "handler", None)
if handler_value is None:
parser.print_help()
return 0
handler = cast(_Handler, handler_value)
try:
return handler(args)
except (GraphError, CompilationError) as error:
return _error(error, 2, "FMG200")
except BinaryNotFoundError as error:
error_id = "FMG301" if error.tool == "ffprobe" else "FMG300"
return _error(error, 3, error_id)
except BinaryUnusableError as error:
return _error(error, 3, "FMG302")
except OutputExistsError as error:
_error(error, 4, "FMG400")
print("flowmpeg: add --overwrite to replace it", file=sys.stderr)
return 4
except ProbeError as error:
return _probe_error(error)
except ExecutionError as error:
return _execution_error(error)
except JobTimeoutError as error:
return _error(error, 7, "FMG700")
except JobCancelledError:
print("flowmpeg: cancelled", file=sys.stderr)
return 130
except KeyboardInterrupt:
print("flowmpeg: interrupted", file=sys.stderr)
return 130
except FlowmpegError as error:
return _error(error, 1, "FMG600")
def _command(
commands: argparse._SubParsersAction[argparse.ArgumentParser],
name: str,
help_text: str,
factory: _Factory,
positionals: tuple[str, ...],
*,
aliases: Sequence[str] = (),
) -> argparse.ArgumentParser:
parser = commands.add_parser(
name,
aliases=list(aliases),
help=help_text,
description=help_text,
allow_abbrev=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.set_defaults(
handler=_run_media,
media_factory=factory,
positionals=positionals,
)
return parser
def _source(parser: argparse.ArgumentParser, name: str = "source") -> None:
parser.add_argument(name, help="Input media path or URL")
def _output(parser: argparse.ArgumentParser) -> None:
parser.add_argument("-o", "--output", required=True, help="Output file path")
parser.add_argument(
"--overwrite",
action="store_true",
help="Allow replacing an existing output",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print the FFmpeg command without running it",
)
parser.add_argument("--ffmpeg", default="ffmpeg", help="FFmpeg executable")
parser.add_argument("--ffprobe", default="ffprobe", help="FFprobe executable")
parser.add_argument(
"--probe-timeout",
type=_positive_float,
default=10.0,
help="Maximum seconds for automatic stream inspection",
)
parser.add_argument(
"--timeout",
type=_positive_float,
help="Maximum run time in seconds",
)
parser.add_argument(
"--expected-duration",
type=_positive_float,
help="Expected output duration for percent progress",
)
parser.add_argument(
"--progress",
action=argparse.BooleanOptionalAction,
default=True,
help="Show progress while FFmpeg runs",
)
parser.add_argument(
"--explain",
action="store_true",
help="Describe the plan before running it",
)
def _audio_toggle(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--audio",
dest="include_audio",
action=argparse.BooleanOptionalAction,
default=True,
help="Keep the first audio track",
)
def _normalize_toggle(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--normalize",
action=argparse.BooleanOptionalAction,
default=True,
help="Normalize the mixed audio weights",
)
def _add_transcode(
commands: argparse._SubParsersAction[argparse.ArgumentParser],
) -> None:
parser = _command(
commands,
"transcode",
"Convert a video to a web MP4.",
shortcuts.transcode,
("source",),
aliases=("convert",),
)
_source(parser)
_audio_toggle(parser)
_output(parser)
def _add_batch_transcode(
commands: argparse._SubParsersAction[argparse.ArgumentParser],
) -> None:
parser = commands.add_parser(
"batch-transcode",
aliases=["batch", "batch-convert"],
help="Convert several local videos to web MP4 files.",
description=(
"Convert local files, directories, or quoted patterns to web MP4 files."
),
allow_abbrev=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"sources",
nargs="+",
help="Input files, directories, or quoted wildcard patterns",
)
parser.add_argument(
"-o",
"--output-dir",
required=True,
help="Directory for converted MP4 files",
)
parser.add_argument(
"--recursive",
action="store_true",
help="Search directory inputs and double-star patterns recursively",
)
parser.add_argument(
"--name-suffix",
default="",
help="Text added after each source stem",
)
_audio_toggle(parser)
parser.add_argument(
"--continue-on-error",
action="store_true",
help="Run later files after one conversion fails",
)
parser.add_argument("--overwrite", action="store_true")
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--json", action="store_true", help="Print result JSON")
parser.add_argument("--ffmpeg", default="ffmpeg", help="FFmpeg executable")
parser.add_argument("--ffprobe", default="ffprobe", help="FFprobe executable")
parser.add_argument(
"--probe-timeout",
type=_positive_float,
default=10.0,
help="Maximum seconds for each audio stream check",
)
parser.add_argument(
"--timeout",
type=_positive_float,
help="Maximum run time per file in seconds",
)
parser.add_argument(
"--progress",
action=argparse.BooleanOptionalAction,
default=True,
help="Show FFmpeg progress",
)
parser.set_defaults(handler=_run_batch_transcode)
def _add_batch_shrink(
commands: argparse._SubParsersAction[argparse.ArgumentParser],
) -> None:
parser = commands.add_parser(
"batch-shrink",
aliases=["shrink-batch", "shrink-folder", "shrink-all"],
help="Shrink several local videos to small MP4 files.",
description=(
"Shrink local files, directories, or quoted patterns to small MP4 files."
),
allow_abbrev=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"sources",
nargs="+",
help="Input files, directories, or quoted wildcard patterns",
)
parser.add_argument(
"-o",
"--output-dir",
required=True,
help="Directory for small MP4 files",
)
parser.add_argument(
"--recursive",
action="store_true",
help="Search directory inputs and double-star patterns recursively",
)
parser.add_argument(
"--name-suffix",
default="-small",
help="Text added after each source stem",
)
parser.add_argument("--codec", choices=("h264", "hevc"), default="hevc")
parser.add_argument("--crf", type=_nonnegative_int, default=28)
parser.add_argument(
"--encoder-preset",
choices=(
"ultrafast",
"superfast",
"veryfast",
"faster",
"fast",
"medium",
"slow",
"slower",
"veryslow",
),
default="medium",
)
parser.add_argument("--max-width", type=_positive_int)
parser.add_argument("--max-height", type=_positive_int, default=720)
parser.add_argument("--fps", type=_positive_int, default=30)
parser.add_argument(
"--keep-size",
action="store_true",
help="Keep source dimensions apart from even-pixel rounding",
)
parser.add_argument(
"--keep-fps",
action="store_true",
help="Keep the original frame rate",
)
parser.add_argument("--audio-codec", choices=("aac", "opus"), default="aac")
parser.add_argument("--audio-bitrate", default="96k")
_audio_toggle(parser)
parser.add_argument(
"--continue-on-error",
action="store_true",
help="Run later files after one conversion fails",
)
parser.add_argument("--overwrite", action="store_true")
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--json", action="store_true", help="Print result JSON")
parser.add_argument("--ffmpeg", default="ffmpeg", help="FFmpeg executable")
parser.add_argument("--ffprobe", default="ffprobe", help="FFprobe executable")
parser.add_argument(
"--probe-timeout",
type=_positive_float,
default=10.0,
help="Maximum seconds for each audio stream check",
)
parser.add_argument(
"--timeout",
type=_positive_float,
help="Maximum run time per file in seconds",
)
parser.add_argument(
"--progress",
action=argparse.BooleanOptionalAction,
default=True,
help="Show FFmpeg progress",
)
parser.set_defaults(handler=_run_batch_shrink)
def _add_transcode_webm(
commands: argparse._SubParsersAction[argparse.ArgumentParser],
) -> None:
parser = _command(
commands,
"transcode-webm",
"Encode VP9 video and Opus audio in WebM.",
shortcuts.transcode_webm,
("source",),
aliases=("webm", "vp9"),
)
_source(parser)
parser.add_argument("--crf", type=_nonnegative_int, default=32)
parser.add_argument("--cpu-used", type=_nonnegative_int, default=2)
parser.add_argument("--audio-bitrate", default="128k")
_audio_toggle(parser)
_output(parser)
def _add_transcode_hevc(
commands: argparse._SubParsersAction[argparse.ArgumentParser],
) -> None:
parser = _command(