
;c]c           @` s  d  Z  d d l m Z m Z m Z d d l Z d d l Z d d l Z d d l Z d d l	 Z
 d d l Z d d l m Z d d l m Z m Z m Z e j e  Z e j j d  r d Z n< e j j d	  r d
 Z n! e j j d  r d Z n d Z e e d  Z d   Z e a d   Z d e f d     YZ d e j  f d     YZ! d   Z" e d d d d  Z# e j$ e#  d S(   s    Plugin that uses ffmpeg to read and write series of images to
a wide range of video formats.

Code inspired/based on code from moviepy: https://github.com/Zulko/moviepy/
by Zulko

i    (   t   absolute_importt   print_functiont   divisionNi   (   t   formats(   t   Formatt   string_typest   image_as_uintt   wint   dshowt   linuxt   video4linux2t   darwint   avfoundations   unknown-cam-formatc         C` s   t  d   d  S(   NsY   imageio.ffmpeg.download() has been deprecated. Use 'pip install imageio-ffmpeg' instead.'(   t   RuntimeError(   t	   directoryt   force_download(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   download&   s    c          C` s   d d l  }  |  j   S(   s1    Wrapper for imageio_ffmpeg.get_ffmpeg_exe()
    i    N(   t   imageio_ffmpegt   get_ffmpeg_exe(   R   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   get_exe.   s    c          C` sg   t  d  k rc t j d k  r* t d   n  y d d  l }  Wn t k
 rY t d   n X|  a  n  t  S(   Ni   s-   The ffmpeg plugin does not work on Python 2.xi    sI   To use the imageio ffmpeg plugin you need to 'pip install imageio-ffmpeg'(   i   (   t   _ffmpeg_apit   Nonet   syst   version_infoR   R   t   ImportError(   R   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   _get_ffmpeg_api9   s    	t   FfmpegFormatc           B` sR   e  Z d  Z d   Z d   Z d e j f d     YZ d e j f d     YZ RS(   s   The ffmpeg format provides reading and writing for a wide range
    of movie formats such as .avi, .mpeg, .mp4, etc. And also to read
    streams from webcams and USB cameras.

    To read from camera streams, supply "<video0>" as the filename,
    where the "0" can be replaced with any index of cameras known to
    the system.

    To use this plugin, the ``imageio-ffmpeg`` library should be installed
    (e.g. via pip). For most platforms this includes the ffmpeg executable.
    One can use the ``IMAGEIO_FFMPEG_EXE`` environment variable to force
    using a specific ffmpeg executable.

    When reading from a video, the number of available frames is hard/expensive
    to calculate, which is why its set to inf by default, indicating
    "stream mode". To get the number of frames before having read them all,
    you can use the ``reader.count_frames()`` method (the reader will then use
    ``imageio_ffmpeg.count_frames_and_secs()`` to get the exact number of
    frames, note that this operation can take a few seconds on large files).
    Alternatively, the number of frames can be estimated from the fps and
    duration in the meta data (though these values themselves are not always
    present/reliable).

    Parameters for reading
    ----------------------
    fps : scalar
        The number of frames per second to read the data at. Default None (i.e.
        read at the file's own fps). One can use this for files with a
        variable fps, or in cases where imageio is unable to correctly detect
        the fps.
    loop : bool
        If True, the video will rewind as soon as a frame is requested
        beyond the last frame. Otherwise, IndexError is raised. Default False.
        Setting this to True will internally call ``count_frames()``,
        and set the reader's length to that value instead of inf.
    size : str | tuple
        The frame size (i.e. resolution) to read the images, e.g.
        (100, 100) or "640x480". For camera streams, this allows setting
        the capture resolution. For normal video data, ffmpeg will
        rescale the data.
    dtype : str | type
        The dtype for the output arrays. Determines the bit-depth that
        is requested from ffmpeg. Supported dtypes: uint8, uint16.
        Default: uint8.
    pixelformat : str
        The pixel format for the camera to use (e.g. "yuyv422" or
        "gray"). The camera needs to support the format in order for
        this to take effect. Note that the images produced by this
        reader are always RGB.
    input_params : list
        List additional arguments to ffmpeg for input file options.
        (Can also be provided as ``ffmpeg_params`` for backwards compatibility)
        Example ffmpeg arguments to use aggressive error handling:
        ['-err_detect', 'aggressive']
    output_params : list
        List additional arguments to ffmpeg for output file options (i.e. the
        stream being read by imageio).
    print_info : bool
        Print information about the video file as reported by ffmpeg.

    Parameters for saving
    ---------------------
    fps : scalar
        The number of frames per second. Default 10.
    codec : str
        the video codec to use. Default 'libx264', which represents the
        widely available mpeg4. Except when saving .wmv files, then the
        defaults is 'msmpeg4' which is more commonly supported for windows
    quality : float | None
        Video output quality. Default is 5. Uses variable bit rate. Highest
        quality is 10, lowest is 0. Set to None to prevent variable bitrate
        flags to FFMPEG so you can manually specify them using output_params
        instead. Specifying a fixed bitrate using 'bitrate' disables this
        parameter.
    bitrate : int | None
        Set a constant bitrate for the video encoding. Default is None causing
        'quality' parameter to be used instead.  Better quality videos with
        smaller file sizes will result from using the 'quality'  variable
        bitrate parameter rather than specifiying a fixed bitrate with this
        parameter.
    pixelformat: str
        The output video pixel format. Default is 'yuv420p' which most widely
        supported by video players.
    input_params : list
        List additional arguments to ffmpeg for input file options (i.e. the
        stream that imageio provides).
    output_params : list
        List additional arguments to ffmpeg for output file options.
        (Can also be provided as ``ffmpeg_params`` for backwards compatibility)
        Example ffmpeg arguments to use only intra frames and set aspect ratio:
        ['-intra', '-aspect', '16:9']
    ffmpeg_log_level: str
        Sets ffmpeg output log level.  Default is "warning".
        Values can be "quiet", "panic", "fatal", "error", "warning", "info"
        "verbose", or "debug". Also prints the FFMPEG command being used by
        imageio if "info", "verbose", or "debug".
    macro_block_size: int
        Size constraint for video. Width and height, must be divisible by this
        number. If not divisible by this number imageio will tell ffmpeg to
        scale the image up to the next closest size
        divisible by this number. Most codecs are compatible with a macroblock
        size of 16 (default), some can go smaller (4, 8). To disable this
        automatic feature set it to None or 1, however be warned many players
        can't decode videos that are odd in size and some codecs will produce
        poor results or fail. See https://en.wikipedia.org/wiki/Macroblock.
    c         C` sa   | j  d d k r t S| j g  t d  D] } d | ^ q* k rG t S| j |  j k r] t Sd  S(   Ni   s   I?i
   s	   <video%i>(   t   modet   Falset   filenamet   ranget   Truet	   extensiont
   extensions(   t   selft   requestt   i(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt	   _can_read   s    ,c         C` s7   | j  d |  j d k r3 | j |  j k r3 t Sn  d  S(   Ni   t   ?(   R   t   modesR    R!   R   (   R"   R#   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt
   _can_write   s    t   Readerc        
   B` s   e  Z d Z d Z d    Z e d d d e d d d d d 	 Z d   Z d   Z	 d   Z
 d   Z d   Z d d  Z d	 d
  Z d   Z RS(   c      
   C` s2  t  j j d  r' d |  j j d d !St  j j d  rt   } | j   d d d t d	 d
 g } t j	 | d t j
 d t j
 d t j
 d t } | j j   | j   | j j   j d d d } y t |  | } Wn! t k
 r t d |   n Xd | St  j j d  r*t |  } | Sd Sd  S(   NR	   s   /dev/i   iR   s   -list_devicest   trues   -fs   -it   dummyt   stdint   stdoutt   stderrt   shells   utf-8t   errorst   ignores   No ffdshow camera at index %i.s   video=%sR   s   ??(   R   t   platformt
   startswithR#   t   _videoR   R   t
   CAM_FORMATt   spt   Popent   PIPER   R-   t   readlinet	   terminateR.   t   readt   decodet   parse_device_namest
   IndexErrort   str(   R"   t   indext
   ffmpeg_apit   cmdt   proct   infost   name(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   _get_cam_inputname   s2    			*
c
         C` s  t    |  _ t |  |  _ | d  k r3 d  |  _ nR t | t  rR d | |  _ n3 t | t  ry d | k ry | |  _ n t	 d   | d  k r n t | t  s t	 d   n  | d  k r t
 j d  |  _ nQ t
 j |  |  _ d d g }
 |  j j |
 k r$t	 d j d j |
     n  | |  _ | p6g  |  _ | pEg  |  _ |  j | p[g  7_ d  |  j _ |  j j g  t d	  D] } d
 | ^ qk r|  j j |  j _ n  |  j j rt |  j j d  } |  j |  |  _ n* |  j j   |  _ |  j j d d  |  _ d |  _ |  j j d k rAd |  _ d |  _ n d |  _ d |  _ d |  _ i d d 6|  _  d  |  _! t" d  |  _# |  j r|  j j r|  j$   |  _# n  |  j# |  j  d <|  j%   |  j j rt& |  j'  |  _( n  d  S(   Ns   %ix%it   xs"   FFMPEG size must be tuple of "NxM"s   FFMPEG pixelformat must be strt   uint8t   uint16s   dtype must be one of: {}s   , i
   s	   <video%i>it   ^s   ^^i   t   rgb24i   t   rgb48lei   it   ffmpegt   plugint   inft   nframes()   R   R   t   boolt	   _arg_loopR   t	   _arg_sizet
   isinstancet   tupleR   t
   ValueErrort   npt   dtypet   _dtypeRE   t   formatt   joint   _arg_pixelformatt   _arg_input_paramst   _arg_output_paramsR#   R4   R   R   t   intRF   t	   _filenamet   get_local_filenamet   replacet   _deptht   _pix_fmtt   _bytes_per_channelt   _post   _metat	   _lastreadt   floatt   _nframest   count_framest   _initializet   FrameCatchert	   _read_gent   _frame_catcher(   R"   t   loopt   sizeRX   t   pixelformatt
   print_infot   ffmpeg_paramst   input_paramst   output_paramst   fpst   allowed_dtypesR$   R@   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   _open   s`    	/						
c         C` sT   |  j  d  k	 r( |  j  j   d  |  _  n  |  j d  k	 rP |  j j   d  |  _ n  d  S(   N(   Ro   R   t   stop_meRn   t   close(   R"   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   _closeP  s    c         C` s   |  j  j } | |  j  d S(   s    Count the number of frames. Note that this can take a few
            seconds for large files. Also note that it counts the number
            of frames in the original video and does not take a given fps
            into account.
            i    (   R   t   count_frames_and_secsR`   (   R"   t   cf(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyRk   Z  s    c         C` s   |  j  S(   N(   Rj   (   R"   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   _get_lengthh  s    c         C` s  |  j  r. |  j t d  k  r. | |  j ;} n  | |  j k rS |  j t d t  f S| d k  rn t d   n | |  j k r t d   nx | |  j k  s | |  j d k r |  j |  n |  j	 | |  j d  |  j
   \ } } | |  _ | t d |  f Sd S(	   s3   Reads a frame at index. Note for coders: getting an
            arbitrary frame in the video with ffmpeg can be painfully
            slow if some decoding has to be done. This function tries
            to avoid fectching arbitrary frames whenever possible, by
            moving between adjacent frames. RO   t   newi    s   Frame index must be >= 0s   Reached end of videoid   i   N(   RR   Rj   Ri   Rf   Rh   t   dictR   R>   Rl   t   _skip_framest   _read_frame(   R"   R@   t   resultt   is_new(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt	   _get_datak  s    "	c         C` s   |  j  S(   N(   Rg   (   R"   R@   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   _get_meta_data  s    i    c         C` s  |  j  d  k	 r |  j  j   n  g  } g  } | |  j 7} |  j j r | d t g 7} |  j rs | d |  j g 7} n  |  j r | d |  j g 7} q na | d k r | |  j	 d } t
 d |  } | | } | d d | g 7} | d d | g 7} n  |  j r| d |  j g 7} n  |  j j j d d   rZt |  j j d  } | d	 d
 | g 7} n  | |  j 7} |  j } |  j |  j }	 |  j j }
 |
 |  j | |	 d | d | |  _  |  j j rMy |  j  j   } Wnh t k
 r9} t |  } d t j k rd | k r| d 7} qn  t d j |  j j |    qX|  j	 j |  n5 | d k ru|  j	 j |  j  j    n |  j  j   d  S(   Ns   -fs   -pix_fmts   -si    Rw   i
   s   -sss   %.06fs   -rs   %.02fRu   Rv   R   s$   Unknown input format: 'avfoundation'sP   Try installing FFMPEG using home brew to get a version with support for cameras.s   No camera at {}.

{}(   Rn   R   R{   R]   R#   R4   R5   R\   RS   Rg   t   mint   kwargst   getRi   R^   Rd   Rc   Re   R   t   read_framesR`   t   __next__t   IOErrorR?   R   R2   R>   RZ   t   update(   R"   R@   t   iargst   oargst	   starttimet	   seek_slowt	   seek_fastRw   t   pix_fmtt   bppt   rft   metat   errt   err_text(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyRl     sV    		
		!i   c         C` s7   x! t  |  D] } |  j j   q W|  j | 7_ d S(   s     Reads and throws away n frames N(   R   Rn   R   Rf   (   R"   t   nR$   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR     s    c         C` s   |  j  d \ } } | | |  j |  j } |  j rL |  j j   \ } } n |  j j   } t } t |  | k r t	 d t |  | f   n  t
 j | d |  j j   } | j | | |  j f  } | |  _ | | f S(   NRq   s#   Frame is %i bytes, but expected %i.RX   (   Rg   Rc   Re   Ro   t	   get_frameRn   R   R   t   lenR   RW   t
   frombufferRY   t   copyt   reshapeRh   (   R"   t   wt   ht	   framesizet   sR   R   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR     s    		N(   t   __name__t
   __module__R   Ro   Rn   RF   R   Ry   R|   Rk   R   R   R   Rl   R   R   (    (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR)      s(   	+N	
				Ot   Writerc           B` sY   e  Z d Z d  d d d d d d d d d d 
 Z d   Z d   Z d	   Z d
   Z RS(   i
   t   libx264t   yuv420pt   quieti   i   c         C` s=   t    |  _ |  j j   |  _ d  |  _ d  |  _ d  |  _ d  S(   N(	   R   R   R#   Ra   R`   R   Rd   Rc   t   _size(   R"   Rw   t   codect   bitrateRr   Rt   Ru   Rv   t   ffmpeg_log_levelt   qualityt   macro_block_size(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyRy     s
    		c         C` s,   |  j  d  k	 r( |  j  j   d  |  _  n  d  S(   N(   t
   _write_genR   R{   (   R"   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR|     s    c         C` sY  | j  d  \ } } | | f } | j d k r4 d n
 | j  d } t | d d } | j j sq t j |  } n  |  j d  k r i d d 6d d 6d d 6d	 d
 6} | j	 | d   |  _
 |  j
 d  k r t d   n  | |  _ | |  _ |  j   n  | |  j k rt d   n  | |  j k r0t d   n  |  j d  k	 sEt  |  j j |  d  S(   Ni   i   t   bitdepthi   t   grayt   gray8aRK   i   t   rgbai   s%   Image must have 1, 2, 3 or 4 channelss+   All images in a movie should have same sizes9   All images in a movie should have same number of channels(   t   shapet   ndimR   t   flagst   c_contiguousRW   t   ascontiguousarrayR   R   R   Rd   RV   Rc   Rl   R   t   AssertionErrort   send(   R"   t   imR   R   R   Rq   t   deptht   map(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   _append_data  s*    ""		c         C` s   t  d   d  S(   Ns5   The ffmpeg format does not support setting meta data.(   R   (   R"   R   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   set_meta_data>  s    c   
      C` s  |  j  d  k	 r |  j  j   n  |  j j j d d  } |  j j j d d   } |  j j j d d   } |  j j j d d   } |  j j j d  p g  } |  j j j d  p g  } | |  j j j d  p g  7} |  j j j d	 d   } |  j j j d
 d  } |  j j j d d   }	 | p%d } |  j j |  j |  j	 d |  j
 d | d | d | d | d | d
 | d |	 d | d | 
|  _  |  j  j d   d  S(   NRw   i
   R   R   R   Ru   Rv   Rt   Rr   R   i   R   i   t
   pix_fmt_int   pix_fmt_out(   R   R   R{   R#   R   R   R   t   write_framesR`   R   Rd   R   (
   R"   Rw   R   R   R   Ru   Rv   Rr   R   R   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyRl   C  s6    			N(	   R   R   R   R   Ry   R|   R   R   Rl   (    (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR     s   		(	(   R   R   t   __doc__R%   R(   R   R)   R   (    (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR   I   s   j		 1Rm   c           B` s2   e  Z d  Z d   Z d   Z d   Z d   Z RS(   sN   Thread to keep reading the frame data from stdout. This is
    useful when streaming from a webcam. Otherwise, if the user code
    does not grab frames fast enough, the buffer will fill up, leading
    to lag, and ffmpeg can also stall (experienced on Linux). The
    get_frame() method always returns the last available image.
    c         C` s^   | |  _  d  |  _ t |  _ t j   |  _ t j j	 |   |  j
 t  t |  _ |  j   d  S(   N(   t   _genR   t   _frameR   t   _frame_is_newt	   threadingt   RLockt   _lockt   Threadt   __init__t	   setDaemonR   t   _should_stopt   start(   R"   t   gen(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR   t  s    				c         C` s-   t  |  _ x |  j   r( t j d  q Wd  S(   NgMbP?(   R   R   t   is_alivet   timet   sleep(   R"   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyRz   ~  s    	c         C` sV   x  |  j  d  k r" t j d  q W|  j $ |  j } t |  _ |  j  | f SWd  QXd  S(   NgMbP?(   R   R   R   R   R   R   R   (   R"   R   (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR     s    
		c         C` sp   yR xK |  j  sP t j d  |  j j   } |  j  | |  _ t |  _ Wd  QXq WWn t	 t
 f k
 rk n Xd  S(   Ni    (   R   R   R   R   R   R   R   R   R   t   StopIterationt   EOFError(   R"   t   frame(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   run  s    
	(   R   R   R   R   Rz   R   R   (    (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyRm   l  s
   	
		c         C` s  g  } t  } x9|  j   D]+} | j d  r t j |  | j d d  d j   } | r | j d  r | d d !} | j | d g  qD| r| j   j d  r| j d d  d j   d d !} t	 j
 j d	  r | j d
 d  } n | j d
 d  } | | d d <qDd | k r,t } qDd | k rDt  } qDq q Wg  } xS | D]K \ } } | | k r}| j |  qU| r| j |  qU| j |  qUW| S(   s5    Parse the output of the ffmpeg -list-devices commands   [dshowt   ]i   t   "it    s   alternative names    name R   t   &s   ^&s   \&s   video devicest   devices(   R   t
   splitlinesR3   t   loggert   debugt   splitt   stript   appendt   lowerR   R2   Rb   R   (   t   ffmpeg_outputt   device_namest   in_video_devicest   linet   friendly_namet   alt_namet   device_names2(    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyR=     s6    #	RM   s+   Many video formats and cameras (via ffmpeg)s#   .mov .avi .mpg .mpeg .mp4 .mkv .wmvt   I(%   R   t
   __future__R    R   R   R   R   t   loggingR   t
   subprocessR6   t   numpyRW   R   R   t   coreR   R   R   t	   getLoggerR   R   R2   R3   R5   R   R   R   R   R   R   R   R   Rm   R=   RZ   t
   add_format(    (    (    s5   lib/python2.7/site-packages/imageio/plugins/ffmpeg.pyt   <module>
   s@   					  %,	&	