U
    a+d$                     @   st  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	m
Z
mZ ddlmZ ddlmZmZ ddlmZ ddlmZmZmZmZmZmZmZ dd	lmZmZmZmZmZ d
dl m!Z! d
dl"m#Z#m$Z$m%Z% d
dl&m'Z' G dd deZ(G dd de(Z)G dd de(Z*G dd de(Z+ee(j,de(_-ee(j.de(_/ee(j#de(_0ee(j1de(_2G dd de+Z3G dd de+Z4dS )z
This module implements VideoClip (base class for video clips) and its
main subclasses:
- Animated clips:     VideofileClip, ImageSequenceClip
- Static image clips: ImageClip, ColorClip, TextClip,
    N)imreadimsave   )Clip)DEVNULLstring_types)get_setting)add_mask_if_noneapply_to_maskconvert_masks_to_RGBconvert_to_secondsoutplacerequires_durationuse_clip_fps_by_default)deprecated_version_ofextensions_dictfind_extension	is_stringsubprocess_call   )ffmpeg_write_video)	write_gifwrite_gif_with_image_iowrite_gif_with_tempfiles)blitc                   @   sP  e Zd ZdZdAddZedd Zed	d
 Zedd Ze	dge
dBddZeee
dCddZeee
dDddZee
dEddZdFdd ZdGd!d"ZdHd$d%Zd&d' Zd(d) ZdId+d,Zed-d. Zed/d0 Zed1d2 Zeed3d4 ZeedJd5d6Ze	dgdKd7d8ZdLd9d:Z d;d< Z!ed=d> Z"ed?d@ Z#dS )M	VideoClipa  Base class for video clips.

    See ``VideoFileClip``, ``ImageClip`` etc. for more user-friendly
    classes.


    Parameters
    -----------

    ismask
      `True` if the clip is going to be used as a mask.


    Attributes
    ----------

    size
      The size of the clip, (width,heigth), in pixels.

    w, h
      The width and height of the clip, in pixels.

    ismask
      Boolean set to `True` if the clip is a mask.

    make_frame
      A function ``t-> frame at time t`` where ``frame`` is a
      w*h*3 RGB array.

    mask (default None)
      VideoClip mask attached to this clip. If mask is ``None``,
                The video clip is fully opaque.

    audio (default None)
      An AudioClip instance containing the audio of the video clip.

    pos
      A function ``t->(x,y)`` where ``x,y`` is the position
      of the clip when it is composed with other clips.
      See ``VideoClip.set_pos`` for more details

    relative_pos
      See variable ``pos``.

    NFTc                 C   st   t |  d | _d | _dd | _d| _|rP|| _| djd d d d d | _	|| _
|| _|d k	rp|| _|| _d S )Nc                 S   s   dS )Nr   r    tr   r   ;/tmp/pip-unpacked-wheel-0yp4gafk/moviepy/video/VideoClip.py<lambda>R       z$VideoClip.__init__.<locals>.<lambda>Fr   r   )r   __init__maskaudioposrelative_pos
make_frame	get_frameshapesizeismaskhas_constant_sizedurationend)selfr)   r-   r/   r.   r   r   r    r$   M   s    

 zVideoClip.__init__c                 C   s
   | j d S )Nr   r,   r1   r   r   r    w]   s    zVideoClip.wc                 C   s
   | j d S )Nr   r2   r3   r   r   r    ha   s    zVideoClip.hc                 C   s   | j t| j S N)r4   floatr5   r3   r   r   r    aspect_ratioe   s    zVideoClip.aspect_ratior   r   c                 C   sV   |  |}|r>| jdk	r>d| j | }t||gd}n
|d}t|| dS )as   Save a clip's frame to an image file.

        Saves the frame of clip corresponding to time ``t`` in
        'filename'. ``t`` can be expressed in seconds (15.35), in
        (min, sec), in (hour, min, sec), or as a string: '01:03:05.35'.

        If ``withmask`` is ``True`` the mask is saved in
        the alpha layer of the picture (only works with PNGs).

        N   uint8)r*   r%   npdstackastyper   )r1   filenamer   withmaskZimr%   r   r   r    
save_framel   s    

