
    0-Pht                        d 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Zddl	Z	ddl
ZddlmZmZ  ej        e          Zej                            d          rdZn<ej                            d          rdZnej                            d	          rd
ZndZddZd Z G d de          Z G d dej                  Zd ZdS )aJ  Read/Write video using FFMPEG

.. note::
    We are in the process of (slowly) replacing this plugin with a new one that
    is based on `pyav <https://pyav.org/docs/stable/>`_. It is faster and more
    flexible than the plugin documented here. Check the :mod:`pyav
    plugin's documentation <imageio.plugins.pyav>` for more information about
    this plugin.

Backend Library: https://github.com/imageio/imageio-ffmpeg

.. note::
    To use this plugin you have to install its backend::

        pip install imageio[ffmpeg]


The ffmpeg format provides reading and writing for a wide range of movie formats
such as .avi, .mpeg, .mp4, etc. as well as the ability to read streams from
webcams and USB cameras. It is based on ffmpeg and is inspired by/based `moviepy
<https://github.com/Zulko/moviepy/>`_ by Zulko.

Parameters for reading
----------------------
fps : scalar
    The number of frames per second of the input stream. Default None (i.e.
    read at the file's native fps). One can use this for files with a
    variable fps, or in cases where imageio is unable to correctly detect
    the fps. In case of trouble opening camera streams, it may help to set an
    explicit fps value matching a framerate supported by the camera.
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 writing
----------------------
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 specifying 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.
audio_path : str | None
    Audio path of any audio that needs to be written. Defaults to nothing,
    so no audio will be written. Please note, when writing shorter video
    than the original, ffmpeg will not truncate the audio track; it
    will maintain its original length and be longer than the video.
audio_codec : str | None
    The audio codec to use. Defaults to nothing, but if an audio_path has
    been provided ffmpeg will attempt to set a default codec.

Notes
-----
If you are using anaconda and ``anaconda/ffmpeg`` you will not be able to
encode/decode H.264 (likely due to licensing concerns). If you need this
format on anaconda install ``conda-forge/ffmpeg`` instead.

You can use the ``IMAGEIO_FFMPEG_EXE`` environment variable to force using a
specific ffmpeg executable.

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).

    N   )Formatimage_as_uintwindshowlinuxvideo4linux2darwinavfoundationzunknown-cam-formatFc                      t          d          )NzYimageio.ffmpeg.download() has been deprecated. Use 'pip install imageio-ffmpeg' instead.'RuntimeError)	directoryforce_downloads     V/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/imageio/plugins/ffmpeg.pydownloadr      s    
	5      c                  (    t          j                    S )z+Wrapper for imageio_ffmpeg.get_ffmpeg_exe())imageio_ffmpegget_ffmpeg_exe r   r   get_exer      s     (***r   c                   j    e Zd ZdZd Zd Z G d dej                  Z G d dej                  ZdS )	FfmpegFormatzSRead/Write ImageResources using FFMPEG.

    See :mod:`imageio.plugins.ffmpeg`
    c                 ^    t          j        d|j                  rdS |j        | j        v rdS d S )N<video(\d+)>T)rematchfilename	extension
extensionsselfrequests     r   	_can_readzFfmpegFormat._can_read   s?     8OW%566 	4 //4 0/r   c                 &    |j         | j        v rdS d S )NT)r    r!   r"   s     r   
_can_writezFfmpegFormat._can_write   s    //4 0/r   c                   j    e Zd ZdZdZd Z	 	 	 	 	 	 	 	 	 ddZd Zd Zd Z	d Z
d	 ZddZddZd ZdS )FfmpegFormat.ReaderNc                 <   t           j                            d          rd| j        j        dd         z   S t           j                            d          rt
          }|                                dddt          d	d
