-
Notifications
You must be signed in to change notification settings - Fork 55
/
ffprobe.py
266 lines (222 loc) · 8.6 KB
/
ffprobe.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""
Python wrapper for ffprobe command line tool. ffprobe must exist in the path.
"""
import functools
import operator
import os
import pipes
import platform
import re
import subprocess
from ffprobe.exceptions import FFProbeError
class FFProbe:
"""
FFProbe wraps the ffprobe command and pulls the data into an object form::
metadata=FFProbe('multimedia-file.mov')
"""
def __init__(self, path_to_video):
self.path_to_video = path_to_video
try:
with open(os.devnull, 'w') as tempf:
subprocess.check_call(["ffprobe", "-h"], stdout=tempf, stderr=tempf)
except FileNotFoundError:
raise IOError('ffprobe not found.')
if os.path.isfile(self.path_to_video) or self.path_to_video.startswith('http'):
if platform.system() == 'Windows':
cmd = ["ffprobe", "-show_streams", self.path_to_video]
else:
cmd = ["ffprobe -show_streams " + pipes.quote(self.path_to_video)]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stream = False
ignoreLine = False
self.streams = []
self.video = []
self.audio = []
self.subtitle = []
self.attachment = []
for line in iter(p.stdout.readline, b''):
line = line.decode('UTF-8', 'ignore')
if '[STREAM]' in line:
stream = True
ignoreLine = False
data_lines = []
elif '[/STREAM]' in line and stream:
stream = False
ignoreLine = False
# noinspection PyUnboundLocalVariable
self.streams.append(FFStream(data_lines))
elif stream:
if '[SIDE_DATA]' in line:
ignoreLine = True
elif '[/SIDE_DATA]' in line:
ignoreLine = False
elif ignoreLine == False:
data_lines.append(line)
self.metadata = {}
is_metadata = False
stream_metadata_met = False
for line in iter(p.stderr.readline, b''):
line = line.decode('UTF-8', 'ignore')
if 'Metadata:' in line and not stream_metadata_met:
is_metadata = True
elif 'Stream #' in line:
is_metadata = False
stream_metadata_met = True
elif is_metadata:
splits = line.split(',')
for s in splits:
m = re.search(r'(\w+)\s*:\s*(.*)$', s)
if m is not None:
# print(m.groups())
self.metadata[m.groups()[0]] = m.groups()[1].strip()
if '[STREAM]' in line:
stream = True
data_lines = []
elif '[/STREAM]' in line and stream:
stream = False
self.streams.append(FFStream(data_lines))
elif stream:
data_lines.append(line)
p.stdout.close()
p.stderr.close()
for stream in self.streams:
if stream.is_audio():
self.audio.append(stream)
elif stream.is_video():
self.video.append(stream)
elif stream.is_subtitle():
self.subtitle.append(stream)
elif stream.is_attachment():
self.attachment.append(stream)
else:
raise IOError('No such media file or stream is not responding: ' + self.path_to_video)
def __repr__(self):
return "<FFprobe: {metadata}, {video}, {audio}, {subtitle}, {attachment}>".format(**vars(self))
class FFStream:
"""
An object representation of an individual stream in a multimedia file.
"""
def __init__(self, data_lines):
for line in data_lines:
self.__dict__.update({key: value for key, value, *_ in [line.strip().split('=')]})
try:
self.__dict__['framerate'] = round(
functools.reduce(
operator.truediv, map(int, self.__dict__.get('avg_frame_rate', '').split('/'))
)
)
except ValueError:
self.__dict__['framerate'] = None
except ZeroDivisionError:
self.__dict__['framerate'] = 0
def __repr__(self):
if self.is_video():
template = "<Stream: #{index} [{codec_type}] {codec_long_name}, {framerate}, ({width}x{height})>"
elif self.is_audio():
template = "<Stream: #{index} [{codec_type}] {codec_long_name}, channels: {channels} ({channel_layout}), " \
"{sample_rate}Hz> "
elif self.is_subtitle() or self.is_attachment():
template = "<Stream: #{index} [{codec_type}] {codec_long_name}>"
else:
template = ''
return template.format(**self.__dict__)
def is_audio(self):
"""
Is this stream labelled as an audio stream?
"""
return self.__dict__.get('codec_type', None) == 'audio'
def is_video(self):
"""
Is the stream labelled as a video stream.
"""
return self.__dict__.get('codec_type', None) == 'video'
def is_subtitle(self):
"""
Is the stream labelled as a subtitle stream.
"""
return self.__dict__.get('codec_type', None) == 'subtitle'
def is_attachment(self):
"""
Is the stream labelled as a attachment stream.
"""
return self.__dict__.get('codec_type', None) == 'attachment'
def frame_size(self):
"""
Returns the pixel frame size as an integer tuple (width,height) if the stream is a video stream.
Returns None if it is not a video stream.
"""
size = None
if self.is_video():
width = self.__dict__['width']
height = self.__dict__['height']
if width and height:
try:
size = (int(width), int(height))
except ValueError:
raise FFProbeError("None integer size {}:{}".format(width, height))
else:
return None
return size
def pixel_format(self):
"""
Returns a string representing the pixel format of the video stream. e.g. yuv420p.
Returns none is it is not a video stream.
"""
return self.__dict__.get('pix_fmt', None)
def frames(self):
"""
Returns the length of a video stream in frames. Returns 0 if not a video stream.
"""
if self.is_video() or self.is_audio():
if self.__dict__.get('nb_frames', '') != 'N/A':
try:
frame_count = int(self.__dict__.get('nb_frames', ''))
except ValueError:
raise FFProbeError('None integer frame count')
else:
# When N/A is returned, set frame_count to 0 too
frame_count = 0
else:
frame_count = 0
return frame_count
def duration_seconds(self):
"""
Returns the runtime duration of the video stream as a floating point number of seconds.
Returns 0.0 if not a video stream.
"""
if self.is_video() or self.is_audio():
try:
duration = float(self.__dict__.get('duration', ''))
except ValueError:
raise FFProbeError('None numeric duration')
else:
duration = 0.0
return duration
def language(self):
"""
Returns language tag of stream. e.g. eng
"""
return self.__dict__.get('TAG:language', None)
def codec(self):
"""
Returns a string representation of the stream codec.
"""
return self.__dict__.get('codec_name', None)
def codec_description(self):
"""
Returns a long representation of the stream codec.
"""
return self.__dict__.get('codec_long_name', None)
def codec_tag(self):
"""
Returns a short representative tag of the stream codec.
"""
return self.__dict__.get('codec_tag_string', None)
def bit_rate(self):
"""
Returns bit_rate as an integer in bps
"""
try:
return int(self.__dict__.get('bit_rate', ''))
except ValueError:
raise FFProbeError('None integer bit_rate')