zVideoClip.save_frameD  medium     barc                 C   s  t jt j|\}}|dd  }t|}|dkrlzt| d d }W n tk
rj   t	dY nX |	dkr|dkrd}	qd}	n|	d	krd
}	n|	dkrd}	t
|r|nd}|dko|dko| jdk	}|r|r|}n|rt|	}|tj d|  }|d| d |r*| jj|||||	|
|||d	 t| |||||||||||d |rn|rnt j|rnt | |d| d dS )a  Write the clip to a videofile.

        Parameters
        -----------

        filename
          Name of the video file to write in.
          The extension must correspond to the "codec" used (see below),
          or simply be '.avi' (which will work with any codec).

        fps
          Number of frames per second in the resulting video file. If None is
          provided, and the clip has an fps attribute, this fps will be used.

        codec
          Codec to use for image encoding. Can be any codec supported
          by ffmpeg. If the filename is has extension '.mp4', '.ogv', '.webm',
          the codec will be set accordingly, but you can still set it if you
          don't like the default. For other extensions, the output filename
          must be set accordingly.

          Some examples of codecs are:

          ``'libx264'`` (default codec for file extension ``.mp4``)
          makes well-compressed videos (quality tunable using 'bitrate').


          ``'mpeg4'`` (other codec for extension ``.mp4``) can be an alternative
          to ``'libx264'``, and produces higher quality videos by default.


          ``'rawvideo'`` (use file extension ``.avi``) will produce
          a video of perfect quality, of possibly very huge size.


          ``png`` (use file extension ``.avi``) will produce a video
          of perfect quality, of smaller size than with ``rawvideo``.


          ``'libvorbis'`` (use file extension ``.ogv``) is a nice video
          format, which is completely free/ open source. However not
          everyone has the codecs installed by default on their machine.


          ``'libvpx'`` (use file extension ``.webm``) is tiny a video
          format well indicated for web videos (with HTML5). Open source.


        audio
          Either ``True``, ``False``, or a file name.
          If ``True`` and the clip has an audio clip attached, this
          audio clip will be incorporated as a soundtrack in the movie.
          If ``audio`` is the name of an audio file, this audio file
          will be incorporated as a soundtrack in the movie.

        audiofps
          frame rate to use when generating the sound.

        temp_audiofile
          the name of the temporary audiofile to be generated and
          incorporated in the the movie, if any.

        audio_codec
          Which audio codec should be used. Examples are 'libmp3lame'
          for '.mp3', 'libvorbis' for 'ogg', 'libfdk_aac':'m4a',
          'pcm_s16le' for 16-bit wav and 'pcm_s32le' for 32-bit wav.
          Default is 'libmp3lame', unless the video extension is 'ogv'
          or 'webm', at which case the default is 'libvorbis'.

        audio_bitrate
          Audio bitrate, given as a string like '50k', '500k', '3000k'.
          Will determine the size/quality of audio in the output file.
          Note that it mainly an indicative goal, the bitrate won't
          necessarily be the this in the final file.

        preset
          Sets the time that FFMPEG will spend optimizing the compression.
          Choices are: ultrafast, superfast, veryfast, faster, fast, medium,
          slow, slower, veryslow, placebo. Note that this does not impact
          the quality of the video, only the size of the video file. So
          choose ultrafast when you are in a hurry and file size does not
          matter.

        threads
          Number of threads to use for ffmpeg. Can speed up the writing of
          the video on multicore computers.

        ffmpeg_params
          Any additional ffmpeg parameters you would like to pass, as a list
          of terms, like ['-option1', 'value1', '-option2', 'value2'].

        write_logfile
          If true, will write log files for the audio and the video.
          These will be files ending with '.log' with the name of the
          output file in them.

        logger
          Either "bar" for progress bar or None or any Proglog logger.

        verbose (deprecated, kept for compatibility)
          Formerly used for toggling messages on/off. Use logger=None now.

        Examples
        ========

        >>> from moviepy.editor import VideoFileClip
        >>> clip = VideoFileClip("myvideo.mp4").subclip(100,120)
        >>> clip.write_videofile("my_new_video.mp4")
        >>> clip.close()

        r   Ncodecr   zoMoviePy couldn't find the codec associated with the filename. Provide the 'codec' parameter in write_videofile.)ZogvZwebmZ	libvorbisZ
libmp3lameZraw16Z	pcm_s16leZraw32Z	pcm_s32leTz
wvf_snd.%szMoviepy - Building video %s.message)bitratewrite_logfileverboselogger)rI   presetrJ   	audiofilerK   threadsffmpeg_paramsrL   zMoviepy - video ready %s)ospathsplitextbasenamelowerproglogdefault_bar_loggerr   KeyError
ValueErrorr   r&   r   r   Z_TEMP_FILES_PREFIXZwrite_audiofiler   existsremove)r1   r>   fpsrF   rI   r&   Z	audio_fpsrM   Zaudio_nbytesZaudio_codecZaudio_bitrateZaudio_bufsizeZtemp_audiofileZrewrite_audioremove_temprJ   rK   rO   rP   rL   nameextrN   Z
make_audioZ	audio_extr   r   r    write_videofile   sd    |

  
 	
zVideoClip.write_videofilec                 C   s   t |}|d| d td| jd| }g }|jtt|dD ]*\}}	|| }
||
 | j	|
|	|d qD|d| d |S )a   Writes the videoclip to a sequence of image files.

        Parameters
        -----------

        nameformat
          A filename specifying the numerotation format and extension
          of the pictures. For instance "frame%03d.png" for filenames
          indexed with 3 digits and PNG format. Also possible:
          "some_folder/frame%04d.jpeg", etc.

        fps
          Number of frames per second to consider when writing the
          clip. If not specified, the clip's ``fps`` attribute will
          be used if it has one.

        withmask
          will save the clip's mask (if any) as an alpha canal (PNGs only).

        verbose
          Boolean indicating whether to print information.

        logger
          Either 'bar' (progress bar) or None or any Proglog logger.


        Returns
        --------

        names_list
          A list of all the files generated.

        Notes
        ------

        The resulting image sequence can be read using e.g. the class
        ``ImageSequenceClip``.

        zMoviepy - Writing frames %s.rG   r         ?r   )r?   z!Moviepy - Done writing frames %s.)
rV   rW   r;   Zaranger/   Ziter_barlist	enumerateappendr@   )r1   Z
nameformatr\   rK   r?   rL   tt	filenamesir   r^   r   r   r    write_images_sequence:  s    ,

zVideoClip.write_images_sequenceimageionqr   c                 C   s   |dkr"t | ||||||	|d nb|
rV|dkr2dnd}t| |||||||||	|d n.|dkrbdnd}t| |||||||||	|d dS )a7   Write the VideoClip to a GIF file.

        Converts a VideoClip into an animated GIF using ImageMagick
        or ffmpeg.

        Parameters
        -----------

        filename
          Name of the resulting gif file.

        fps
          Number of frames per second (see note below). If it
          isn't provided, then the function will look for the clip's
          ``fps`` attribute (VideoFileClip, for instance, have one).

        program
          Software to use for the conversion, either 'imageio' (this will use
          the library FreeImage through ImageIO), or 'ImageMagick', or 'ffmpeg'.

        opt
          Optimalization to apply. If program='imageio', opt must be either 'wu'
          (Wu) or 'nq' (Neuquant). If program='ImageMagick',
          either 'optimizeplus' or 'OptimizeTransparency'.

        fuzz
          (ImageMagick only) Compresses the GIF by considering that
          the colors that are less than fuzz% different are in fact
          the same.

        tempfiles
          Writes every frame to a file instead of passing them in the RAM.
          Useful on computers with little RAM. Can only be used with
          ImageMagick' or 'ffmpeg'.

        progress_bar
          If True, displays a progress bar


        Notes
        -----

        The gif will be playing the clip in real time (you can
        only change the frame rate). If you want the gif to be played
        slower than the clip you will use ::

            >>> # slow down clip 50% and make it a gif
            >>> myClip.speedx(0.5).to_gif('myClip.gif')

        ri   )r\   optlooprK   colorsrL   rj   ZoptimizeplusZOptimizeTransparency)	r\   programrk   fuzzrK   rl   disposerm   rL   N)r   r   r   )r1   r>   r\   rn   rk   ro   rK   rl   rp   rm   Z	tempfilesrL   r   r   r    r   t  s8    ;     
    zVideoClip.write_gifc           
      K   sn   |r|  d|nd}|  ||j|f|}|r:| j |dnd}dd |||fD }ddlm}	 |	|| jS )a  Apply a transformation to a part of the clip.

        Returns a new clip in which the function ``fun`` (clip->clip)
        has been applied to the subclip between times `ta` and `tb`
        (in seconds).

        Examples
        ---------

        >>> # The scene between times t=3s and t=6s in ``clip`` will be
        >>> # be played twice slower in ``newclip``
        >>> newclip = clip.subapply(lambda c:c.speedx(0.5) , 3,6)

        r   N)Zt_startc                 S   s   g | ]}|r|qS r   r   ).0cr   r   r    
<listcomp>  s      z#VideoClip.subfx.<locals>.<listcomp>)concatenate_videoclips)ZsubclipfxZ%moviepy.video.compositing.concatenatert   Z	set_startstart)
r1   ru   tatbkwargsleftcenterrightZclipsrt   r   r   r    subfx  s    zVideoClip.subfxc                    s   |pg }|   fdd|S )z
        Modifies the images of a clip by replacing the frame
        `get_frame(t)` by another frame,  `image_func(get_frame(t))`
        c                    s    | |S r6   r   )Zgfr   
image_funcr   r    r!     r"   z$VideoClip.fl_image.<locals>.<lambda>)fl)r1   r   apply_tor   r~   r    fl_image  s    zVideoClip.fl_imager   c                 C   s   |j }|d |d  }|d |d  }|}|dk rD|d |d  }n0|dkrtdddgg|d  g| }t||f}|dk r|d d d |d f }n2|dkrdddgg| g|j d  }t||f}|S )Nr   r   )r+   r;   ZvstackZhstack)r1   Z	pre_arrayr+   Z	pre_shapeZdxZdyZ
post_arrayZx_1r   r   r    
fill_array  s    zVideoClip.fill_arrayc              	   C   s  |j dd  \}}}| jrB| rBtd|| t|| S || j }| |}| j	rh| j	|nd}|dk	r|j d |j d ks|j d |j d kr| 
||j }|j dd \}	}
| |}t|trddgddgddgddgdd	gd
| }nt|}| jrBt||gD ]*\}}t|| ts|||  ||< qt|d trzd||
 d ||
 d}||d  |d< t|d trd||	 d ||	 d}||d  |d< tt|}t||||| jdS )z
        Returns the result of the blit of the clip's frame at time `t`
        on the given `picture`, the position of the clip being given
        by the clip's ``pos`` attribute. Meant for compositing.
        Nr   r   r   r{   rz   r|   topbottom)r{   rz   r|   r   r   )rz   r{   r|   )r   r{   r   )r%   r-   )r+   r-   maxr;   Zminimumblit_onzerosrv   r*   r%   r   r'   
isinstancestrrb   r(   rc   mapintr   )r1   Zpicturer   ZhfZwfZ	framesizectimgr%   hiZwir'   rg   ZdimDr   r   r    r      s@    

0


zVideoClip.blit_onc                    sV    j r(t jddd} | jS  fdd}td|d} | jS dS )aL  Add a mask VideoClip to the VideoClip.

        Returns a copy of the clip with a completely opaque mask
        (made of ones). This makes computations slower compared to
        having a None mask but can be useful in many cases. Choose

        Set ``constant_size`` to  `False` for clips with moving
        image size.
        ra   Tr-   c                    s   t j | jd d tdS )Nr   )Zdtype)r;   Zonesr*   r+   r7   r   r3   r   r    r!   D  r"   z$VideoClip.add_mask.<locals>.<lambda>)r-   r)   N)r.   	ColorClipr,   set_maskset_durationr/   r   )r1   r%   r)   r   r3   r    add_mask6  s    
zVideoClip.add_maskr   r   r   c           	      C   s   ddl m} |dkr| j}|dkr&d}t||d}|dk	rdt||| jd|}||| |g}n|| |g||d}t| trt	|ds| j
dkst| j
tr| }|j
dk	r|j
 |_