g}t          j	        |t          j
        t          j
        ddd          }	 t          |j                  |         }n # t          $ r t          d|z            w xY wd|z  S t           j                            d          rt          |          }|S dS )Nr   z/dev/   r   z-list_devicestrue-fz-idummyzutf-8TF)stdoutstderrencodingshellcheckzNo ffdshow camera at index %i.zvideo=%sr
   z??)sysplatform
startswithr$   _videor   r   
CAM_FORMATsprunPIPEparse_device_namesr1   
IndexErrorstr)r#   index
ffmpeg_apicmdcompleted_processnames         r   _get_cam_inputnamez&FfmpegFormat.Reader._get_cam_inputname   s4   |&&w// ,!4QrT!:::((// )+
--//# %'F77$% % %!O-.?.FGGNDD! O O O$%E%MNNNO!D((((22  5zz ts   ,C C$Fc
                 6   t           | _        t          |          | _        |d | _        nPt          |t                    rd|z  | _        n0t          |t                    rd|v r|| _        nt          d          |n$t          |t                    st          d          |t          j
        d          | _        n`t          j
        |          | _        ddg}
| j        j        |
vr5t          d                    d                    |
                              || _        |pg | _        |pg | _        | xj        |pg z  c_        d | j        _        t)          j        d	| j        j                  }|r| j        j        | j        _        | j        j        r=t/          |                    d
                    }|                     |          | _        n>| j                                        | _        | j                            dd          | _        d| _        | j        j        dk    rd| _        d
| _        nd| _        d| _        d| _         ddi| _!        d | _"        tG          d          | _$        | j        r%| j        j        s| %                                | _$        | j$        | j!        d<   dx}}| j        j        rctM          j'                    (                                dk    r:dt          | j                  vrd}| j        j)        *                    dd           sd}|r6| j        +                    dt          tG          d                    g           |r6| j        +                    dt          tG          d                    g           	 | ,                                 nL# tZ          $ r? |r9t          tG          d                    | j        d<   | ,                                 n Y nw xY w| j        j        rt]          | j/                  | _0        d S d S )Nz%ix%ixz"FFMPEG size must be tuple of "NxM"zFFMPEG pixelformat must be struint8uint16zdtype must be one of: {}z, r   r+   ^z^^   rgb24rgb48ler   r,   pluginffmpeginfnframesFr
   z
-framerateTfps   -r   )1r   _ffmpeg_apibool	_arg_loop	_arg_size
isinstancetupler?   
ValueErrornpdtype_dtyperD   formatjoin_arg_pixelformat_arg_input_params_arg_output_paramsr$   r8   r   r   r   intgrouprE   	_filenameget_local_filenamereplace_depth_pix_fmt_bytes_per_channel_pos_meta	_lastreadfloat_nframescount_framesr6   systemlowerkwargsgetextend_initializer>   FrameCatcher	_read_gen_frame_catcher)r#   loopsizer^   pixelformat
print_infoffmpeg_paramsinput_paramsoutput_paramsrR   allowed_dtypesregex_matchr@   need_input_fpsneed_output_fpss                  r   _openzFfmpegFormat.Reader._open   s     .D!$ZZDN|!%D%(( G!(4D#&& G3$;;!% !EFFF"S11 C !ABBB} hw// huoo")8!4;#>99$299$))N:S:STT   %0D!%1%7RD"&3&9rD#""m&9r9"""&DL(?DL4IJJK <&*l&;#|" CK--a0011!%!8!8!?!?!%!@!@!B!B!%!7!7T!B!BDK{7** '*+'' )*+'DI"H-DJ!DN
 "%LLDM~ 4dl&9 4 $ 1 1 3 3$(MDJy! 054N_|" +x'8'8'>'>'@'@H'L'Ls4+A'B'BBB%)N|*..ud;; +&*O N&--|Sr^^.LMMM G'..c%))nn/EFFF  """"   ! 14U2YYD*2.$$&&&& '&	 |" C&24>&B&B###C Cs   N& &AO/.O/c                     | j          | j                                          d | _         | j        "| j                                         d | _        d S d S N)r{   stop_merz   closer#   s    r   _closezFfmpegFormat.Reader._closek  sY     ".#++---&*#~)$$&&&!% *)r   c                 F    | j         j        } || j                  d         S )zCount 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.
            r   )rV   count_frames_and_secsrg   )r#   cfs     r   rr   z FfmpegFormat.Reader.count_framesu  s&     !7B2dn%%a((r   c                     | j         S r   )rq   r   s    r   _get_lengthzFfmpegFormat.Reader._get_length  s
    = r   c                    | j         r"| j        t          d          k     r
|| j        z  }|| j        k    r| j        t          d          fS |dk     rt          d          || j        k    rt          d          || j        k     s|| j        dz   k    r|                     |           n |                     || j        z
  dz
             | 	                                \  }}|| _        |t          |          fS )	a1  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.rP   F)newr   zFrame index must be >= 0zReached end of videod   r+   )
rX   rq   rp   rm   ro   dictr>   rx   _skip_frames_read_frame)r#   r@   resultis_news       r   	_get_datazFfmpegFormat.Reader._get_data  s    ~ '$-%,,">">&	!!~t66 !;<<<$-'' !7888DI%%549s?+B+B$$U++++%%edi&7!&;<<<!%!1!1!3!3!	t/////r   c                     | j         S r   )rn   )r#   r@   s     r   _get_meta_dataz"FfmpegFormat.Reader._get_meta_data  s
    :r   r   c                    | j         | j                                          g }g }|| j        z  }| j        j        r3|dt
          gz  }| j        r|d| j        gz  }| j        r|d| j        gz  }n?|dk    r9|| j        d         z  }t          d|          }||z
  }|dd|z  gz  }|dd|z  gz  }| j        r|d| j        gz  }| j        j
                            dd           r)t          | j        j
        d                   }|d	d
|z  gz  }|| j        z  }| j        }| j        | j        z  }	| j        j        }
 |
| j        ||	||          | _         | j        j        r	 | j                                         }| j                            |           d S # t,          $ rX}t/          |          }dt0          j        v r	d|v r|dz  }t5          d                    | j        j        |                    d }~ww xY w|dk    r3| j                            | j                                                    d S | j                                          d S )Nr.   z-pix_fmtz-sr   rR   
   z-ssz%.06frT   z%.02f)r   r   r
   z$Unknown input format: 'avfoundation'zPTry installing FFMPEG using home brew to get a version with support for cameras.zNo (working) camera at {}.

{})rz   r   rc   r$   r8   r9   rb   rY   rn   minru   rv   rp   rd   rk   rj   rl   rV   read_framesrg   __next__updateIOErrorr?   r5   r6   r>   r`   )r#   r@   iargsoargs	starttime	seek_slow	seek_fastrR   pix_fmtbpprfmetaerrerr_texts                 r   rx   zFfmpegFormat.Reader._initialize  s   ~)$$&&&EE T++E|" 8$
++( Aj$*?@@E> 4dDN33E "DJu$55	I..	%	1	 %I!677%I!677 ~ 0$//|"&&ud33 /DL/677$#..T,,E mG+ 77C !-BR5PU  DN
 |" *,>2244D  J%%d+++++    "3xxH3<//AXMM$!7H
 %:AA L/     !
!!$."9"9";";<<<<<'')))))s   F 
G3AG..G3r+   c                 |    t          |          D ]}| j                                         | xj        |z  c_        dS )zReads and throws away n framesN)rangerz   r   rm   )r#   nis      r   r   z FfmpegFormat.Reader._skip_frames  sA    1XX * *''))))IINIIIIr   c                    | j         d         \  }}||z  | j        z  | j        z  }| j        r| j                                        \  }}n| j                                        }d}t          |          |k    r!t          dt          |          |fz            t          j
        || j                                                  }|                    ||| j        f          }|| _        ||fS )Nr}   Tz#Frame is %i bytes, but expected %i.)r^   )rn   rj   rl   r{   	get_framerz   r   lenr   r]   
