forked from mueslo/pythonBits
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathffmpeg.py
More file actions
60 lines (50 loc) · 1.87 KB
/
Copy pathffmpeg.py
File metadata and controls
60 lines (50 loc) · 1.87 KB
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
# -*- coding: utf-8 -*-
"""
ffmpeg.py
Created by Ichabond on 2012-07-01.
Copyright (c) 2012 Baconseed. All rights reserved.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import * # noqa: F401, F403
import os
import subprocess
import re
from tempfile import mkdtemp
class FfmpegException(Exception):
pass
class FFMpeg(object):
def __init__(self, filepath):
self.file = filepath
self.ffmpeg = None
self.tempdir = mkdtemp(prefix="pythonbits-") + os.sep
def duration(self):
self.ffmpeg = subprocess.Popen([r"ffmpeg", "-i", self.file],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
ffmpeg_out = self.ffmpeg.stdout.read().decode('utf8')
ffmpeg_duration = re.findall(
r'Duration:\D(\d{2}):(\d{2}):(\d{2})', ffmpeg_out)
if not ffmpeg_duration:
raise FfmpegException("ffmpeg output did not contain 'Duration'")
dur = ffmpeg_duration[0]
dur_hh = int(dur[0])
dur_mm = int(dur[1])
dur_ss = int(dur[2])
return dur_hh * 3600 + dur_mm * 60 + dur_ss
def take_screenshots(self, num_screenshots):
duration = self.duration()
stops = range(20, 81, 60 // (num_screenshots - 1))
imgs = []
for stop in stops:
imgs.append(os.path.join(self.tempdir, "screen%s.png" % stop))
subprocess.Popen(
[r"ffmpeg",
"-ss", str((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()
return imgs