||jS |S )	a  Place the clip on a colored background.

        Returns a clip made of the current clip overlaid on a color
        clip of a possibly bigger size. Can serve to flatten transparent
        clips.

        Parameters
        -----------

        size
          Size (width, height) in pixels of the final clip.
          By default it will be the size of the current clip.

        color
          Background color of the final clip ([R,G,B]).

        pos
          Position of the clip in the final clip. 'center' is the default

        col_opacity
          Parameter in 0..1 indicating the opacity of the colored
          background.

        r   )CompositeVideoClipNr{   )color)r   r/   )r,   bg_color__call__)Zcompositing.CompositeVideoClipr   r,   r   r/   set_opacityset_positionr   	ImageCliphasattrr%   to_ImageClipr   )	r1   r,   r   r'   Zcol_opacityr   Z	colorclipresultZ
new_resultr   r   r    on_colorH  s2    

zVideoClip.on_colorc                 C   s*   || _ | djdd ddd | _dS )zChange the clip's ``get_frame``.

        Returns a copy of the VideoClip instance, with the make_frame
        attribute set to `mf`.
        r   Nr   r#   )r)   r*   r+   r,   )r1   Zmfr   r   r    set_make_frame|  s    zVideoClip.set_make_framec                 C   s
   || _ dS )zAttach an AudioClip to the VideoClip.

        Returns a copy of the VideoClip instance, with the `audio`
        attribute set to ``audio``, which must be an AudioClip instance.
        Nr&   )r1   Z	audioclipr   r   r    	set_audio  s    zVideoClip.set_audioc                 C   s   |dks|j st|| _dS )zSet the clip's mask.

        Returns a copy of the VideoClip with the mask attribute set to
        ``mask``, which must be a greyscale (values in 0-1) VideoClipN)r-   AssertionErrorr%   )r1   r%   r   r   r    r     s    zVideoClip.set_maskc                    s   | j  fdd| _ dS )zSet the opacity/transparency level of the clip.

        Returns a semi-transparent copy of the clip where the mask is
        multiplied by ``op`` (any float, normally between 0 and 1).
        c                    s    |  S r6   r   Zpicopr   r    r!     r"   z'VideoClip.set_opacity.<locals>.<lambda>N)r%   r   )r1   r   r   r   r    r     s    zVideoClip.set_opacityc                    s*   || _ t dr | _n fdd| _dS )aC  Set the clip's position in compositions.

        Sets the position that the clip will have when included
        in compositions. The argument ``pos`` can be either a couple
        ``(x,y)`` or a function ``t-> (x,y)``. `x` and `y` mark the
        location of the top left corner of the clip, and can be
        of several types.

        Examples
        ----------

        >>> clip.set_position((45,150)) # x=45, y=150
        >>>
        >>> # clip horizontally centered, at the top of the picture
        >>> clip.set_position(("center","top"))
        >>>
        >>> # clip is at 40% of the width, 70% of the height:
        >>> clip.set_position((0.4,0.7), relative=True)
        >>>
        >>> # clip's position is horizontally centered, and moving up !
        >>> clip.set_position(lambda t: ('center', 50+t) )

        r   c                    s    S r6   r   r   r'   r   r    r!     r"   z(VideoClip.set_position.<locals>.<lambda>N)r(   r   r'   )r1   r'   relativer   r   r    r     s    
zVideoClip.set_positionc                 C   s6   t | || j|d}|r2| jdk	r2| j||_|S )z
        Returns an ImageClip made out of the clip's frame at time ``t``,
        which can be expressed in seconds (15.35), in (min, sec),
        in (hour, min, sec), or as a string: '01:03:05.35'.
        r-   r/   N)r   r*   r-   r%   r   )r1   r   Z	with_maskr/   newclipr   r   r    r     s    zVideoClip.to_ImageClipc                    s*   | j r
| S |  fdd}d|_ |S dS )z.Return a mask a video clip made from the clip.c                    s   d| d d d d  f  d S )Nra   r9   r   r   canalr   r    r!     s    z#VideoClip.to_mask.<locals>.<lambda>TNr-   r   )r1   r   r   r   r   r    to_mask  s
    zVideoClip.to_maskc                 C   s*   | j r"dd }| |}d|_ |S | S dS )z;Return a non-mask video clip made from the mask video clip.c                 S   s   t dd|  g dS )N   r9   r:   )r;   r<   r=   r   r   r   r    r!     r"   z"VideoClip.to_RGB.<locals>.<lambda>FNr   )r1   fr   r   r   r    to_RGB  s    
zVideoClip.to_RGBc                 C   s
   d| _ dS )z]Remove the clip's audio.

        Return a copy of the clip with audio set to None.

        Nr   r3   r   r   r    without_audio  s    zVideoClip.without_audioc                 O   s   | j j|f||| _ dS )zmTransform the clip's audio.

        Return a new clip whose audio has been transformed by ``fun``.

        N)r&   ru   )r1   Zfunakr   r   r    afx  s    zVideoClip.afx)NFNT)r   T)NNNTrA   rB   rC   NNrD   NTTFTNNrE   )NTTrE   )
Nri   rj   r   Tr   FNFrE   )r   N)N)r   )Nr   NN)F)r   TN)r   )$__name__
__module____qualname____doc__r$   propertyr4   r5   r8   r   r   r@   r   r   r`   rh   r   r}   r   r   r   r   r   r   r   r   r   r	   r   r
   r   r   r   r   r   r   r   r   r   r    r      s   .  



                         5    7              R


6  
4
	

!


r   c                   @   s   e Zd ZdZdddZdS )DataVideoClipa  
    Class of video clips whose successive frames are functions
    of successive datasets

    Parameters
    -----------
    data
      A liste of datasets, each dataset being used for one frame of the clip

    data_to_frame
      A function d -> video frame, where d is one element of the list `data`

    fps
      Number of frames per second in the animation

    Examples
    ---------
    FTc                    sB   | _ | _| _ fdd}tj ||dt| | |d d S )Nc                    s      jt j|   S r6   )data_to_framedatar   r\   r   r3   r   r    r!     r"   z(DataVideoClip.__init__.<locals>.<lambda>ra   )r-   r/   r.   )r   r   r\   r   r$   len)r1   r   r   r\   r-   r.   r)   r   r3   r    r$     s    
zDataVideoClip.__init__N)FTr   r   r   r   r$   r   r   r   r    r     s     r   c                   @   s   e Zd ZdZdddZdS )UpdatedVideoClipa  
    Class of clips whose make_frame requires some objects to
    be updated. Particularly practical in science where some
    algorithm needs to make some steps before a new frame can
    be generated.

    UpdatedVideoClips have the following make_frame:

    >>> def make_frame(t):
    >>>     while self.world.clip_t < t:
    >>>         world.update() # updates, and increases world.clip_t
    >>>     return world.to_frame()

    Parameters
    -----------

    world
      An object with the following attributes:
      - world.clip_t : the clip's time corresponding to the
          world's state
      - world.update() : update the world's state, (including
        increasing world.clip_t of one time step)
      - world.to_frame() : renders a frame depending on the world's state

    ismask
      True if the clip is a WxH mask with values in 0-1

    duration
      Duration of the clip, in seconds

    FNc                    s*    _  fdd}tj |||d d S )Nc                    s    j j| k r  q  S r6   )worldZclip_tupdateZto_framer   r1   r   r   r    r)   ?  s    
z-UpdatedVideoClip.__init__.<locals>.make_frame)r)   r-   r/   )r   r   r$   )r1   r   r-   r/   r)   r   r   r    r$   <  s     zUpdatedVideoClip.__init__)FNr   r   r   r   r    r     s    r   c                   @   s@   e Zd ZdZdddZdddZedd	d
ZedddZdS )r   a  Class for non-moving VideoClips.

    A video clip originating from a picture. This clip will simply
    display the given picture at all times.

    Examples
    ---------

    >>> clip = ImageClip("myHouse.jpeg")
    >>> clip = ImageClip( someArray ) # a Numpy array represent

    Parameters
    -----------

    img
      Any picture file (png, tiff, jpeg, etc.) or any array representing
      an RGB image (for instance a frame from a VideoClip).

    ismask
      Set this parameter to `True` if the clip is a mask.

    transparent
      Set this parameter to `True` (default) if you want the alpha layer
      of the picture (if it exists) to be used as a mask.

    Attributes
    -----------

    img
      Array representing the image of the clip.

    FTNc                    s"  t j| ||d t tr"t  t jdkr jd dkr|rbd d d d d df  d  q|rd d d d d df  d  q|rtd d d d d df  d dd	| _ d d d d d df  n"|rd d d d d df  d   fd
d| _	 jd d d d d | _
 | _d S )Nr   r   r   rC   ra   r9   r   Tr   c                    s    S r6   r   r   r   r   r    r!     r"   z$ImageClip.__init__.<locals>.<lambda>r#   )r   r$   r   r   r   r   r+   r   r%   r)   r,   r   )r1   r   r-   transparentZ	fromalphar/   r   r   r    r$   t  s(    
   zImageClip.__init__c                 C   s(   |dkrg }t j| |||d}t |_|S )zGeneral transformation filter.

        Equivalent to VideoClip.fl . The result is no more an
        ImageClip, it has the class VideoClip (since it may be animated)
        N)r   keep_duration)r   r   	__class__)r1   r   r   r   r   r   r   r    r     s    
zImageClip.flc                    s   |dkrg }||  d  jdd ddd | _ fdd| _ | _|D ].}t| |d}|dk	rL||}t| || qLdS )zImage-transformation filter.

        Does the same as VideoClip.fl_image, but for ImageClip the
        tranformed clip is computed once and for all at the beginning,
        and not for each 'frame'.
        Nr   r   r#   c                    s    S r6   r   r   Zarrr   r    r!     r"   z$ImageClip.fl_image.<locals>.<lambda>)r*   r+   r,   r)   r   getattrr   setattr)r1   r   r   attrr   new_ar   r   r    r     s    
zImageClip.fl_imagec                 C   sH   |dkrddg}|D ].}t | |d}|dk	r||}t| || qdS )a  Time-transformation filter.

        Applies a transformation to the clip's timeline
        (see Clip.fl_time).

        This method does nothing for ImageClips (but it may affect their
        masks or their audios). The result is still an ImageClip.
        Nr%   r&   )r   fl_timer   )r1   Z	time_funcr   r   r   r   r   r   r   r    r     s    
zImageClip.fl_time)FTFN)NT)N)NF)	r   r   r   r   r$   r   r   r   r   r   r   r   r    r   R  s   !    

  r   set_posto_videofileto_gifto_images_sequencec                   @   s   e Zd ZdZdddZdS )r   a  An ImageClip showing just one color.

    Parameters
    -----------

    size
      Size (width, height) in pixels of the clip.

    color
      If argument ``ismask`` is False, ``color`` indicates
      the color in RGB of the clip (default is black). If `ismask``
      is True, ``color`` must be  a float between 0 and 1 (default is 1)

    ismask
      Set to true if the clip will be used as a mask.

    col
      Has been deprecated. Do not use.
    NFc           	      C   s~   |d k	r.t dt |d k	r*t dt n|}|\}}t|rH||fn||t|f}tj| t	||| 
|||d d S )NzPThe `ColorClip` parameter `col` has been deprecated. Please use `color` instead.z_The arguments `color` and `col` have both been passed to `ColorClip` so `col` has been ignored.r   )warningswarnDeprecationWarningUserWarningr;   Zisscalarr   r   r$   ZtileZreshape)	r1   r,   r   r-   r/   colr4   r5   r+   r   r   r    r$     s      zColorClip.__init__)NFNNr   r   r   r   r    r     s   r   c                   @   s2   e Zd ZdZdddZedd Zedd ZdS )TextClipa  Class for autogenerated text clips.

    Creates an ImageClip originating from a script-generated text image.
    Requires ImageMagick.

    Parameters
    -----------

    txt
      A string of the text to write. Can be replaced by argument
      ``filename``.

    filename
      The name of a file in which there is the text to write.
      Can be provided instead of argument ``txt``

    size
      Size of the picture in pixels. Can be auto-set if
      method='label', but mandatory if method='caption'.
      the height can be None, it will then be auto-determined.

    bg_color
      Color of the background. See ``TextClip.list('color')``
      for a list of acceptable names.

    color
      Color of the text. See ``TextClip.list('color')`` for a
      list of acceptable names.

    font
      Name of the font to use. See ``TextClip.list('font')`` for
      the list of fonts you can use on your computer.

    stroke_color
      Color of the stroke (=contour line) of the text. If ``None``,
      there will be no stroke.

    stroke_width
      Width of the stroke, in pixels. Can be a float, like 1.5.

    method
      Either 'label' (default, the picture will be autosized so as to fit
      exactly the size) or 'caption' (the text will be drawn in a picture
      with fixed size provided with the ``size`` argument). If `caption`,
      the text will be wrapped automagically (sometimes it is buggy, not
      my fault, complain to the ImageMagick crew) and can be aligned or
      centered (see parameter ``align``).

    kerning
      Changes the default spacing between letters. For
      instance ``kerning=-1`` will make the letters 1 pixel nearer from
      ach other compared to the default spacing.

    align
      center | East | West | South | North . Will only work if ``method``
      is set to ``caption``

    transparent
      ``True`` (default) if you want to take into account the
      transparency in the image.

    Nblackr   Courierr   labelr{   TFc              
   C   st  |d k	rl|d krbt jdd\}}zt|t|d W n  tk
rV   t|| Y nX t| d| }nd| }|d k	r|d d krdn
t|d |d d krdn
t|d f}td	d
|d|d|g}|d k	r|dd| g7 }|d k	r|dd| g7 }|d k	r|d|dd|	 g7 }|d k	r>|dd|d |d f g7 }|d k	rT|d|g7 }|d k	rn|dd| g7 }|d krt jdd\}}t| |d|
|f ddd| g7 }|rt	d
| zt|d d W nD ttfk
r } z d|t|f d  }t|W 5 d }~X Y nX tj| ||d! || _|| _|| _|rptj|rXt| tj|rpt| d S )"Nz.txt)suffixUTF8@z@%r    r   IMAGEMAGICK_BINARYz-backgroundz-fillz-fontz
-pointsizez%dz-kerningz%0.1fz-strokez-strokewidthz%.01fz-sizez%sx%sz-gravityz-interline-spacingz.pngz%s:%sz-typeZtruecolormattezPNG32:%s )rL   zLMoviePy Error: creation of %s failed because of the following error:

%s.

.zThis error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or that the path you specified is incorrect)r   )tempfilemkstemprQ   writebytes	TypeErrorcloser   r   printjoinr   IOErrorOSErrorr   r$   txtr   stroke_colorrR   rZ   r[   )r1   r   r>   r,   r   r   Zfontsizefontr   Zstroke_widthmethodZkerningZalignZ	interlineZtempfilenameZtemptxtr   r]   Z	print_cmdZ
temptxt_fdcmdZtempfile_fderrerrorr   r   r    r$   :  s    

   





  

zTextClip.__init__c                 C   s   t jttd}tjdkr d|d< t jtdd| gf|}| d }| }| dkrbd	d
 |D S | dkrdd
 |dd D S t	ddS )zzReturns the list of all valid entries for the argument of
        ``TextClip`` given (can be ``font``, ``color``, etc...) )stdoutstderrstdinnti   creationflagsr   z-listr   r   c                 S   s(   g | ] }| d r|ddd qS )s     Font:zUTF-8   N)
startswithdecoderq   lr   r   r    rs     s     
 z!TextClip.list.<locals>.<listcomp>r   c                 S   s   g | ]}| d d qS )    r   )splitr   r   r   r    rs     s     r   Nz4Moviepy:Error! Argument must equal 'font' or 'color')
spPIPEr   rQ   r^   Popenr   communicate
splitlines	Exception)argZpopen_paramsprocessr   linesr   r   r    rb     s&    

 zTextClip.listc                    s$       t|} fdd|D S )a  Returns the of all valid entries which contain ``string`` for the
           argument ``arg`` of ``TextClip``, for instance

           >>> # Find all the available fonts which contain "Courier"
           >>> print ( TextClip.search('Courier', 'font') )

        c                    s   g | ]} |  kr|qS r   )rU   )rq   r^   stringr   r    rs     s      z#TextClip.search.<locals>.<listcomp>)rU   r   rb   )r
  r  Z
names_listr   r	  r    search  s    	
zTextClip.search)NNNr   r   Nr   Nr   r   Nr{   NNNTTF)r   r   r   r   r$   staticmethodrb   r  r   r   r   r    r     s*   ?                       
M
r   )5r   rQ   
subprocessr   r   r   Znumpyr;   rV   ri   r   r   r   compatr   r   configr   Z
decoratorsr	   r
   r   r   r   r   r   Ztoolsr   r   r   r   r   Zio.ffmpeg_writerr   Zio.gif_writersr   r   r   Ztools.drawingr   r   r   r   r   r   r   r`   r   r   rh   r   r   r   r   r   r   r    <module>   sH   $     c7z%