Last active
April 11, 2021 23:15
-
-
Save lancepioch/b6f7fc245ee21f60e6caf3734a73527e to your computer and use it in GitHub Desktop.
Encoder for Media
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, subprocess, json | |
codec = 'h264' # codec to re-encode video to | |
acceptable = ['hevc', 'h264', 'h265', 'libx264'] | |
skipExtensions = ['jpg', 'png', 'gif', 'txt', 'nfo', 'ds_store'] | |
directory = "" | |
# Make sure a directory is chosen | |
if not directory: | |
directory = input("Enter directory: ") | |
def getVideoDetails(path): | |
cmd = ['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams'] | |
proc = subprocess.Popen(cmd + [path], shell=True, stdout=subprocess.PIPE) | |
return json.loads(proc.stdout.read()) | |
for (dirpath, dirnames, filenames) in os.walk(directory): | |
for filename in filenames: | |
path = os.path.join(dirpath, filename) | |
extension = filename.split('.')[-1].lower() | |
if extension in skipExtensions: | |
continue | |
data = getVideoDetails(path) | |
if not 'streams' in data: | |
print("[Info] {} - Skipping non video file".format(filename)) | |
continue | |
streams = data['streams'] | |
for stream in streams: | |
if stream['codec_type'] != 'video': | |
# Skip Non Video Stream | |
continue | |
dimensions = str(stream['width']) + 'x' + str(stream['height']) | |
if stream['codec_name'] in acceptable: | |
# Skip Already Encoded Video Stream | |
print("[Info] {} ({}) - Skipping video stream #{}, already is: {}".format(filename, dimensions, stream['index'], stream['codec_name'])) | |
break | |
newpath = os.path.join(dirpath, 'out-' + filename) | |
print("[Info] {} ({}) - Encoding video stream #{} to {} from {}".format(filename, dimensions, stream['index'], codec, stream['codec_name'])) | |
encodeCmd = ['ffmpeg', '-y', '-i', path, '-c:v', codec, '-crf', '18', '-preset', 'slow', '-c:a', 'copy', newpath] | |
subprocess.call(encodeCmd) | |
data = getVideoDetails(newpath) | |
if not 'streams' in data: | |
print("[Error] {} - Encoded video file is not a valid video file".format(filename)) | |
break | |
# Overwrite old video file with new video file | |
os.replace(newpath, path) | |
# No need to check rest of streams | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment