-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path__init__.py
More file actions
337 lines (284 loc) · 11.5 KB
/
Copy path__init__.py
File metadata and controls
337 lines (284 loc) · 11.5 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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""FFmpeg I/O interface
Transcode media file to another format/codecs
---------------------------------------------
:py:func:`ffmpegio.transcode()`
Stream Read/Write
-----------------
ffmpegio.open()
Block Read/Write/Filter Functions
---------------------------------
`ffmpegio.video.read()`
`ffmpegio.video.write()`
`ffmpegio.video.filter()`
`ffmpegio.image.read()`
`ffmpegio.image.write()`
`ffmpegio.image.filter()`
`ffmpegio.audio.read()`
`ffmpegio.audio.write()`
`ffmpegio.audio.filter()`
`ffmpegio.media.read()`
"""
from contextlib import contextmanager
import logging
logger = logging.getLogger("ffmpegio")
logger.addHandler(logging.NullHandler())
from . import path, plugins
# register builtin plugins and external plugins found in site-packages
plugins.initialize()
# initialize the paths
try:
path.find()
except Exception as e:
logger.warning(str(e))
def __getattr__(name):
if name == "ffmpeg_ver":
return path.FFMPEG_VER
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
from . import ffmpegprocess
from .errors import FFmpegError
from .utils.concat import FFConcat
from .filtergraph import Graph as FilterGraph
from . import devices, ffmpegprocess, caps, probe, audio, image, video, media
from .transcode import transcode
from . import streams as _streams
from .utils.parser import FLAG
# fmt:off
__all__ = ["ffmpeg_info", "get_path", "set_path", "is_ready", "ffmpeg", "ffprobe",
"transcode", "caps", "probe", "audio", "image", "video", "media", "devices",
"open", "ffmpegprocess", "FFmpegError", "FilterGraph", "FFConcat"]
# fmt:on
__version__ = "0.9.1"
ffmpeg_info = path.versions
set_path = path.find
get_path = path.where
is_ready = path.found
ffmpeg = path.ffmpeg
ffprobe = path.ffprobe
@contextmanager
def open(
url_fg,
mode="",
rate_in=None,
shape_in=None,
dtype_in=None,
rate=None,
shape=None,
**kwds,
):
"""Open a multimedia file/stream for read/write
:param url_fg: URL of the media source/destination for file read/write or filtergraph definition
for filter operation.
:type url_fg: str or seq(str)
:param mode: specifies the mode in which the FFmpeg is used, defaults to None
:type mode: str, optional
:param rate_in: (filter specific) input frame rate (video write) or sample rate (audio
write), defaults to None
:type rate_in: Fraction, float, int, optional
:param shape_in: (write and filter specific) input video frame size (height x width [x ncomponents]),
or audio sample size (channels,), defaults to None
:type shape_in: seq of int, optional
:param dtype_in: (write and filter specific) input data type, defaults to None
:type dtype_in: str, optional
:param rate: (filter specific) output frame rate (video write) or sample rate (audio
write), defaults to None
:type rate: Fraction, float, int, optional
:param dtype: (read and filter specific) output data type, defaults to None
:type dtype: str, optional
:param shape: (read and filter specific) output video frame size (height x width [x ncomponents]),
or audio sample size (channels,), defaults to None
:type shape: seq of int, optional
:param \\**options: FFmpeg options, append '_in' for input option names (see :doc:`options`)
:type \\**options: dict, optional
:yields: ffmpegio stream object
Start FFmpeg and open I/O link to it to perform read/write/filter operation and return
a corresponding stream object. If the file cannot be opened, an error is raised.
See Reading and Writing Files for more examples of how to use this function.
`open()` yields a ffmpegio's stream object and automatically closes it
when goes out of the context
:Examples:
Open an MP4 file and process all the frames::
with ffmpegio.open('video_source.mp4') as f:
frame = f.read()
while frame:
# process the captured frame data
frame = f.read()
Read an audio stream of MP4 file and write it to a FLAC file as samples
are decoded::
with ffmpegio.open('video_source.mp4','ra') as rd:
fs = rd.sample_rate
with ffmpegio.open('video_dst.flac','wa',rate_in=fs) as wr:
frame = rd.read()
while frame:
wr.write(frame)
frame = rd.read()
:Additional Notes:
`url_fg` can be a string specifying either the pathname (absolute or relative to the current
working directory) of the media target (file or streaming media) to be opened or a string describing
the filtergraph to be implemented. Its interpretation depends on the `mode` argument.
`mode` is an optional string that specifies the mode in which the FFmpeg is opened.
==== ===================================================
Mode Description
==== ===================================================
'r' read from url (default)
'w' write to url
'f' filter data defined by fg
'v' operate on video stream, 'vv' if multi-video reader
'a' operate on audio stream, 'aa' if multi-audio reader
==== ===================================================
The default operating mode is dictated by `rate` and `rate_in` arguments. The 'f' mode is selected
if both `rate` and `rate_in` are given while the 'w' mode is selected if only `rate_in` without
`rate` argument is given. Otherwise, it defaults to 'r'.
If no media type ('v' or 'a') is specified, it selects the first stream of the media in read mode.
For write and filter modes, the length of `shape_in` if given will be used for the detection:
'a' if 1 else 'v'. If cannot be autodetected, ValueError will be raised.
`rate` and `rate_in`: Video frame rates shall be given in frames/second and
may be given as a number, string, or `fractions.Fraction`. Audio sample rate in
samples/second (per channel) and shall be given as an integer or string.
Optional `shape` or `shape_in` for video defines the video frame size and
number of components with a 2 or 3 element sequence: `(width, height[, ncomp])`.
The number of components and other optional `dtype` (or `dtype_in`) implicitly
define the pixel format (FFmpeg pix_fmt option):
===== ===== ========= ===================================
ncomp dtype pix_fmt Description
===== ===== ========= ===================================
1 \|u8 gray grayscale
1 <u2 gray10le 10-bit grayscale
1 <u2 gray12le 12-bit grayscale
1 <u2 gray14le 14-bit grayscale
1 <u2 gray16le 16-bit grayscale (default <u2 choice)
1 <f4 grayf32le floating-point grayscale
2 \|u1 ya8 grayscale with alpha channel
2 <u2 ya16le 16-bit grayscale with alpha channel
3 \|u1 rgb24 RGB
3 <u2 rgb48le 16-bit RGB
4 \|u1 rgba RGB with alpha transparency channel
4 <u2 rgba64le 16-bit RGB with alpha channel
===== ===== ========= ===================================
For audio stream, single-element seq argument, `shape` or `shape_in`,
specifies the number of channels while `dtype` and `dtype_in` determines
the sample format (FFmpeg sample_fmt option):
====== ==========
dtype sample_fmt
====== ==========
\|u1 u8
<i2 s16
<i4 s32
<f4 flt
<f8 dbl
====== ==========
If dtypes and shapes are not specified at the time of opening, they will
be set during the first write/filter operation using the input data.
In addition, `open()` accepts the standard option keyword arguments.
"""
is_fg = isinstance(url_fg, FilterGraph)
if isinstance(url_fg, str):
is_fg = kwds.get("f_in", None) == "lavfi"
url_fg = (url_fg,)
audio = "a" in mode
video = "v" in mode
read = "r" in mode
write = "w" in mode
filter = "f" in mode
# backwards = "b" in mode
unk = set(mode) - set("avrwf")
if unk:
raise Exception(
f"Invalid FFmpeg streaming mode: {mode}. Unknown mode {unk} specified."
)
if read + write + filter > 1:
raise Exception(
f"Invalid FFmpeg streaming mode: {mode}. Only 1 of 'rwf' may be specified."
)
if (read or write or filter):
# convert unused rate argument to ffmpeg option
if read and rate_in is not None:
kwds['r_in' if video else 'ar_in'] = rate_in
rate_in = None
elif write and rate is not None:
kwds['r' if video else 'ar'] = rate
rate = None
else:
# auto-detect operation
if rate_in is None:
read = True
elif rate is None:
write = True
else:
filter = True
# auto-detect type
if not (audio or video):
if is_fg:
raise ValueError(
"media type must be specified to read from an Input filtergraph"
)
elif read:
for url in url_fg:
try:
info = probe.streams_basic(url, entries=("codec_type",))
except:
raise ValueError(f"cannot auto-detect media type of {url}")
for inf in info:
t = inf["codec_type"]
if t == "video" and not video:
video = True
elif t == "audio" and not audio:
audio = True
if video and audio:
break
else:
if shape_in is not None:
audio = len(shape_in) < 2
elif shape is not None:
audio = len(shape) < 2
else:
# TODO identify based on file extension
raise ValueError(f"cannot auto-detect media type")
video = not audio
elif read:
# if audio or video is set multiple times, use avi reader
if audio and not video:
video = audio and sum((1 for m in mode if m == "a")) > 1
elif video and not audio:
audio = video and sum((1 for m in mode if m == "v")) > 1
elif write and is_fg:
ValueError("Cannot write to a filtergraph.")
try:
StreamClass = {
1: {
0: _streams.SimpleAudioReader,
1: _streams.SimpleAudioWriter,
2: _streams.SimpleAudioFilter,
},
2: {
0: _streams.SimpleVideoReader,
1: _streams.SimpleVideoWriter,
2: _streams.SimpleVideoFilter,
},
3: {
0: _streams.AviMediaReader,
},
}[audio + 2 * video][write + 2 * filter]
except:
raise Exception(f"Invalid/unsupported FFmpeg streaming mode: {mode}.")
if len(url_fg) > 1 and not StreamClass.multi_read:
raise Exception(f'Multi-input streaming is not supported in "{mode}" mode')
# add other info to the arguments
args = (*url_fg,) if read else (*url_fg, rate_in)
for k, v in (
("dtype_in", dtype_in),
("shape_in", shape_in),
("rate", rate),
("shape", shape),
):
if v is not None:
kwds[k] = v
# instantiate the streaming object
# TODO wrap in try-catch if AV stream fails to try a multi-stream version
stream = StreamClass(*args, **kwds)
try:
yield stream
finally:
# terminate FFmpeg
stream.close()