Skip to content

Instantly share code, notes, and snippets.

@husmen
Forked from oldo/video-metada-finder.py
Last active July 26, 2018 11:02
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 husmen/638b77e917f941e799a29932b9d9f252 to your computer and use it in GitHub Desktop.
Save husmen/638b77e917f941e799a29932b9d9f252 to your computer and use it in GitHub Desktop.
A python function utilising `ffprobe` to find any metadata related to a video file. Examples of what it can find include bitrate, fps, codec details, duration and many more. This gist returns the video height and width as an example.
#!/usr/local/bin/python3
import subprocess
import shlex
import json
import datetime
# function to find the resolution of the input video file
def findVideoMetada(pathToInputVideo):
cmd = "ffprobe -v quiet -print_format json -show_streams"
args = shlex.split(cmd)
args.append(pathToInputVideo)
# run the ffprobe process, decode stdout into utf-8 & convert to JSON
ffprobeOutput = subprocess.check_output(args).decode('utf-8')
ffprobeOutput = json.loads(ffprobeOutput)
# prints all the metadata available:
import pprint
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(ffprobeOutput['streams'][0])
# for example, find height, widthand duration
width = int(ffprobeOutput['streams'][0]['width'])
height = int(ffprobeOutput['streams'][0]['height'])
duration_ = float(ffprobeOutput['streams'][0]['duration'])
# change duration into a readable format
duration = str(datetime.timedelta(seconds=duration_))
# to find fps, you need to account for different situations where some metadata could be missing
try:
nb_frames = int(ffprobeOutput['streams'][0]['nb_frames'])
fps = nb_frames/duration_
except:
try:
avg_frame_rate = ffprobeOutput['streams'][0]['avg_frame_rate']
tmp = avg_frame_rate.split('/')
except:
r_frame_rate = ffprobeOutput['streams'][0]['r_frame_rate']
tmp = r_frame_rate.split('/')
fps = float(tmp[0])/float(tmp[1])
print(width, height, duration, fps)
return width, height, duration, fps
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment