add interactive menu to ffmpeg script
This commit is contained in:
1 parent
c6aa1ac6fb
commit
a56a4dfbf6
1 file changed
+205
-83
+205
-83
@@ -13,6 +13,11 @@ import sys
|
|||||||
import json
|
import json
|
||||||
import ffmpeg
|
import ffmpeg
|
||||||
import re
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# ----------------------------
|
||||||
|
# OUTPUT ENFORCEMENT (clean + centralized)
|
||||||
|
# ----------------------------
|
||||||
REQUIRES_OUTPUT = {
|
REQUIRES_OUTPUT = {
|
||||||
"convert-av",
|
"convert-av",
|
||||||
"convert-audio",
|
"convert-audio",
|
||||||
@@ -26,6 +31,18 @@ REQUIRES_OUTPUT = {
|
|||||||
}
|
}
|
||||||
# ---------- Utilities ---------- #
|
# ---------- Utilities ---------- #
|
||||||
|
|
||||||
|
# ----------------------------
|
||||||
|
# HELPERS
|
||||||
|
# ----------------------------
|
||||||
|
def ask(prompt, default=None):
|
||||||
|
value = input(f"{prompt}" + (f" [{default}]" if default else "") + ": ").strip()
|
||||||
|
return value if value else default
|
||||||
|
|
||||||
|
def ensure(value, prompt):
|
||||||
|
if value is None:
|
||||||
|
return ask(prompt)
|
||||||
|
return value
|
||||||
|
|
||||||
def run_ffmpeg(stream, overwrite=True):
|
def run_ffmpeg(stream, overwrite=True):
|
||||||
"""
|
"""
|
||||||
Run FFmpeg and stream output directly to terminal.
|
Run FFmpeg and stream output directly to terminal.
|
||||||
@@ -75,11 +92,11 @@ def select_audio_stream(file, provided=None):
|
|||||||
print("No audio streams found.")
|
print("No audio streams found.")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
provided = int(provided) if provided else None
|
||||||
if provided is not None:
|
if provided is not None:
|
||||||
if any(s[0] == provided for s in streams):
|
if any(s[0] == provided for s in streams):
|
||||||
return provided
|
return provided
|
||||||
print(f"Provided index {provided} is not a valid audio stream.")
|
print(f"Provided index {provided} is not a valid audio stream.")
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
if len(streams) == 1:
|
if len(streams) == 1:
|
||||||
return streams[0][0]
|
return streams[0][0]
|
||||||
@@ -530,7 +547,7 @@ def cmd_test(args):
|
|||||||
|
|
||||||
if not outputs:
|
if not outputs:
|
||||||
print("No outputs returned.")
|
print("No outputs returned.")
|
||||||
return
|
return 1
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ffmpeg.run(
|
ffmpeg.run(
|
||||||
@@ -543,7 +560,7 @@ def cmd_test(args):
|
|||||||
print("FFmpeg failed:")
|
print("FFmpeg failed:")
|
||||||
if e.stderr:
|
if e.stderr:
|
||||||
print(e.stderr.decode(errors="ignore"))
|
print(e.stderr.decode(errors="ignore"))
|
||||||
return
|
return 1
|
||||||
|
|
||||||
# Probe result file(s)
|
# Probe result file(s)
|
||||||
out_files = []
|
out_files = []
|
||||||
@@ -561,10 +578,13 @@ def cmd_test(args):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
validate_ffprobe(f,test_dict[i])
|
ret_va = validate_ffprobe(f,test_dict[i])
|
||||||
except ffmpeg.Error as e:
|
except ffmpeg.Error as e:
|
||||||
print(f"{red_tag("FAIL")} Probe error: {f}")
|
print(f"{red_tag("FAIL")} Probe error: {f}")
|
||||||
print(e)
|
print(e)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
return ret_va
|
||||||
|
|
||||||
def get_streams(test_file):
|
def get_streams(test_file):
|
||||||
info = ffmpeg.probe(test_file)
|
info = ffmpeg.probe(test_file)
|
||||||
@@ -599,19 +619,23 @@ def cmd_test(args):
|
|||||||
video_streams = [s for s in streams if s.get("codec_type") == "video"]
|
video_streams = [s for s in streams if s.get("codec_type") == "video"]
|
||||||
audio_streams = [s for s in streams if s.get("codec_type") == "audio"]
|
audio_streams = [s for s in streams if s.get("codec_type") == "audio"]
|
||||||
subtitle_streams = [s for s in streams if s.get("codec_type") == "subtitle"]
|
subtitle_streams = [s for s in streams if s.get("codec_type") == "subtitle"]
|
||||||
|
ret = 0
|
||||||
|
|
||||||
# ---------- COUNT CHECKS ----------
|
# ---------- COUNT CHECKS ----------
|
||||||
if "video_count" in expected:
|
if "video_count" in expected:
|
||||||
if len(video_streams) != expected["video_count"]:
|
if len(video_streams) != expected["video_count"]:
|
||||||
print(f"{red_tag("VIDEO COUNT FAIL")} expected {expected['video_count']}, got {len(video_streams)}")
|
print(f"{red_tag("VIDEO COUNT FAIL")} expected {expected['video_count']}, got {len(video_streams)}")
|
||||||
|
ret = 1
|
||||||
|
|
||||||
if "audio_count" in expected:
|
if "audio_count" in expected:
|
||||||
if len(audio_streams) != expected["audio_count"]:
|
if len(audio_streams) != expected["audio_count"]:
|
||||||
print(f"{red_tag("AUDIO COUNT FAIL")} expected {expected['audio_count']}, got {len(audio_streams)}")
|
print(f"{red_tag("AUDIO COUNT FAIL")} expected {expected['audio_count']}, got {len(audio_streams)}")
|
||||||
|
ret = 1
|
||||||
|
|
||||||
if "subtitle_count" in expected:
|
if "subtitle_count" in expected:
|
||||||
if len(subtitle_streams) != expected["subtitle_count"]:
|
if len(subtitle_streams) != expected["subtitle_count"]:
|
||||||
print(f"{red_tag("SUBTITLE COUNT FAIL")} expected {expected['subtitle_count']}, got {len(subtitle_streams)}")
|
print(f"{red_tag("SUBTITLE COUNT FAIL")} expected {expected['subtitle_count']}, got {len(subtitle_streams)}")
|
||||||
|
ret = 1
|
||||||
|
|
||||||
# ---------- CODEC CHECKS ----------
|
# ---------- CODEC CHECKS ----------
|
||||||
if "audio_codecs" in expected:
|
if "audio_codecs" in expected:
|
||||||
@@ -623,6 +647,7 @@ def cmd_test(args):
|
|||||||
|
|
||||||
if actual != expected_codecs:
|
if actual != expected_codecs:
|
||||||
print(f"{red_tag("AUDIO CODEC FAIL")}\nExpected: {expected_codecs}\nGot: {actual}")
|
print(f"{red_tag("AUDIO CODEC FAIL")}\nExpected: {expected_codecs}\nGot: {actual}")
|
||||||
|
ret = 1
|
||||||
|
|
||||||
if "video_codecs" in expected:
|
if "video_codecs" in expected:
|
||||||
actual = sorted([s.get("codec_name") for s in video_streams])
|
actual = sorted([s.get("codec_name") for s in video_streams])
|
||||||
@@ -632,6 +657,8 @@ def cmd_test(args):
|
|||||||
expected_codecs = expected_codecs + [last] * (len(actual) - len(expected_codecs))
|
expected_codecs = expected_codecs + [last] * (len(actual) - len(expected_codecs))
|
||||||
if actual != expected_codecs:
|
if actual != expected_codecs:
|
||||||
print(f"{red_tag("VIDEO CODEC FAIL")}\nExpected: {expected_codecs}\nGot: {actual}")
|
print(f"{red_tag("VIDEO CODEC FAIL")}\nExpected: {expected_codecs}\nGot: {actual}")
|
||||||
|
ret = 1
|
||||||
|
|
||||||
# ---------- DURATION CHECKS ----------
|
# ---------- DURATION CHECKS ----------
|
||||||
if "duration" in expected:
|
if "duration" in expected:
|
||||||
format_info = info.get("format", {})
|
format_info = info.get("format", {})
|
||||||
@@ -644,20 +671,22 @@ def cmd_test(args):
|
|||||||
|
|
||||||
if abs(actual_duration - expected_duration) <= tolerance:
|
if abs(actual_duration - expected_duration) <= tolerance:
|
||||||
print(f"{red_tag("DURATION FAIL")} expected ~{expected_duration} (±{tolerance}), got {actual_duration}s")
|
print(f"{red_tag("DURATION FAIL")} expected ~{expected_duration} (±{tolerance}), got {actual_duration}s")
|
||||||
|
ret = 1
|
||||||
|
|
||||||
print(f"{green_tag("PASS")} {file_path}")
|
print(f"{green_tag("PASS")} {file_path}")
|
||||||
return True
|
return ret
|
||||||
|
|
||||||
class Args:
|
class Args:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
ret = 0
|
||||||
# ---------- INFO ----------
|
# ---------- INFO ----------
|
||||||
#args = Args()
|
#args = Args()
|
||||||
#args.input = test_file_mp4
|
#args.input = test_file_mp4
|
||||||
#test_dict = {}
|
#test_dict = {}
|
||||||
#run_and_probe("info", cmd_info, args, test_dict)
|
#run_and_probe("info", cmd_info, args, test_dict)
|
||||||
#args.input = test_file_mkv
|
#args.input = test_file_mkv
|
||||||
#run_and_probe("info", cmd_info, args, test_dict)
|
#ret += run_and_probe("info", cmd_info, args, test_dict)
|
||||||
|
|
||||||
# ---------- DOWNSIZE ----------
|
# ---------- DOWNSIZE ----------
|
||||||
args = Args()
|
args = Args()
|
||||||
@@ -670,7 +699,7 @@ def cmd_test(args):
|
|||||||
args.crf = 28
|
args.crf = 28
|
||||||
test_dict = [{"video_count": len(video_streams), "audio_count": len(audio_streams),
|
test_dict = [{"video_count": len(video_streams), "audio_count": len(audio_streams),
|
||||||
"subtitle_count": len(subtitle_streams), "video_codecs": ["h264"]}]
|
"subtitle_count": len(subtitle_streams), "video_codecs": ["h264"]}]
|
||||||
run_and_probe("downsize", cmd_downsize, args, test_dict)
|
ret += run_and_probe("downsize", cmd_downsize, args, test_dict)
|
||||||
|
|
||||||
# ---------- REMOVE AUDIO TRACK ----------
|
# ---------- REMOVE AUDIO TRACK ----------
|
||||||
args = Args()
|
args = Args()
|
||||||
@@ -683,7 +712,7 @@ def cmd_test(args):
|
|||||||
{"video_count": 0, "audio_count": 1, "subtitle_count": 0}]
|
{"video_count": 0, "audio_count": 1, "subtitle_count": 0}]
|
||||||
args.output = os.path.join(test_dir, "out_remove_audio" + os.path.splitext(test_file)[1])
|
args.output = os.path.join(test_dir, "out_remove_audio" + os.path.splitext(test_file)[1])
|
||||||
args.output_audio = os.path.join(test_dir, "extracted_audio_" + os.path.splitext(test_file)[1][1:] + ".mp3")
|
args.output_audio = os.path.join(test_dir, "extracted_audio_" + os.path.splitext(test_file)[1][1:] + ".mp3")
|
||||||
run_and_probe("remove-audio-track", cmd_remove_audio_track, args, test_dict)
|
ret += run_and_probe("remove-audio-track", cmd_remove_audio_track, args, test_dict)
|
||||||
|
|
||||||
# ---------- CONVERT AV ----------
|
# ---------- CONVERT AV ----------
|
||||||
args = Args()
|
args = Args()
|
||||||
@@ -697,7 +726,7 @@ def cmd_test(args):
|
|||||||
args.quality = 23
|
args.quality = 23
|
||||||
test_dict = [ {"video_count": len(video_streams),"audio_count": len(audio_streams),
|
test_dict = [ {"video_count": len(video_streams),"audio_count": len(audio_streams),
|
||||||
"subtitle_count": len(subtitle_streams), "video_codecs": ["h264"],"audio_codecs": ["aac"]}]
|
"subtitle_count": len(subtitle_streams), "video_codecs": ["h264"],"audio_codecs": ["aac"]}]
|
||||||
run_and_probe("convert-av", cmd_convert_av, args, test_dict)
|
ret += run_and_probe("convert-av", cmd_convert_av, args, test_dict)
|
||||||
|
|
||||||
|
|
||||||
# ---------- CONVERT AUDIO ----------
|
# ---------- CONVERT AUDIO ----------
|
||||||
@@ -709,7 +738,7 @@ def cmd_test(args):
|
|||||||
args.audio_codec = "aac"
|
args.audio_codec = "aac"
|
||||||
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
||||||
"subtitle_count": len(subtitle_streams), "audio_codecs": ["aac"]}]
|
"subtitle_count": len(subtitle_streams), "audio_codecs": ["aac"]}]
|
||||||
run_and_probe("convert-audio", cmd_convert_audio, args, test_dict)
|
ret += run_and_probe("convert-audio", cmd_convert_audio, args, test_dict)
|
||||||
|
|
||||||
# ---------- CONVERT VIDEO ----------
|
# ---------- CONVERT VIDEO ----------
|
||||||
args = Args()
|
args = Args()
|
||||||
@@ -720,7 +749,7 @@ def cmd_test(args):
|
|||||||
args.video_codec = "libx264"
|
args.video_codec = "libx264"
|
||||||
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
||||||
"subtitle_count": len(subtitle_streams), "video_codecs": ["h264"]}]
|
"subtitle_count": len(subtitle_streams), "video_codecs": ["h264"]}]
|
||||||
run_and_probe("convert-video", cmd_convert_video, args, test_dict)
|
ret += run_and_probe("convert-video", cmd_convert_video, args, test_dict)
|
||||||
|
|
||||||
# ---------- REMOVE SUBS ----------
|
# ---------- REMOVE SUBS ----------
|
||||||
args = Args()
|
args = Args()
|
||||||
@@ -729,7 +758,7 @@ def cmd_test(args):
|
|||||||
args.input = test_file
|
args.input = test_file
|
||||||
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams), "subtitle_count": 0}]
|
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams), "subtitle_count": 0}]
|
||||||
args.output = os.path.join(test_dir, "out_no_subs" + os.path.splitext(test_file)[1])
|
args.output = os.path.join(test_dir, "out_no_subs" + os.path.splitext(test_file)[1])
|
||||||
run_and_probe("remove-subs", cmd_remove_subs, args, test_dict)
|
ret += run_and_probe("remove-subs", cmd_remove_subs, args, test_dict)
|
||||||
|
|
||||||
# ---------- FILTER AUDIO ----------
|
# ---------- FILTER AUDIO ----------
|
||||||
args = Args()
|
args = Args()
|
||||||
@@ -740,7 +769,7 @@ def cmd_test(args):
|
|||||||
args.audio_index = 1
|
args.audio_index = 1
|
||||||
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
||||||
"subtitle_count": len(subtitle_streams), "audio_codecs": ["vorbis"]}]
|
"subtitle_count": len(subtitle_streams), "audio_codecs": ["vorbis"]}]
|
||||||
run_and_probe("filter-audio", cmd_filter_audio, args, test_dict)
|
ret += run_and_probe("filter-audio", cmd_filter_audio, args, test_dict)
|
||||||
|
|
||||||
# ---------- CUT ----------
|
# ---------- CUT ----------
|
||||||
args = Args()
|
args = Args()
|
||||||
@@ -752,7 +781,7 @@ def cmd_test(args):
|
|||||||
args.duration = "10s"
|
args.duration = "10s"
|
||||||
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
||||||
"subtitle_count": len(subtitle_streams), "duration": "10s"}]
|
"subtitle_count": len(subtitle_streams), "duration": "10s"}]
|
||||||
run_and_probe("cut", cmd_cut_segment, args, test_dict)
|
ret += run_and_probe("cut", cmd_cut_segment, args, test_dict)
|
||||||
|
|
||||||
# ---------- SET PRIMARY AUDIO ----------
|
# ---------- SET PRIMARY AUDIO ----------
|
||||||
args = Args()
|
args = Args()
|
||||||
@@ -763,108 +792,201 @@ def cmd_test(args):
|
|||||||
args.audio_index = 2
|
args.audio_index = 2
|
||||||
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
test_dict = [ {"video_count": len(video_streams), "audio_count": len(audio_streams),
|
||||||
"subtitle_count": len(subtitle_streams)}]
|
"subtitle_count": len(subtitle_streams)}]
|
||||||
run_and_probe("set-primary-audio", cmd_set_primary_audio, args, test_dict)
|
ret += run_and_probe("set-primary-audio", cmd_set_primary_audio, args, test_dict)
|
||||||
|
|
||||||
print("\nALL TESTS COMPLETED")
|
if ret == 0:
|
||||||
|
print(green_tag("ALL TESTS SUCCEEDED"))
|
||||||
|
else:
|
||||||
|
print(red_tag("SOME TESTS FAILED"))
|
||||||
|
|
||||||
# ---------- CLI Setup ---------- #
|
# ---------- CLI Setup ---------- #
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
description="Media processing tool using ffmpeg-python",
|
description="Media processing tool using ffmpeg-python (CLI + interactive fallback)",
|
||||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter
|
||||||
)
|
)
|
||||||
|
|
||||||
# Base parser shared across all subcommands
|
# ----------------------------
|
||||||
|
# BASE ARGS (shared)
|
||||||
|
# ----------------------------
|
||||||
base_p = argparse.ArgumentParser(add_help=False)
|
base_p = argparse.ArgumentParser(add_help=False)
|
||||||
base_p.add_argument("input", help="Path to input media file")
|
base_p.add_argument("input", nargs="?", help="Path to input media file")
|
||||||
base_p.add_argument("-o", "--output", help="Path for output file")
|
base_p.add_argument("-o", "--output", help="Path for output file")
|
||||||
|
|
||||||
sub = parser.add_subparsers(dest="command", required=True)
|
sub = parser.add_subparsers(dest="command") # command is optional now
|
||||||
|
|
||||||
# Info Command
|
# ----------------------------
|
||||||
p_info = sub.add_parser("info", parents=[base_p], help="Inspect media metadata")
|
# INFO
|
||||||
p_info.set_defaults(func=cmd_info)
|
# ----------------------------
|
||||||
# Info Command
|
p_info = sub.add_parser("info", aliases=["i"], parents=[base_p], help="Inspect media metadata")
|
||||||
p_info = sub.add_parser("test", help="Inspect media metadata")
|
p_info.set_defaults(func=cmd_info, command="info")
|
||||||
p_info.set_defaults(func=cmd_test)
|
|
||||||
|
|
||||||
# Convert AV Command
|
# TEST
|
||||||
p_av = sub.add_parser("convert-av", parents=[base_p], help="Full re-encode of video/audio")
|
p_test = sub.add_parser("test", aliases=["t"], help="Run test function")
|
||||||
p_av.add_argument("--video-codec", default="libx264", help="FFmpeg -c:v flag")
|
p_test.set_defaults(func=cmd_test, command="test")
|
||||||
p_av.add_argument("--audio-codec", default="aac", help="FFmpeg -c:a flag")
|
|
||||||
p_av.add_argument("--preset", default="medium", help="FFmpeg -preset flag")
|
|
||||||
p_av.add_argument("--quality", type=int, default=23, help="FFmpeg -crf value")
|
|
||||||
p_av.set_defaults(func=cmd_convert_av)
|
|
||||||
|
|
||||||
# Convert Audio Command
|
# ----------------------------
|
||||||
p_a = sub.add_parser("convert-audio", parents=[base_p], help="Change audio format only")
|
# CONVERT AV
|
||||||
p_a.add_argument("--audio-codec", default="mp3", help="FFmpeg -c:a flag")
|
# ----------------------------
|
||||||
p_a.set_defaults(func=cmd_convert_audio)
|
p_av = sub.add_parser("convert-av", aliases=["cav"], parents=[base_p], help="Full re-encode of video/audio")
|
||||||
|
p_av.add_argument("--video-codec", default="libx264",
|
||||||
|
help="Video codec to use (default: libx264, e.g. libx265, vp9)")
|
||||||
|
p_av.add_argument("--audio-codec", default="aac", help="Audio codec to use (default: aac, e.g. mp3, opus)")
|
||||||
|
p_av.add_argument("--preset", default="medium",
|
||||||
|
help="Encoding speed/quality preset (default: medium, e.g. ultrafast, fast, slow, veryslow)")
|
||||||
|
p_av.add_argument("--quality", type=int,
|
||||||
|
help="Output quality level (e.g. CRF value or bitrate depending on encoder)")
|
||||||
|
p_av.set_defaults(func=cmd_convert_av, command="convert-av")
|
||||||
|
|
||||||
# Convert Video Command
|
# ----------------------------
|
||||||
p_v = sub.add_parser("convert-video", parents=[base_p], help="Change video format only")
|
# CONVERT AUDIO
|
||||||
p_v.add_argument("--video-codec", default="libx264", help="FFmpeg -c:v flag")
|
# ----------------------------
|
||||||
p_v.set_defaults(func=cmd_convert_video)
|
p_a = sub.add_parser("convert-audio", aliases=["ca"], parents=[base_p], help="Change audio format only")
|
||||||
|
p_a.add_argument("--audio-codec", default="aac", help="Audio codec to use (default: aac, e.g. mp3, opus)")
|
||||||
|
p_a.set_defaults(func=cmd_convert_audio, command="convert-audio")
|
||||||
|
|
||||||
# Remove Subs Command
|
# ----------------------------
|
||||||
p_rs = sub.add_parser("remove-subs", parents=[base_p], help="Strip all subtitle streams (-sn)")
|
# CONVERT VIDEO
|
||||||
p_rs.set_defaults(func=cmd_remove_subs)
|
# ----------------------------
|
||||||
|
p_v = sub.add_parser("convert-video", aliases=["cv"], parents=[base_p], help="Change video format only")
|
||||||
|
p_v.add_argument("--video-codec", default="libx264",
|
||||||
|
help="Video codec to use (default: libx264, e.g. libx265, vp9)")
|
||||||
|
p_v.set_defaults(func=cmd_convert_video, command="convert-video")
|
||||||
|
|
||||||
# Remove Audio Command
|
# ----------------------------
|
||||||
p_ra = sub.add_parser("remove-audio", parents=[base_p], help="Remove one audio track via map exclusion")
|
# REMOVE SUBS
|
||||||
p_ra.add_argument("-oa", "--output-audio", required=False)
|
# ----------------------------
|
||||||
p_ra.add_argument("-a", "--audio-index", type=int, help="Track index within audio streams")
|
p_rs = sub.add_parser("remove-subs", aliases=["rs"], parents=[base_p], help="Strip all subtitle streams (-sn)")
|
||||||
p_ra.set_defaults(func=cmd_remove_audio_track)
|
p_rs.set_defaults(func=cmd_remove_subs, command="remove-subs")
|
||||||
|
|
||||||
# Downsize Command
|
# ----------------------------
|
||||||
p_ds = sub.add_parser("downsize", parents=[base_p], help="Scale video dimensions (-vf scale)")
|
# REMOVE AUDIO TRACK
|
||||||
p_ds.add_argument("--width", type=int, default=1280)
|
# ----------------------------
|
||||||
p_ds.add_argument("--height", type=int, default=720)
|
p_ra = sub.add_parser("remove-audio", aliases=["ra"], parents=[base_p], help="Remove one audio track")
|
||||||
p_ds.add_argument("--crf", type=int, default=23)
|
p_ra.add_argument("-oa", "--output-audio")
|
||||||
p_ds.set_defaults(func=cmd_downsize)
|
p_ra.add_argument("-a", "--audio-index", type=int)
|
||||||
|
p_ra.set_defaults(func=cmd_remove_audio_track, command="remove-audio")
|
||||||
|
|
||||||
# Filter Audio Command
|
# ----------------------------
|
||||||
p_fa = sub.add_parser("filter-audio", parents=[base_p], help="Apply complex audio enhancement chain")
|
# DOWNSIZE
|
||||||
p_fa.add_argument("-a", "--audio-index", type=int, help="Index of audio stream to filter (e.g. 0, 1, 2...)")
|
# ----------------------------
|
||||||
p_fa.set_defaults(func=cmd_filter_audio)
|
p_ds = sub.add_parser("downsize", aliases=["d"], parents=[base_p], help="Scale video dimensions (-vf scale)")
|
||||||
|
p_ds.add_argument("-w", "--width", type=int, help="width: eg 1080")
|
||||||
|
p_ds.add_argument("-he", "--height", type=int, help="height: eg 720")
|
||||||
|
p_ds.add_argument("-c" , "--crf", type=int, help="crf: eg 23")
|
||||||
|
p_ds.set_defaults(func=cmd_downsize, command="downsize")
|
||||||
|
|
||||||
# Cut Video Segment
|
# ----------------------------
|
||||||
p_c = sub.add_parser("cut", parents=[base_p], help="Cut X sec out of the video stream")
|
# FILTER AUDIO
|
||||||
p_c.add_argument("--start",required=True,help="Start time (e.g. 10, 10s, 1m5s, 0:1:5)")
|
# ----------------------------
|
||||||
p_c.add_argument("--duration",required=True,help="Duration (e.g. 30, 30s, 1m5s, 0:1:5)")
|
p_fa = sub.add_parser("filter-audio", aliases=["fa"], parents=[base_p], help="Apply audio enhancement chain")
|
||||||
p_c.set_defaults(func=cmd_cut_segment)
|
p_fa.add_argument("-a", "--audio-index", type=int)
|
||||||
|
p_fa.set_defaults(func=cmd_filter_audio, command="filter-audio")
|
||||||
|
|
||||||
# Set audio track as primary
|
# ----------------------------
|
||||||
p_pa = sub.add_parser("set-primary-audio", parents=[base_p], help="Set audiotrack X as primary track")
|
# CUT
|
||||||
p_pa.add_argument("-a", "--audio-index",type=int,help="Index of audio stream to make primary (e.g. 0, 1, 2...)")
|
# ----------------------------
|
||||||
p_pa.set_defaults(func=cmd_set_primary_audio)
|
p_c = sub.add_parser("cut", aliases=["c"], parents=[base_p], help="Cut X seconds out of video")
|
||||||
|
p_c.add_argument("--start")
|
||||||
|
p_c.add_argument("--duration")
|
||||||
|
p_c.set_defaults(func=cmd_cut_segment, command="cut")
|
||||||
|
|
||||||
# Switch primary audio
|
# ----------------------------
|
||||||
|
# SET PRIMARY AUDIO
|
||||||
|
# ----------------------------
|
||||||
|
p_pa = sub.add_parser("set-primary-audio", aliases=["spa"], parents=[base_p], help="Set primary audio track")
|
||||||
|
p_pa.add_argument("-a", "--audio-index", type=int)
|
||||||
|
p_pa.set_defaults(func=cmd_set_primary_audio, command="set-primary-audio")
|
||||||
|
|
||||||
|
# =========================================================
|
||||||
|
# PARSE
|
||||||
|
# =========================================================
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# ----------------------------
|
||||||
|
# COMMAND VALIDATION
|
||||||
|
# ----------------------------
|
||||||
if not hasattr(args, "func"):
|
if not hasattr(args, "func"):
|
||||||
parser.error("No command function bound.")
|
print("\nAvailable commands:")
|
||||||
# enforce output only for convert-av
|
|
||||||
if args.command in REQUIRES_OUTPUT and not args.output:
|
|
||||||
parser.error("--output is required for this command")
|
|
||||||
|
|
||||||
# Default output path generation logic
|
seen = set()
|
||||||
outputs = args.func(args)
|
for name, parser in sub.choices.items():
|
||||||
|
if id(parser) in seen:
|
||||||
|
continue
|
||||||
|
seen.add(id(parser))
|
||||||
|
print(f" - {name}")
|
||||||
|
|
||||||
if not isinstance(outputs, list):
|
args.command = ensure(None, "Command")
|
||||||
outputs = [outputs]
|
|
||||||
|
|
||||||
|
if args.command not in sub.choices:
|
||||||
|
parser.error("Unknown command")
|
||||||
|
|
||||||
|
# re-parse subcommand properly
|
||||||
|
sub_args = sub.choices[args.command].parse_args([])
|
||||||
|
args = argparse.Namespace( **vars(sub_args))
|
||||||
|
|
||||||
|
# ----------------------------
|
||||||
|
# INTERACTIVE FALLBACK (ensure ALL missing values)
|
||||||
|
# ----------------------------
|
||||||
if args.command != "test":
|
if args.command != "test":
|
||||||
try:
|
args.input = ensure(getattr(args, "input", None), f"Input file ({Path.cwd()})")
|
||||||
|
if not Path(args.input).is_file():
|
||||||
|
parser.error("Input file does not exist!")
|
||||||
|
|
||||||
|
if args.command in REQUIRES_OUTPUT and not getattr(args, "output", None):
|
||||||
|
args.output = ensure(getattr(args, "output", None), "Output file")
|
||||||
|
# ----------------------------
|
||||||
|
# COMMAND-SPECIFIC REQUIRED FIELDS
|
||||||
|
# ----------------------------
|
||||||
|
if args.command == "convert-av":
|
||||||
|
args.preset = ensure(getattr(args, "preset", None),
|
||||||
|
"Encoding speed/quality preset (default: medium, e.g. ultrafast, fast, slow, veryslow)")
|
||||||
|
args.quality = ensure(getattr(args, "quality", None),
|
||||||
|
"Output quality level (e.g. CRF value or bitrate depending on encoder)")
|
||||||
|
if args.command == "convert-av" or args.command == "convert-audio":
|
||||||
|
args.audio_codec = ensure(getattr(args, "audio_codec", None),
|
||||||
|
"Audio codec to use (default: aac, e.g. mp3, opus)")
|
||||||
|
if args.command == "convert-av" or args.command == "convert-video":
|
||||||
|
args.video_codec = ensure(getattr(args, "video_codec", None),
|
||||||
|
"Video codec to use (default: libx264, e.g. libx265, vp9)")
|
||||||
|
|
||||||
|
if args.command == "cut":
|
||||||
|
args.start = ensure(getattr(args, "start", None), "Start time (e.g. 10s, 1:00)")
|
||||||
|
args.duration = ensure(getattr(args, "duration", None), "Duration (e.g. 30s)")
|
||||||
|
|
||||||
|
if args.command == "downsize":
|
||||||
|
args.width = ensure(getattr(args, "width", None), "width: eg 1080")
|
||||||
|
args.height = ensure(getattr(args, "height", None), "height: eg 720")
|
||||||
|
args.crf = ensure(getattr(args, "crf", None), "crf: eg 23")
|
||||||
|
|
||||||
|
if args.command in ["filter-audio", "remove-audio", "set-primary-audio"]:
|
||||||
|
args.audio_index = ensure(getattr(args, "audio_index", None), "Audio index")
|
||||||
|
|
||||||
|
# ----------------------------
|
||||||
|
# EXECUTE COMMAND
|
||||||
|
# ----------------------------
|
||||||
|
try:
|
||||||
|
outputs = args.func(args)
|
||||||
|
|
||||||
|
if outputs is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if not isinstance(outputs, list):
|
||||||
|
outputs = [outputs]
|
||||||
|
|
||||||
|
if args.command != "test":
|
||||||
ffmpeg.run(
|
ffmpeg.run(
|
||||||
ffmpeg.merge_outputs(*outputs),
|
ffmpeg.merge_outputs(*outputs),
|
||||||
overwrite_output=True
|
overwrite_output=True
|
||||||
)
|
)
|
||||||
except ffmpeg.Error as e:
|
|
||||||
print("FFmpeg failed.\n")
|
except ffmpeg.Error as e:
|
||||||
if e.stderr:
|
print("FFmpeg failed.\n")
|
||||||
print(e.stderr.decode(errors="ignore"))
|
if e.stderr:
|
||||||
sys.exit(1)
|
print(e.stderr.decode(errors="ignore"))
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in new issue
Block a user