frombufferr_   copyreshapero   )r#   wh	framesizesr   r   s          r   r   zFfmpegFormat.Reader._read_frame  s    :f%DAqA+d.EEI "  /99;;	66N++-- 1vv"""9SVVY<OO   ]1DK888==??F^^Q4;$788F
 $DN6>!r   )	FNNNFNNNN)r   )r+   )__name__
__module____qualname__r{   rz   rE   r   r   rr   r   r   r   rx   r   r   r   r   r   Readerr)      s        	-	 -	 -	b h	C h	C h	C h	Cb	& 	& 	&	) 	) 	)	! 	! 	!	0 	0 	02	 	 	N	* N	* N	* N	*`	 	 	 		" 	" 	" 	" 	"r   r   c                   J    e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 ddZd	 Zd
 Zd Zd ZdS )FfmpegFormat.WriterNr   libx264yuv420pquiet      c                     t           | _        | j                                        | _        d | _        d | _        d | _        d S r   )r   rV   r$   rh   rg   rk   rj   _size)r#   rR   codecbitrater~   r   r   r   ffmpeg_log_levelqualitymacro_block_size
audio_pathaudio_codecs                r   r   zFfmpegFormat.Writer._open  s:      .D!\<<>>DN DMDKDJJJr   c                 X    | j         "| j                                          d | _         d S d S r   )
_write_genr   r   s    r   r   zFfmpegFormat.Writer._close.  s1    *%%'''"& +*r   c                 8   |j         d d         \  }}||f}|j        dk    rdn|j         d         }t          |d          }|j        j        st          j        |          }| j        Zddddd	}|                    |d           | _	        | j	        t          d
          || _        || _        |                                  || j        k    rt          d          || j        k    rt          d          | j        J | j                            |           d S )Nr   r+      )bitdepthgraygray8arL   rgba)r+   r   rK      z%Image must have 1, 2, 3 or 4 channelsz+All images in a movie should have same sizez9All images in a movie should have same number of channels)shapendimr   flagsc_contiguousr]   ascontiguousarrayr   rv   rk   r\   rj   rx   r   send)r#   imr   r   r   r}   depthmaps           r   _append_dataz FfmpegFormat.Writer._append_data3  sA   8BQB<DAqa4DAAA28A;E rA...B 8( . )"-- z! X'fEE #t 4 4=($%LMMM!
#  """ tz!! !NOOO## R   ?... O  $$$$$r   c                      t          d          )Nz5The ffmpeg format does not support setting meta data.r   )r#   r   s     r   set_meta_dataz!FfmpegFormat.Writer.set_meta_dataZ  s    J  r   c                    | j         | j                                          | j        j                            dd          }| j        j                            dd           }| j        j                            dd           }| j        j                            dd           }| j        j                            d          pg }| j        j                            d          pg }|| j        j                            d          pg z  }| j        j                            d	d           }| j        j                            d
d          }| j        j                            dd           }	| j        j                            dd           }
| j        j                            dd           }|pd}| j                            | j        | j        | j	        |||||||	|||
|          | _         | j         
                    d            d S )NrR   r   r   r   r   r   r   r   r~   r   r   r   r   r   r+   )
pix_fmt_inpix_fmt_outrR   r   r   r   r   r   r   r   r   r   )r   r   r$   ru   rv   rV   write_framesrg   r   rk   r   )r#   rR   r   r   r   r   r   r~   r   r   r   r   s               r   rx   zFfmpegFormat.Writer._initialize_  s   *%%''' ,%))%44CL'++GT::El)--i>>Gl)--i>>G<.22>BBHbL L/33ODDJMT\044_EEKKM,-11-FFK#|2667I2NN#|2667I4PP,00tDDJ,-11-FFK/41 #.;;
='!1!1)+%' <  DO$ O  &&&&&r   )r   r   Nr   NNNr   r   r   NN)	r   r   r   r   r   r   r   r   rx   r   r   r   Writerr     s        
 !$	 	 	 	*	' 	' 	'
%	% %	% %	%N	 	 	
)	' )	' )	' )	' )	'r   r   N)	r   r   r   __doc__r%   r'   r   r   r   r   r   r   r   r      s         
	 	 	  K" K" K" K" K" K" K" K"^
r' r' r' r' r' r' r' r' r' r'r   r   c                   *    e Zd ZdZd Zd Zd Zd ZdS )ry   aM  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                     || _         d | _        d| _        t          j                    | _        t          j                            |            d| _        d| _	        | 
                                 d S )NFT)_gen_frame_frame_is_new	threadingRLock_lockThread__init__daemon_should_stopstart)r#   gens     r   r   zFrameCatcher.__init__  s^    	"_&&
!!$'''!

r   c                     d| _         |                                 r*t          j        d           |                                 (d S d S )NTMbP?)r   is_alivetimesleepr   s    r   r   zFrameCatcher.stop_me  sP     mmoo 	Ju mmoo 	 	 	 	 	r   c                     | j         t          j        d           | j         | j        5  | j        }d| _        | j         |fcd d d            S # 1 swxY w Y   d S )Nr   F)r   r   r   r   r   )r#   r   s     r   r   zFrameCatcher.get_frame  s    k!Ju k!Z 	' 	''F!&D;&	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	' 	's   AAAc                    	 | j         sct          j        d           | j                                        }| j        5  || _        d| _        d d d            n# 1 swxY w Y   | j         ad S d S # t          t          f$ r Y d S w xY w)Nr   T)
r   r   r   r   r   r   r   r   StopIterationEOFError)r#   frames     r   r;   zFrameCatcher.run  s    	' .
1	**,,Z . ."'DK)-D&. . . . . . . . . . . . . . . ' . . . . . x( 	 	 	DD	s4   ;A. AA. AA. A 
A. .BBN)r   r   r   r   r   r   r   r;   r   r   r   ry   ry     sZ             
' ' '
 
 
 
 
r   ry   c                    g }d}|                                  D ]`}|                    d          rGt                              |           |                    dd          d                                         }|r7|                    d          r"|dd         }|                    |dg           |r|                                                    d          r|                    d	d          d                                         dd         }t          j	                            d
          r|
                    dd          }n|
                    dd          }||d         d<   Rd|v rd}Zd|v rd}bg }|D ]L\  }}||vr|                    |           |r|                    |           7|                    |           M|S )z4Parse the output of the ffmpeg -list-devices commandFz[dshow]r+   "r,    zalternative namez name r   &z^&z\&zvideo devicesTdevices)
splitlinesr7   loggerdebugsplitstripappendrt   r5   r6   ri   )ffmpeg_outputdevice_namesin_video_deviceslinefriendly_namealt_namedevice_names2s          r   r=   r=     s     L((** ) )??8$$ 	)LL::c1%%a(..00D )DOOC$8$8 ) $QrT
##]B$78888! )djjll&=&=>P&Q&Q )::h2215;;==adC<**511 <'//T::HH'//U;;H'/R $$ D((#'  d""#(  M#/ 0 0x--  //// 	0  ****  ////r   )NF)r   r   r5   r   loggingr6   r   
subprocessr:   r   numpyr]   corer   r   	getLoggerr   r  r7   r9   r   r   r   r   ry   r=   r   r   r   <module>r     s  B BH 
			 



                    ( ( ( ( ( ( ( (		8	$	$ <5!! &JJ\W%% &JJ\X&& &JJ%J   + + +X' X' X' X' X'6 X' X' X'v) ) ) ) )9# ) ) )X" " " " "r   