Skip to content

Instantly share code, notes, and snippets.

@cboddy
Created November 9, 2023 22:15
Show Gist options
  • Save cboddy/2ebedd4bf4d70cd1a8333d05a5d7c7d9 to your computer and use it in GitHub Desktop.
Save cboddy/2ebedd4bf4d70cd1a8333d05a5d7c7d9 to your computer and use it in GitHub Desktop.
Wrap ffmpeg to concat parts of a video file together using ffmpeg
#!/usr/bin/env python3
import subprocess
from typing import Tuple
import tempfile
import argparse
def to_concat_input(from_to_seconds: Tuple[Tuple[int]], in_path: str) -> str:
return "\n".join(
[
f"""file '{in_path}'
inpoint {from_sec}
outpoint {to_sec}"""
for from_sec, to_sec in from_to_seconds
]
)
def ffmpeg(from_to_seconds: Tuple[Tuple[int]], in_path: str, out_path: str):
concat_path = tempfile.mktemp()
concat_input = to_concat_input(from_to_seconds, in_path)
with open(concat_path, "w") as f:
f.write(concat_input)
subprocess.Popen(f"ffmpeg -f concat -safe 0 -i {concat_path} -c copy {out_path}".split(), shell=False)
# requires ffmpeg
def main():
parser = argparse.ArgumentParser("Wrap ffmpeg to concat parts of a video file together using ffmpeg.")
parser.add_argument("-i", help="Input video path.")
parser.add_argument("-o", help="Output video path.")
parser.add_argument("from_to", help="start and endpoints in seconds to cut (must be sorted).", nargs="+", type=int)
args= parser.parse_args()
assert len(args.from_to) and len(args.from_to) % 2== 0, "from_to must have a multiple of 2 arguments"
assert sorted(args.from_to) == args.from_to, "from_to must be ffmpeg to sorted"
from_to = list(zip(*(args.from_to[::2], args.from_to[1::2])))
ffmpeg(from_to, args.i, args.o)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment