| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Read/Write video using FFMPEG |
| 5 |
|
| 6 |
.. note:: |
| 7 |
We are in the process of (slowly) replacing this plugin with a new one that |
| 8 |
is based on `pyav <https://pyav.org/docs/stable/>`_. It is faster and more |
| 9 |
flexible than the plugin documented here. Check the :mod:`pyav |
| 10 |
plugin's documentation <imageio.plugins.pyav>` for more information about |
| 11 |
this plugin. |
| 12 |
|
| 13 |
Backend Library: https://github.com/imageio/imageio-ffmpeg |
| 14 |
|
| 15 |
.. note:: |
| 16 |
To use this plugin you have to install its backend:: |
| 17 |
|
| 18 |
pip install imageio[ffmpeg] |
| 19 |
|
| 20 |
|
| 21 |
The ffmpeg format provides reading and writing for a wide range of movie formats |
| 22 |
such as .avi, .mpeg, .mp4, etc. as well as the ability to read streams from |
| 23 |
webcams and USB cameras. It is based on ffmpeg and is inspired by/based `moviepy |
| 24 |
<https://github.com/Zulko/moviepy/>`_ by Zulko. |
| 25 |
|
| 26 |
Parameters for reading |
| 27 |
---------------------- |
| 28 |
fps : scalar |
| 29 |
The number of frames per second of the input stream. Default None (i.e. |
| 30 |
read at the file's native fps). One can use this for files with a |
| 31 |
variable fps, or in cases where imageio is unable to correctly detect |
| 32 |
the fps. In case of trouble opening camera streams, it may help to set an |
| 33 |
explicit fps value matching a framerate supported by the camera. |
| 34 |
loop : bool |
| 35 |
If True, the video will rewind as soon as a frame is requested |
| 36 |
beyond the last frame. Otherwise, IndexError is raised. Default False. |
| 37 |
Setting this to True will internally call ``count_frames()``, |
| 38 |
and set the reader's length to that value instead of inf. |
| 39 |
size : str | tuple |
| 40 |
The frame size (i.e. resolution) to read the images, e.g. |
| 41 |
(100, 100) or "640x480". For camera streams, this allows setting |
| 42 |
the capture resolution. For normal video data, ffmpeg will |
| 43 |
rescale the data. |
| 44 |
dtype : str | type |
| 45 |
The dtype for the output arrays. Determines the bit-depth that |
| 46 |
is requested from ffmpeg. Supported dtypes: uint8, uint16. |
| 47 |
Default: uint8. |
| 48 |
pixelformat : str |
| 49 |
The pixel format for the camera to use (e.g. "yuyv422" or |
| 50 |
"gray"). The camera needs to support the format in order for |
| 51 |
this to take effect. Note that the images produced by this |
| 52 |
reader are always RGB. |
| 53 |
input_params : list |
| 54 |
List additional arguments to ffmpeg for input file options. |
| 55 |
(Can also be provided as ``ffmpeg_params`` for backwards compatibility) |
| 56 |
Example ffmpeg arguments to use aggressive error handling: |
| 57 |
['-err_detect', 'aggressive'] |
| 58 |
output_params : list |
| 59 |
List additional arguments to ffmpeg for output file options (i.e. the |
| 60 |
stream being read by imageio). |
| 61 |
print_info : bool |
| 62 |
Print information about the video file as reported by ffmpeg. |
| 63 |
|
| 64 |
Parameters for writing |
| 65 |
---------------------- |
| 66 |
fps : scalar |
| 67 |
The number of frames per second. Default 10. |
| 68 |
codec : str |
| 69 |
the video codec to use. Default 'libx264', which represents the |
| 70 |
widely available mpeg4. Except when saving .wmv files, then the |
| 71 |
defaults is 'msmpeg4' which is more commonly supported for windows |
| 72 |
quality : float | None |
| 73 |
Video output quality. Default is 5. Uses variable bit rate. Highest |
| 74 |
quality is 10, lowest is 0. Set to None to prevent variable bitrate |
| 75 |
flags to FFMPEG so you can manually specify them using output_params |
| 76 |
instead. Specifying a fixed bitrate using 'bitrate' disables this |
| 77 |
parameter. |
| 78 |
bitrate : int | None |
| 79 |
Set a constant bitrate for the video encoding. Default is None causing |
| 80 |
'quality' parameter to be used instead. Better quality videos with |
| 81 |
smaller file sizes will result from using the 'quality' variable |
| 82 |
bitrate parameter rather than specifying a fixed bitrate with this |
| 83 |
parameter. |
| 84 |
pixelformat: str |
| 85 |
The output video pixel format. Default is 'yuv420p' which most widely |
| 86 |
supported by video players. |
| 87 |
input_params : list |
| 88 |
List additional arguments to ffmpeg for input file options (i.e. the |
| 89 |
stream that imageio provides). |
| 90 |
output_params : list |
| 91 |
List additional arguments to ffmpeg for output file options. |
| 92 |
(Can also be provided as ``ffmpeg_params`` for backwards compatibility) |
| 93 |
Example ffmpeg arguments to use only intra frames and set aspect ratio: |
| 94 |
['-intra', '-aspect', '16:9'] |
| 95 |
ffmpeg_log_level: str |
| 96 |
Sets ffmpeg output log level. Default is "warning". |
| 97 |
Values can be "quiet", "panic", "fatal", "error", "warning", "info" |
| 98 |
"verbose", or "debug". Also prints the FFMPEG command being used by |
| 99 |
imageio if "info", "verbose", or "debug". |
| 100 |
macro_block_size: int |
| 101 |
Size constraint for video. Width and height, must be divisible by this |
| 102 |
number. If not divisible by this number imageio will tell ffmpeg to |
| 103 |
scale the image up to the next closest size |
| 104 |
divisible by this number. Most codecs are compatible with a macroblock |
| 105 |
size of 16 (default), some can go smaller (4, 8). To disable this |
| 106 |
automatic feature set it to None or 1, however be warned many players |
| 107 |
can't decode videos that are odd in size and some codecs will produce |
| 108 |
poor results or fail. See https://en.wikipedia.org/wiki/Macroblock. |
| 109 |
audio_path : str | None |
| 110 |
Audio path of any audio that needs to be written. Defaults to nothing, |
| 111 |
so no audio will be written. Please note, when writing shorter video |
| 112 |
than the original, ffmpeg will not truncate the audio track; it |
| 113 |
will maintain its original length and be longer than the video. |
| 114 |
audio_codec : str | None |
| 115 |
The audio codec to use. Defaults to nothing, but if an audio_path has |
| 116 |
been provided ffmpeg will attempt to set a default codec. |
| 117 |
|
| 118 |
Notes |
| 119 |
----- |
| 120 |
If you are using anaconda and ``anaconda/ffmpeg`` you will not be able to |
| 121 |
encode/decode H.264 (likely due to licensing concerns). If you need this |
| 122 |
format on anaconda install ``conda-forge/ffmpeg`` instead. |
| 123 |
|
| 124 |
You can use the ``IMAGEIO_FFMPEG_EXE`` environment variable to force using a |
| 125 |
specific ffmpeg executable. |
| 126 |
|
| 127 |
To get the number of frames before having read them all, you can use the |
| 128 |
``reader.count_frames()`` method (the reader will then use |
| 129 |
``imageio_ffmpeg.count_frames_and_secs()`` to get the exact number of frames, |
| 130 |
note that this operation can take a few seconds on large files). Alternatively, |
| 131 |
the number of frames can be estimated from the fps and duration in the meta data |
| 132 |
(though these values themselves are not always present/reliable). |
| 133 |
|
| 134 |
""" |
| 135 |
|
| 136 |
import re |
| 137 |
import sys |
| 138 |
import time |
| 139 |
import logging |
| 140 |
import platform |
| 141 |
import threading |
| 142 |
import subprocess as sp |
| 143 |
import imageio_ffmpeg |
| 144 |
|
| 145 |
import numpy as np |
| 146 |
|
| 147 |
from ..core import Format, image_as_uint |
| 148 |
|
| 149 |
logger = logging.getLogger(__name__) |
| 150 |
|
| 151 |
|
| 152 |
if sys.platform.startswith("win"): |
| 153 |
CAM_FORMAT = "dshow" |
| 154 |
elif sys.platform.startswith("linux"): |
| 155 |
CAM_FORMAT = "video4linux2" |
| 156 |
elif sys.platform.startswith("darwin"): |
| 157 |
CAM_FORMAT = "avfoundation" |
| 158 |
else: |
| 159 |
CAM_FORMAT = "unknown-cam-format" |
| 160 |
|
| 161 |
|
| 162 |
def download(directory=None, force_download=False): |
| 163 |
raise RuntimeError( |
| 164 |
"imageio.ffmpeg.download() has been deprecated. " |
| 165 |
"Use 'pip install imageio-ffmpeg' instead.'" |
| 166 |
) |
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
def get_exe(): |
| 171 |
"""Wrapper for imageio_ffmpeg.get_ffmpeg_exe()""" |
| 172 |
|
| 173 |
return imageio_ffmpeg.get_ffmpeg_exe() |
| 174 |
|
| 175 |
|
| 176 |
def get_version(): |
| 177 |
"""Return the version of imageio-ffmpeg in tuple.""" |
| 178 |
return tuple(map(int, imageio_ffmpeg.__version__.split("."))) |
| 179 |
|
| 180 |
|
| 181 |
class FfmpegFormat(Format): |
| 182 |
"""Read/Write ImageResources using FFMPEG. |
| 183 |
|
| 184 |
See :mod:`imageio.plugins.ffmpeg` |
| 185 |
""" |
| 186 |
|
| 187 |
def _can_read(self, request): |
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
if re.match(r"<video(\d+)>", request.filename): |
| 192 |
return True |
| 193 |
|
| 194 |
|
| 195 |
if request.extension in self.extensions: |
| 196 |
return True |
| 197 |
|
| 198 |
def _can_write(self, request): |
| 199 |
if request.extension in self.extensions: |
| 200 |
return True |
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
class Reader(Format.Reader): |
| 205 |
_frame_catcher = None |
| 206 |
_read_gen = None |
| 207 |
|
| 208 |
def _get_cam_inputname(self, index): |
| 209 |
if sys.platform.startswith("linux"): |
| 210 |
return "/dev/" + self.request._video[1:-1] |
| 211 |
|
| 212 |
elif sys.platform.startswith("win"): |
| 213 |
|
| 214 |
ffmpeg_api = imageio_ffmpeg |
| 215 |
cmd = [ |
| 216 |
ffmpeg_api.get_ffmpeg_exe(), |
| 217 |
"-list_devices", |
| 218 |
"true", |
| 219 |
"-f", |
| 220 |
CAM_FORMAT, |
| 221 |
"-i", |
| 222 |
"dummy", |
| 223 |
] |
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
completed_process = sp.run( |
| 231 |
cmd, |
| 232 |
stdout=sp.PIPE, |
| 233 |
stderr=sp.PIPE, |
| 234 |
encoding="utf-8", |
| 235 |
shell=True, |
| 236 |
check=False, |
| 237 |
) |
| 238 |
|
| 239 |
|
| 240 |
try: |
| 241 |
name = parse_device_names(completed_process.stderr)[index] |
| 242 |
except IndexError: |
| 243 |
raise IndexError("No ffdshow camera at index %i." % index) |
| 244 |
return "video=%s" % name |
| 245 |
|
| 246 |
elif sys.platform.startswith("darwin"): |
| 247 |
|
| 248 |
|
| 249 |
name = str(index) |
| 250 |
return name |
| 251 |
|
| 252 |
else: |
| 253 |
return "??" |
| 254 |
|
| 255 |
def _open( |
| 256 |
self, |
| 257 |
loop=False, |
| 258 |
size=None, |
| 259 |
dtype=None, |
| 260 |
pixelformat=None, |
| 261 |
print_info=False, |
| 262 |
ffmpeg_params=None, |
| 263 |
input_params=None, |
| 264 |
output_params=None, |
| 265 |
fps=None, |
| 266 |
): |
| 267 |
|
| 268 |
self._ffmpeg_api = imageio_ffmpeg |
| 269 |
|
| 270 |
self._arg_loop = bool(loop) |
| 271 |
if size is None: |
| 272 |
self._arg_size = None |
| 273 |
elif isinstance(size, tuple): |
| 274 |
self._arg_size = "%ix%i" % size |
| 275 |
elif isinstance(size, str) and "x" in size: |
| 276 |
self._arg_size = size |
| 277 |
else: |
| 278 |
raise ValueError('FFMPEG size must be tuple of "NxM"') |
| 279 |
if pixelformat is None: |
| 280 |
pass |
| 281 |
elif not isinstance(pixelformat, str): |
| 282 |
raise ValueError("FFMPEG pixelformat must be str") |
| 283 |
if dtype is None: |
| 284 |
self._dtype = np.dtype("uint8") |
| 285 |
else: |
| 286 |
self._dtype = np.dtype(dtype) |
| 287 |
allowed_dtypes = ["uint8", "uint16"] |
| 288 |
if self._dtype.name not in allowed_dtypes: |
| 289 |
raise ValueError( |
| 290 |
"dtype must be one of: {}".format(", ".join(allowed_dtypes)) |
| 291 |
) |
| 292 |
self._arg_pixelformat = pixelformat |
| 293 |
self._arg_input_params = input_params or [] |
| 294 |
self._arg_output_params = output_params or [] |
| 295 |
self._arg_input_params += ffmpeg_params or [] |
| 296 |
|
| 297 |
self.request._video = None |
| 298 |
regex_match = re.match(r"<video(\d+)>", self.request.filename) |
| 299 |
if regex_match: |
| 300 |
self.request._video = self.request.filename |
| 301 |
|
| 302 |
if self.request._video: |
| 303 |
index = int(regex_match.group(1)) |
| 304 |
self._filename = self._get_cam_inputname(index) |
| 305 |
else: |
| 306 |
self._filename = self.request.get_local_filename() |
| 307 |
|
| 308 |
if get_version() < (0, 4, 2): |
| 309 |
self._filename = self._filename.replace("^", "^^") |
| 310 |
|
| 311 |
self._depth = 3 |
| 312 |
if self._dtype.name == "uint8": |
| 313 |
self._pix_fmt = "rgb24" |
| 314 |
self._bytes_per_channel = 1 |
| 315 |
else: |
| 316 |
self._pix_fmt = "rgb48le" |
| 317 |
self._bytes_per_channel = 2 |
| 318 |
|
| 319 |
self._pos = -1 |
| 320 |
self._meta = {"plugin": "ffmpeg"} |
| 321 |
self._lastread = None |
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
self._nframes = float("inf") |
| 327 |
if self._arg_loop and not self.request._video: |
| 328 |
self._nframes = self.count_frames() |
| 329 |
self._meta["nframes"] = self._nframes |
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
need_input_fps = need_output_fps = False |
| 337 |
if self.request._video and platform.system().lower() == "darwin": |
| 338 |
if "-framerate" not in str(self._arg_input_params): |
| 339 |
need_input_fps = True |
| 340 |
if not self.request.kwargs.get("fps", None): |
| 341 |
need_output_fps = True |
| 342 |
if need_input_fps: |
| 343 |
self._arg_input_params.extend(["-framerate", str(float(30))]) |
| 344 |
if need_output_fps: |
| 345 |
self._arg_output_params.extend(["-r", str(float(30))]) |
| 346 |
|
| 347 |
|
| 348 |
try: |
| 349 |
self._initialize() |
| 350 |
except IndexError: |
| 351 |
|
| 352 |
if need_input_fps: |
| 353 |
self._arg_input_params[-1] = str(float(15)) |
| 354 |
self._initialize() |
| 355 |
else: |
| 356 |
raise |
| 357 |
|
| 358 |
|
| 359 |
if self.request._video: |
| 360 |
self._frame_catcher = FrameCatcher(self._read_gen) |
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
def _close(self): |
| 370 |
|
| 371 |
|
| 372 |
if self._frame_catcher is not None: |
| 373 |
self._frame_catcher.stop_me() |
| 374 |
self._frame_catcher = None |
| 375 |
if self._read_gen is not None: |
| 376 |
self._read_gen.close() |
| 377 |
self._read_gen = None |
| 378 |
|
| 379 |
def count_frames(self): |
| 380 |
"""Count the number of frames. Note that this can take a few |
| 381 |
seconds for large files. Also note that it counts the number |
| 382 |
of frames in the original video and does not take a given fps |
| 383 |
into account. |
| 384 |
""" |
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
cf = self._ffmpeg_api.count_frames_and_secs |
| 391 |
return cf(self._filename)[0] |
| 392 |
|
| 393 |
def _get_length(self): |
| 394 |
return self._nframes |
| 395 |
|
| 396 |
def _get_data(self, index): |
| 397 |
"""Reads a frame at index. Note for coders: getting an |
| 398 |
arbitrary frame in the video with ffmpeg can be painfully |
| 399 |
slow if some decoding has to be done. This function tries |
| 400 |
to avoid fectching arbitrary frames whenever possible, by |
| 401 |
moving between adjacent frames.""" |
| 402 |
|
| 403 |
if self._arg_loop and self._nframes < float("inf"): |
| 404 |
index %= self._nframes |
| 405 |
|
| 406 |
if index == self._pos: |
| 407 |
return self._lastread, dict(new=False) |
| 408 |
elif index < 0: |
| 409 |
raise IndexError("Frame index must be >= 0") |
| 410 |
elif index >= self._nframes: |
| 411 |
raise IndexError("Reached end of video") |
| 412 |
else: |
| 413 |
if (index < self._pos) or (index > self._pos + 100): |
| 414 |
self._initialize(index) |
| 415 |
else: |
| 416 |
self._skip_frames(index - self._pos - 1) |
| 417 |
result, is_new = self._read_frame() |
| 418 |
self._pos = index |
| 419 |
return result, dict(new=is_new) |
| 420 |
|
| 421 |
def _get_meta_data(self, index): |
| 422 |
return self._meta |
| 423 |
|
| 424 |
def _initialize(self, index=0): |
| 425 |
|
| 426 |
if self._read_gen is not None: |
| 427 |
self._read_gen.close() |
| 428 |
|
| 429 |
iargs = [] |
| 430 |
oargs = [] |
| 431 |
|
| 432 |
|
| 433 |
iargs += self._arg_input_params |
| 434 |
if self.request._video: |
| 435 |
iargs += ["-f", CAM_FORMAT] |
| 436 |
if self._arg_pixelformat: |
| 437 |
iargs += ["-pix_fmt", self._arg_pixelformat] |
| 438 |
if self._arg_size: |
| 439 |
iargs += ["-s", self._arg_size] |
| 440 |
elif index > 0: |
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
starttime = index / self._meta["fps"] |
| 452 |
seek_slow = min(10, starttime) |
| 453 |
seek_fast = starttime - seek_slow |
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
iargs += ["-ss", "%.06f" % (seek_fast)] |
| 458 |
oargs += ["-ss", "%.06f" % (seek_slow)] |
| 459 |
|
| 460 |
|
| 461 |
if self._arg_size: |
| 462 |
oargs += ["-s", self._arg_size] |
| 463 |
if self.request.kwargs.get("fps", None): |
| 464 |
fps = float(self.request.kwargs["fps"]) |
| 465 |
oargs += ["-r", "%.02f" % fps] |
| 466 |
oargs += self._arg_output_params |
| 467 |
|
| 468 |
|
| 469 |
pix_fmt = self._pix_fmt |
| 470 |
bpp = self._depth * self._bytes_per_channel |
| 471 |
|
| 472 |
|
| 473 |
rf = self._ffmpeg_api.read_frames |
| 474 |
self._read_gen = rf( |
| 475 |
self._filename, pix_fmt, bpp, input_params=iargs, output_params=oargs |
| 476 |
) |
| 477 |
|
| 478 |
|
| 479 |
if self.request._video: |
| 480 |
|
| 481 |
try: |
| 482 |
meta = self._read_gen.__next__() |
| 483 |
except IOError as err: |
| 484 |
err_text = str(err) |
| 485 |
if "darwin" in sys.platform: |
| 486 |
if "Unknown input format: 'avfoundation'" in err_text: |
| 487 |
err_text += ( |
| 488 |
"Try installing FFMPEG using " |
| 489 |
"home brew to get a version with " |
| 490 |
"support for cameras." |
| 491 |
) |
| 492 |
raise IndexError( |
| 493 |
"No (working) camera at {}.\n\n{}".format( |
| 494 |
self.request._video, err_text |
| 495 |
) |
| 496 |
) |
| 497 |
else: |
| 498 |
self._meta.update(meta) |
| 499 |
elif index == 0: |
| 500 |
self._meta.update(self._read_gen.__next__()) |
| 501 |
else: |
| 502 |
self._read_gen.__next__() |
| 503 |
|
| 504 |
def _skip_frames(self, n=1): |
| 505 |
"""Reads and throws away n frames""" |
| 506 |
for i in range(n): |
| 507 |
self._read_gen.__next__() |
| 508 |
self._pos += n |
| 509 |
|
| 510 |
def _read_frame(self): |
| 511 |
|
| 512 |
w, h = self._meta["size"] |
| 513 |
framesize = w * h * self._depth * self._bytes_per_channel |
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
if self._frame_catcher: |
| 518 |
s, is_new = self._frame_catcher.get_frame() |
| 519 |
else: |
| 520 |
s = self._read_gen.__next__() |
| 521 |
is_new = True |
| 522 |
|
| 523 |
|
| 524 |
if len(s) != framesize: |
| 525 |
raise RuntimeError( |
| 526 |
"Frame is %i bytes, but expected %i." % (len(s), framesize) |
| 527 |
) |
| 528 |
|
| 529 |
result = np.frombuffer(s, dtype=self._dtype).copy() |
| 530 |
result = result.reshape((h, w, self._depth)) |
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
self._lastread = result |
| 536 |
return result, is_new |
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
class Writer(Format.Writer): |
| 541 |
_write_gen = None |
| 542 |
|
| 543 |
def _open( |
| 544 |
self, |
| 545 |
fps=10, |
| 546 |
codec="libx264", |
| 547 |
bitrate=None, |
| 548 |
pixelformat="yuv420p", |
| 549 |
ffmpeg_params=None, |
| 550 |
input_params=None, |
| 551 |
output_params=None, |
| 552 |
ffmpeg_log_level="quiet", |
| 553 |
quality=5, |
| 554 |
macro_block_size=16, |
| 555 |
audio_path=None, |
| 556 |
audio_codec=None, |
| 557 |
): |
| 558 |
self._ffmpeg_api = imageio_ffmpeg |
| 559 |
self._filename = self.request.get_local_filename() |
| 560 |
self._pix_fmt = None |
| 561 |
self._depth = None |
| 562 |
self._size = None |
| 563 |
|
| 564 |
def _close(self): |
| 565 |
if self._write_gen is not None: |
| 566 |
self._write_gen.close() |
| 567 |
self._write_gen = None |
| 568 |
|
| 569 |
def _append_data(self, im, meta): |
| 570 |
|
| 571 |
h, w = im.shape[:2] |
| 572 |
size = w, h |
| 573 |
depth = 1 if im.ndim == 2 else im.shape[2] |
| 574 |
|
| 575 |
|
| 576 |
im = image_as_uint(im, bitdepth=8) |
| 577 |
|
| 578 |
|
| 579 |
if not im.flags.c_contiguous: |
| 580 |
|
| 581 |
|
| 582 |
|
| 583 |
im = np.ascontiguousarray(im) |
| 584 |
|
| 585 |
|
| 586 |
if self._size is None: |
| 587 |
map = {1: "gray", 2: "gray8a", 3: "rgb24", 4: "rgba"} |
| 588 |
self._pix_fmt = map.get(depth, None) |
| 589 |
if self._pix_fmt is None: |
| 590 |
raise ValueError("Image must have 1, 2, 3 or 4 channels") |
| 591 |
self._size = size |
| 592 |
self._depth = depth |
| 593 |
self._initialize() |
| 594 |
|
| 595 |
|
| 596 |
if size != self._size: |
| 597 |
raise ValueError("All images in a movie should have same size") |
| 598 |
if depth != self._depth: |
| 599 |
raise ValueError( |
| 600 |
"All images in a movie should have same " "number of channels" |
| 601 |
) |
| 602 |
|
| 603 |
assert self._write_gen is not None |
| 604 |
|
| 605 |
|
| 606 |
self._write_gen.send(im) |
| 607 |
|
| 608 |
def set_meta_data(self, meta): |
| 609 |
raise RuntimeError( |
| 610 |
"The ffmpeg format does not support setting " "meta data." |
| 611 |
) |
| 612 |
|
| 613 |
def _initialize(self): |
| 614 |
|
| 615 |
if self._write_gen is not None: |
| 616 |
self._write_gen.close() |
| 617 |
|
| 618 |
|
| 619 |
|
| 620 |
fps = self.request.kwargs.get("fps", 10) |
| 621 |
codec = self.request.kwargs.get("codec", None) |
| 622 |
bitrate = self.request.kwargs.get("bitrate", None) |
| 623 |
quality = self.request.kwargs.get("quality", None) |
| 624 |
input_params = self.request.kwargs.get("input_params") or [] |
| 625 |
output_params = self.request.kwargs.get("output_params") or [] |
| 626 |
output_params += self.request.kwargs.get("ffmpeg_params") or [] |
| 627 |
pixelformat = self.request.kwargs.get("pixelformat", None) |
| 628 |
macro_block_size = self.request.kwargs.get("macro_block_size", 16) |
| 629 |
ffmpeg_log_level = self.request.kwargs.get("ffmpeg_log_level", None) |
| 630 |
audio_path = self.request.kwargs.get("audio_path", None) |
| 631 |
audio_codec = self.request.kwargs.get("audio_codec", None) |
| 632 |
|
| 633 |
macro_block_size = macro_block_size or 1 |
| 634 |
|
| 635 |
|
| 636 |
self._write_gen = self._ffmpeg_api.write_frames( |
| 637 |
self._filename, |
| 638 |
self._size, |
| 639 |
pix_fmt_in=self._pix_fmt, |
| 640 |
pix_fmt_out=pixelformat, |
| 641 |
fps=fps, |
| 642 |
quality=quality, |
| 643 |
bitrate=bitrate, |
| 644 |
codec=codec, |
| 645 |
macro_block_size=macro_block_size, |
| 646 |
ffmpeg_log_level=ffmpeg_log_level, |
| 647 |
input_params=input_params, |
| 648 |
output_params=output_params, |
| 649 |
audio_path=audio_path, |
| 650 |
audio_codec=audio_codec, |
| 651 |
) |
| 652 |
|
| 653 |
|
| 654 |
self._write_gen.send(None) |
| 655 |
|
| 656 |
|
| 657 |
class FrameCatcher(threading.Thread): |
| 658 |
"""Thread to keep reading the frame data from stdout. This is |
| 659 |
useful when streaming from a webcam. Otherwise, if the user code |
| 660 |
does not grab frames fast enough, the buffer will fill up, leading |
| 661 |
to lag, and ffmpeg can also stall (experienced on Linux). The |
| 662 |
get_frame() method always returns the last available image. |
| 663 |
""" |
| 664 |
|
| 665 |
def __init__(self, gen): |
| 666 |
self._gen = gen |
| 667 |
self._frame = None |
| 668 |
self._frame_is_new = False |
| 669 |
self._lock = threading.RLock() |
| 670 |
threading.Thread.__init__(self) |
| 671 |
self.daemon = True |
| 672 |
self._should_stop = False |
| 673 |
self.start() |
| 674 |
|
| 675 |
def stop_me(self): |
| 676 |
self._should_stop = True |
| 677 |
while self.is_alive(): |
| 678 |
time.sleep(0.001) |
| 679 |
|
| 680 |
def get_frame(self): |
| 681 |
while self._frame is None: |
| 682 |
time.sleep(0.001) |
| 683 |
with self._lock: |
| 684 |
is_new = self._frame_is_new |
| 685 |
self._frame_is_new = False |
| 686 |
return self._frame, is_new |
| 687 |
|
| 688 |
def run(self): |
| 689 |
|
| 690 |
try: |
| 691 |
while not self._should_stop: |
| 692 |
time.sleep(0) |
| 693 |
frame = self._gen.__next__() |
| 694 |
with self._lock: |
| 695 |
self._frame = frame |
| 696 |
self._frame_is_new = True |
| 697 |
except (StopIteration, EOFError): |
| 698 |
pass |
| 699 |
|
| 700 |
|
| 701 |
def parse_device_names(ffmpeg_output): |
| 702 |
"""Parse the output of the ffmpeg -list-devices command""" |
| 703 |
|
| 704 |
device_names = [] |
| 705 |
in_video_devices = False |
| 706 |
for line in ffmpeg_output.splitlines(): |
| 707 |
if line.startswith("[dshow"): |
| 708 |
logger.debug(line) |
| 709 |
line = line.split("]", 1)[1].strip() |
| 710 |
if in_video_devices and line.startswith('"'): |
| 711 |
friendly_name = line[1:-1] |
| 712 |
device_names.append([friendly_name, ""]) |
| 713 |
elif in_video_devices and line.lower().startswith("alternative name"): |
| 714 |
alt_name = line.split(" name ", 1)[1].strip()[1:-1] |
| 715 |
if sys.platform.startswith("win"): |
| 716 |
alt_name = alt_name.replace("&", "^&") |
| 717 |
else: |
| 718 |
alt_name = alt_name.replace("&", "\\&") |
| 719 |
device_names[-1][-1] = alt_name |
| 720 |
elif "video devices" in line: |
| 721 |
in_video_devices = True |
| 722 |
elif "devices" in line: |
| 723 |
|
| 724 |
in_video_devices = False |
| 725 |
|
| 726 |
|
| 727 |
device_names2 = [] |
| 728 |
for friendly_name, alt_name in device_names: |
| 729 |
if friendly_name not in device_names2: |
| 730 |
device_names2.append(friendly_name) |
| 731 |
elif alt_name: |
| 732 |
device_names2.append(alt_name) |
| 733 |
else: |
| 734 |
device_names2.append(friendly_name) |
| 735 |
return device_names2 |