Skip to content

Instantly share code, notes, and snippets.

@pixelchai
Created May 9, 2020 20:39
Show Gist options
  • Save pixelchai/6f7b4af40300683c4c80ce995217dcc4 to your computer and use it in GitHub Desktop.
Save pixelchai/6f7b4af40300683c4c80ce995217dcc4 to your computer and use it in GitHub Desktop.
import subprocess
import os
import sys
import shutil
SEC_LENGTH = 30 # section length - actual time (s)
SEC_SEP = 120 # time petween sections - actual time (s)
SPEEDUP = 1
FPS_FINAL = 15
PART_LENGTH = 59 # time - output time (s)
DIR_TMP = "tmp"
DIR_CLIPS = os.path.join(DIR_TMP, "clips")
DIR_OUT = "output"
DIR_INP = "input"
def run(cmd):
print("> "+str(cmd))
subprocess.run(cmd, shell=True)
def run_out(command):
print("> " + str(command))
result = subprocess.run(command, stdout=subprocess.PIPE, shell=True)
output = result.stdout.decode('utf-8').rstrip()
print("= " + str(output))
return output
def ffmpeg(params):
run("ffmpeg -nostdin -y -hide_banner {}".format(params))
def concat(video_paths, output):
run("mkvmerge -o {} {}".format(
output,
" +".join(['"' + str(x) + '"' for x in video_paths])
))
def clip(input_path, start, duration, output_path):
ffmpeg("-ss {1} -i \"{0}\" -t {2} \"{3}\"".format(
input_path,
start,
duration,
output_path
))
def del_temp():
if os.path.exists(DIR_TMP) and os.path.isdir(DIR_TMP):
shutil.rmtree(DIR_TMP)
def get_length(path):
# https://superuser.com/a/945604/581663
return float(run_out("ffprobe -v error -show_entries "
"format=duration -of default=noprint_wrappers=1:nokey=1 \"{}\""
.format(path)))
del_temp()
os.makedirs(DIR_TMP)
os.makedirs(DIR_OUT, exist_ok=True)
input_files = []
for file_name in os.listdir(DIR_INP):
input_files.append(os.path.join(DIR_INP, file_name))
merged_file = os.path.join(DIR_TMP, "merged.mkv")
concat(input_files, merged_file)
merged_length = get_length(merged_file)
# split videos
os.makedirs(DIR_CLIPS, exist_ok=True)
clip_no = 0
cur_time = 0
while cur_time < merged_length:
clip(merged_file, cur_time, SEC_LENGTH, os.path.join(DIR_CLIPS, "{:05d}.mkv".format(clip_no)))
cur_time += SEC_LENGTH + SEC_SEP
clip_no += 1
# merge videos into timelapsed file
timelapsed_file = os.path.join(DIR_TMP, "timelapsed.mkv")
concat([
os.path.join(DIR_CLIPS, "{:05d}.mkv".format(i)) for i in range(clip_no)
], timelapsed_file)
out_file = os.path.join(DIR_OUT, "output.mkv")
ffmpeg("-r {0} -i \"{1}\" -an -vf \"setpts=PTS/{0}\" \"{2}\"".format(FPS_FINAL, timelapsed_file, out_file))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment