Skip to content

Instantly share code, notes, and snippets.

@arpruss
Last active July 19, 2023 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arpruss/067db7bb41a792c0ed2f870f94036fa1 to your computer and use it in GitHub Desktop.
Save arpruss/067db7bb41a792c0ed2f870f94036fa1 to your computer and use it in GitHub Desktop.
import os
import sys
import math
import subprocess
maxSize = 999999999
overlapSeconds = 6
def getDuration(filename):
pipe = subprocess.Popen(["ffprobe", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
for line in pipe.stderr:
if line.strip().startswith("Duration: "):
duration = line[12:].split(",")[0].split(":")
return float(duration[0])*3600+float(duration[1])*60+float(duration[0])
def trySplit(filename,parts):
print("Trying to split %s into %d parts." % (filename,parts))
duration = getDuration(filename)
print("Original duration: %g sec." % duration)
splitSize = int(math.ceil(duration / parts))
print("Aiming at %d sec parts." % splitSize)
position = 0
nameParts = os.path.splitext(filename)
for i in range(parts):
start = position
if i > 0:
start -= overlapSeconds
if start < 0:
start = 0
position += splitSize
cmd = ["ffmpeg"]
if i > 0:
cmd += ["-ss", "%d" % start]
if i + 1 < parts:
cmd += ["-to", "%d" % position]
outname = "%s-part%02d%s" % (nameParts[0],i+1,nameParts[1])
cmd += ["-i", filename, "-c", "copy", outname]
print(cmd)
try:
os.unlink(outname)
except:
pass
subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
size = os.stat(outname).st_size
print("Size: %d" % size)
if size > maxSize:
print("Too big!")
return False
return True
def help():
print("python videosplitter.py [--max maxByteSize] [--overlap overlapSeconds] filename")
print("(Note: need to have ffprobe and ffmpeg on the path.)");
sys.exit(0)
args = sys.argv[1:]
while args:
if not args[0].startswith("-"):
break
if args[0] == "--":
args = args[1:]
break
if args[0] == "--max":
maxSize = int(args[1])
args = args[2:]
elif args[0] == "--overlap":
overlapSeconds = int(args[1])
args = args[2:]
else:
help()
if not args:
help()
name = args[0]
size = os.stat(name).st_size
if size <= maxSize:
print("Size is already %d, which is good enough!" % size)
sys.exit(0)
partCount = int(math.ceil((float(size) / maxSize)))
while not trySplit(name,partCount):
partCount += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment