-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathFfmpeg.py
67 lines (59 loc) · 2.45 KB
/
Ffmpeg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python2
# encoding: utf-8
"""
Ffmpeg.py
Created by Ichabond on 2012-07-01.
Copyright (c) 2012 Baconseed. All rights reserved.
"""
import os
import subprocess
import sys
import re
from tempfile import mkdtemp
from hashlib import md5
class FFMpeg(object):
def __init__(self, filepath):
self.file = filepath
self.ffmpeg = None
self.duration = None
self.tempdir = mkdtemp(prefix="pythonbits-") + os.sep
def getDuration(self):
try:
self.ffmpeg = subprocess.Popen([r"ffmpeg", "-i", self.file], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
except OSError:
sys.stderr.write(
"Error: Ffmpeg not installed, refer to http://www.ffmpeg.org/download.html for installation")
exit(1)
ffmpeg_out = self.ffmpeg.stdout.read()
ffmpeg_duration = re.findall(r'Duration:\D(\d{2}):(\d{2}):(\d{2})', ffmpeg_out)
if not ffmpeg_duration:
# the odds of a filename collision on an md5 digest are very small
out_fn = '%s.txt' % md5(ffmpeg_out).hexdigest()
err_f = open(out_fn, 'wb')
err_f.write(ffmpeg_out)
err_f.close()
err_msg = ("Expected ffmpeg to mention 'Duration' but it did not;\n" +
"Please copy the contents of '%s' to http://pastebin.com/\n" +
" and send the pastebin link to the bB forum.") % out_fn
sys.stderr.write(err_msg)
dur = ffmpeg_duration[0]
dur_hh = int(dur[0])
dur_mm = int(dur[1])
dur_ss = int(dur[2])
self.duration = dur_hh * 3600 + dur_mm * 60 + dur_ss
def takeScreenshots(self, shots):
self.getDuration()
stops = range(20, 81, 60 / (shots - 1))
imgs = []
try:
for stop in stops:
imgs.append(self.tempdir + "screen%s.png" % stop)
subprocess.Popen([r"ffmpeg", "-ss", str((self.duration * stop) / 100), "-i", self.file, "-vframes", "1",
"-y", "-f", "image2", "-vf", """scale='max(sar,1)*iw':'max(1/sar,1)*ih'""", imgs[-1]],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
except OSError:
sys.stderr.write(
"Error: Ffmpeg not installed, refer to http://www.ffmpeg.org/download.html for installation")
exit(1)
return imgs