Skip to content

Instantly share code, notes, and snippets.

@pixelchai
Created April 28, 2020 14:24
Show Gist options
  • Save pixelchai/2b780a1e2fbea76cf0e242553680c369 to your computer and use it in GitHub Desktop.
Save pixelchai/2b780a1e2fbea76cf0e242553680c369 to your computer and use it in GitHub Desktop.
import math
import subprocess
import os
import sys
import shutil
SEC_LENGTH = 30 # section length - actual time (s)
SEC_SEP = 120 # time spetween sections - actual time (s)
SPEEDUP = 20
FPS_SOURCE = 60
FPS_FINAL = 25
TMP_DIR = "tmp"
PART_LENGTH = 59 # time - output time (s)
def ffmpeg(cmd):
print("ffmpeg command: {}".format(cmd))
subprocess.run("{} -nostdin -y -hide_banner".format(cmd), shell=True)
def del_temp():
if os.path.exists(TMP_DIR) and os.path.isdir(TMP_DIR):
shutil.rmtree(TMP_DIR)
files = [x for x in os.listdir() if os.path.splitext(x)[1] in [".mkv", ".flv"]]
if len(files) != 1:
print('invalid number of files')
input()
sys.exit()
file = files[0]
# ffmpeg -i "2019-11-17 03-08-45.mkv" -vf fps=30/x tmp/%010d.png # x speed up amount (x times)
# ffmpeg -y -i tmp/%010d.png -c:v libx264rgb -crf 23 tmp1.mp4
# 1:16 --> 00:15
# when fps=2: 1:16 --> 00:06
del_temp()
os.makedirs(TMP_DIR)
ffmpeg('ffmpeg -i "{}" -vf fps={}/{} {}/%010d.png'.format(file, FPS_SOURCE, SPEEDUP, TMP_DIR))
images = os.listdir(TMP_DIR)
selected_images = []
discarded_images = []
t = 0
in_sec = True
for image in images:
if not in_sec:
discarded_images.append(image)
if t >= SEC_SEP:
in_sec = True
t = 0
else:
selected_images.append(image)
if t >= SEC_LENGTH:
in_sec = False
t = 0
t += SPEEDUP/FPS_FINAL
for image in discarded_images:
os.remove(os.path.join(TMP_DIR, image))
for i, image in enumerate(selected_images):
os.rename(os.path.join(TMP_DIR, image), os.path.join(TMP_DIR, "{:010d}{}".format(i, os.path.splitext(image)[1])))
ffmpeg("ffmpeg -y -i {}/%010d.png -c:v libx264 -pix_fmt yuv420p -crf 23 out.mp4".format(TMP_DIR))
# 10,30,20 => 1:02:12 -> 00:00:57
# 30,120,20 => 2:10:51 -> 00:01:35
# split into parts for insta
images = os.listdir(TMP_DIR)
folders = []
part_no = 0
i = 0
os.mkdir(os.path.join(TMP_DIR, str(part_no)))
for image in images:
if i >= PART_LENGTH*FPS_FINAL:
part_no += 1
os.mkdir(os.path.join(TMP_DIR, str(part_no)))
i = 0
os.rename(os.path.join(TMP_DIR, image), os.path.join(TMP_DIR, str(part_no), '{:010d}{}'.format(i, os.path.splitext(image)[1])))
i += 1
for i in range(part_no+1):
ffmpeg("ffmpeg -y -i {}/%010d.png -vf scale=1080:-1 -c:v libx264 -pix_fmt yuv420p -crf 23 out{}.mp4".format(os.path.join(TMP_DIR, str(i)), str(i)))
del_temp()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment