Debian Codegraph @

imageio/plugins/ffmpeg.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # imageio is distributed under the terms of the (new) BSD License.
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 # Get camera format
152 if sys.platform.startswith("win"):
153 CAM_FORMAT = "dshow" # dshow or vfwcap
154 elif sys.platform.startswith("linux"):
155 CAM_FORMAT = "video4linux2"
156 elif sys.platform.startswith("darwin"):
157 CAM_FORMAT = "avfoundation"
158 else: # pragma: no cover
159 CAM_FORMAT = "unknown-cam-format"
160
161
162 def download(directory=None, force_download=False): # pragma: no cover
163 raise RuntimeError(
164 "imageio.ffmpeg.download() has been deprecated. "
165 "Use 'pip install imageio-ffmpeg' instead.'"
166 )
167
168
169 # For backwards compatibility - we dont use this ourselves
170 def get_exe(): # pragma: no cover
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 # Read from video stream?
189 # Note that we could write the _video flag here, but a user might
190 # select this format explicitly (and this code is not run)
191 if re.match(r"<video(\d+)>", request.filename):
192 return True
193
194 # Read from file that we know?
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 # Ask ffmpeg for list of dshow device names
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 # Set `shell=True` in sp.run to prevent popup of a command
225 # line window in frozen applications. Note: this would be a
226 # security vulnerability if user-input goes into the cmd.
227 # Note that the ffmpeg process returns with exit code 1 when
228 # using `-list_devices` (or `-list_options`), even if the
229 # command is successful, so we set `check=False` explicitly.
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 # Return device name at index
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 # Appears that newer ffmpeg builds don't support -list-devices
248 # on OS X. But you can directly open the camera by index.
249 name = str(index)
250 return name
251
252 else: # pragma: no cover
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 # Get generator functions
268 self._ffmpeg_api = imageio_ffmpeg
269 # Process input args
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 [] # backward compat
296 # Write "_video"_arg - indicating webcam support
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 # Get local filename
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 # When passed to imageio-ffmpeg (<0.4.2) on command line, carets need to be escaped.
308 if get_version() < (0, 4, 2):
309 self._filename = self._filename.replace("^", "^^")
310 # Determine pixel format and depth
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 # Initialize parameters
319 self._pos = -1
320 self._meta = {"plugin": "ffmpeg"}
321 self._lastread = None
322
323 # Calculating this from fps and duration is not accurate,
324 # and calculating it exactly with ffmpeg_api.count_frames_and_secs
325 # takes too long to do for each video. But we need it for looping.
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 # Specify input framerate? (only on macOS)
332 # Ideally we'd get the supported framerate from the metadata, but we get the
333 # metadata when we boot ffmpeg ... maybe we could refactor this so we can
334 # get the metadata beforehand, but for now we'll just give it 2 tries on MacOS,
335 # one with fps 30 and one with fps 15.
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 # Start ffmpeg subprocess and get meta information
348 try:
349 self._initialize()
350 except IndexError:
351 # Specify input framerate again, this time different.
352 if need_input_fps:
353 self._arg_input_params[-1] = str(float(15))
354 self._initialize()
355 else:
356 raise
357
358 # For cameras, create thread that keeps reading the images
359 if self.request._video:
360 self._frame_catcher = FrameCatcher(self._read_gen)
361
362 # For reference - but disabled, because it is inaccurate
363 # if self._meta["nframes"] == float("inf"):
364 # if self._meta.get("fps", 0) > 0:
365 # if self._meta.get("duration", 0) > 0:
366 # n = round(self._meta["duration"] * self._meta["fps"])
367 # self._meta["nframes"] = int(n)
368
369 def _close(self):
370 # First close the frame catcher, because we cannot close the gen
371 # if the frame catcher thread is using it
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 # This would have been nice, but this does not work :(
386 # oargs = []
387 # if self.request.kwargs.get("fps", None):
388 # fps = float(self.request.kwargs["fps"])
389 # oargs += ["-r", "%.02f" % fps]
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 # only not inf if loop is True
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 # Modulo index (for looping)
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 # Close the current generator, and thereby terminate its subprocess
426 if self._read_gen is not None:
427 self._read_gen.close()
428
429 iargs = []
430 oargs = []
431
432 # Create input args
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: # re-initialize / seek
441 # Note: only works if we initialized earlier, and now have meta
442 # Some info here: https://trac.ffmpeg.org/wiki/Seeking
443 # There are two ways to seek, one before -i (input_params) and
444 # after (output_params). The former is fast, because it uses
445 # keyframes, the latter is slow but accurate. According to
446 # the article above, the fast method should also be accurate
447 # from ffmpeg version 2.1, however in version 4.1 our tests
448 # start failing again. Not sure why, but we can solve this
449 # by combining slow and fast. Seek the long stretch using
450 # the fast method, and seek the last 10s the slow way.
451 starttime = index / self._meta["fps"]
452 seek_slow = min(10, starttime)
453 seek_fast = starttime - seek_slow
454 # We used to have this epsilon earlier, when we did not use
455 # the slow seek. I don't think we need it anymore.
456 # epsilon = -1 / self._meta["fps"] * 0.1
457 iargs += ["-ss", "%.06f" % (seek_fast)]
458 oargs += ["-ss", "%.06f" % (seek_slow)]
459
460 # Output args, for writing to pipe
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 # Get pixelformat and bytes per pixel
469 pix_fmt = self._pix_fmt
470 bpp = self._depth * self._bytes_per_channel
471
472 # Create generator
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 # Read meta data. This start the generator (and ffmpeg subprocess)
479 if self.request._video:
480 # With cameras, catch error and turn into IndexError
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__() # we already have meta data
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 # Read and convert to numpy array
512 w, h = self._meta["size"]
513 framesize = w * h * self._depth * self._bytes_per_channel
514 # t0 = time.time()
515
516 # Read frame
517 if self._frame_catcher: # pragma: no cover - camera thing
518 s, is_new = self._frame_catcher.get_frame()
519 else:
520 s = self._read_gen.__next__()
521 is_new = True
522
523 # Check
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 # t1 = time.time()
532 # print('etime', t1-t0)
533
534 # Store and return
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 # Get props of image
571 h, w = im.shape[:2]
572 size = w, h
573 depth = 1 if im.ndim == 2 else im.shape[2]
574
575 # Ensure that image is in uint8
576 im = image_as_uint(im, bitdepth=8)
577 # To be written efficiently, ie. without creating an immutable
578 # buffer, by calling im.tobytes() the array must be contiguous.
579 if not im.flags.c_contiguous:
580 # checkign the flag is a micro optimization.
581 # the image will be a numpy subclass. See discussion
582 # https://github.com/numpy/numpy/issues/11804
583 im = np.ascontiguousarray(im)
584
585 # Set size and initialize if not initialized yet
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 # Check size of image
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 # Check status
604
605 # Write. Yes, we can send the data in as a numpy array
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 # Close existing generator
615 if self._write_gen is not None:
616 self._write_gen.close()
617
618 # Get parameters
619 # Use None to let imageio-ffmpeg (or ffmpeg) select good results
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 # None -> 1
634
635 # Create generator
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 # Seed the generator (this is where the ffmpeg subprocess starts)
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 # do not let this thread hold up Python shutdown
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: # pragma: no cover - an init thing
682 time.sleep(0.001)
683 with self._lock:
684 is_new = self._frame_is_new
685 self._frame_is_new = False # reset
686 return self._frame, is_new
687
688 def run(self):
689 # This runs in the worker thread
690 try:
691 while not self._should_stop:
692 time.sleep(0) # give control to other threads
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 # Collect device names - get [friendly_name, alt_name] of each
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("&", "^&") # Tested to work
717 else:
718 alt_name = alt_name.replace("&", "\\&") # Does this work?
719 device_names[-1][-1] = alt_name
720 elif "video devices" in line:
721 in_video_devices = True
722 elif "devices" in line:
723 # set False for subsequent "devices" sections
724 in_video_devices = False
725 # Post-process, see #441
726 # prefer friendly names, use alt name if two cams have same friendly name
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) # duplicate, but not much we can do
735 return device_names2