Video editing with Python
Update (#3)
Gloin131325ed5a4d980b
diff --git a/.gitignore b/.gitignoreindex 91ae4ba5..5342d399 100644--- a/.gitignore+++ b/.gitignore@@ -40,9 +40,15 @@ nosetests.xml.pydevproject# Temp files-*~# Pipy codes-.pypirc++# Mac+.DS_Store++# JetBrains+.idea++tests/mediadiff --git a/.travis.yml b/.travis.ymlnew file mode 100644index 00000000..445e9f41--- /dev/null+++ b/.travis.yml@@ -0,0 +1,16 @@+language: python+python:+ - "2.7"+ - "3.3"+ - "3.4"+ - "3.5"+ - "3.6"+# command to install dependencies+before_install:+ - sudo apt-get -qq update+ - sudo apt-get install -y ffmpeg+ - mkdir media+install:+ - python setup.py install+# command to run tests+script: py.testdiff --git a/README.rst b/README.rstindex c8320bab..c8707483 100644--- a/README.rst+++ b/README.rst@@ -1,7 +1,17 @@MoviePy-========--MoviePy (full documentation here_) is a Python module for video editing: cuts, concatenations, title insertions, video compositing (a.k.a. non-linear editing), video processing, and creation of custom effects. See the gallery_ for some examples of use.+=======++.. image:: https://badge.fury.io/py/moviepy.svg+ :target: PyPI_+ :alt: MoviePy page on the Python Package Index+.. image:: https://badges.gitter.im/movie-py/gitter.png+ :target: Gitter_+ :alt: Discuss MoviePy on Gitter+.. image:: https://travis-ci.org/Zulko/moviepy.svg?branch=master+ :target: https://travis-ci.org/Zulko/moviepy+ :alt: Build status on travis-ci++MoviePy (full documentation_) is a Python module for video editing: cutting, concatenations, title insertions, video compositing (a.k.a. non-linear editing), video processing, and creation of custom effects. See the gallery_ for some examples of use.MoviePy can read and write all the most common audio and video formats, including GIF, and runs on Windows/Mac/Linux, with Python 2.7+ and 3. Here it is in action in an IPython notebook:@@ -10,9 +20,11 @@ MoviePy can read and write all the most common audio and video formats, includin:align: centerExample---------+-------++In this example we open a video file, select the subclip between t=50s and t=60s, add a title at the center of the screen, and write the result to a new file:-In this example we open a video file, select the subclip between t=50s and t=60s, add a title at the center of the screen, and write the result to a new file: ::+.. code:: pythonfrom moviepy.editor import *@@ -27,68 +39,78 @@ In this example we open a video file, select the subclip between t=50s and t=60sresult.write_videofile("myHolidays_edited.webm",fps=25) # Many options...+Installation+-------------Contribute !--------------+MoviePy depends on the Python modules Numpy_, imageio_, Decorator_, and tqdm_, which will be automatically installed during MoviePy's installation. The software FFMPEG should be automatically downloaded/installed (by imageio) during your first use of MoviePy (installation will take a few seconds). If you want to use a specific version of FFMPEG, follow the instructions in ``config_defaults.py``. In case of trouble, provide feedback.-MoviePy is an open-source software originally written by Zulko_ and released under the MIT licence. The project is hosted on Github_ , where everyone is welcome to contribute, ask for help or simply give feedback.+**Installation by hand:** download the sources, either from PyPI_ or, if you want the development version, from Github_, unzip everything into one folder, open a terminal and type: ::-You can also discuss about the project on Reddit_ or on the mailing list [email protected] .+ $ (sudo) python setup.py install+**Installation with pip:** if you have ``pip`` installed, just type this in a terminal: ::-Maintainers---------------+ $ (sudo) pip install moviepy-- [Zulko](https://github.com/Zulko/) - Owner-- [mbeacom](https://github.com/mbeacom/)+If you have neither ``setuptools`` nor ``ez_setup`` installed, the command above will fail. In this case type this before installing: ::+ $ (sudo) pip install ez_setup-Installation-----------------MoviePy depends on the Python modules Numpy_, imageio_, Decorator_, and tqdm_, which will be automatically installed during MoviePy's installation. The software FFMPEG should be automatically downloaded/installed (by imageio) during your first use of MoviePy (it takes a few seconds). If you want to use a specific version of FFMPEG, follow the instructions in file ``config_defaults.py``. In case of trouble, provide feedback.+Optional but useful dependencies+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-**Installation by hand:** download the sources, either on PyPI_ or (if you want the development version) on Github_, unzip everything in one folder, open a terminal and type ::+ImageMagick_ is not strictly required, but needed if you want to incorporate texts. It can also be used as a backend for GIFs, though you can also create GIFs with MoviePy without ImageMagick.- (sudo) python setup.py install+Once you have installed ImageMagick, it will be automatically detected by MoviePy, **except on Windows!**. Windows users, before installing MoviePy by hand, need to edit ``moviepy/config_defaults.py`` to provide the path to the ImageMagick binary, which is called `convert`. It should look like this ::-**Installation with pip:** if you have ``pip`` installed, just type this in a terminal: ::+ IMAGEMAGICK_BINARY = "C:\\Program Files\\ImageMagick_VERSION\\convert.exe"- (sudo) pip install moviepy+PyGame_ is needed for video and sound previews (not relevant if you intend to work with MoviePy on a server but essential for advanced video editing by hand).-If you have neither ``setuptools`` nor ``ez_setup`` installed the command above will fail, is this case type this before installing: ::+For advanced image processing, you will need one or several of the following packages:- (sudo) pip install ez_setup+- The Python Imaging Library (PIL) or, even better, its branch Pillow_.+- Scipy_ (for tracking, segmenting, etc.) can be used to resize video clips if PIL and OpenCV are not installed.+- `Scikit Image`_ may be needed for some advanced image manipulation.+- `OpenCV 2.4.6`_ or a more recent version (one that provides the package ``cv2``) may be needed for some advanced image manipulation.+For instance, using the method ``clip.resize`` requires that at least one of Scipy, PIL, Pillow or OpenCV is installed.-Other optional but useful dependencies-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-ImageMagick_ is not strictly required, only if you want to write texts. It can also be used as a backend for GIFs but you can do GIFs with MoviePy without ImageMagick.+Contribute+-----------Once you have installed it, ImageMagick will be automatically detected by MoviePy, **except on Windows !**. Windows user, before installing MoviePy by hand, go into the ``moviepy/config_defaults.py`` file and provide the path to the ImageMagick binary called `convert`. It should look like this ::+MoviePy is open-source software originally written by Zulko_ and released under the MIT licence. The project is hosted on Github_, where everyone is welcome to contribute, ask for help or simply give feedback.++You can also discuss the project on Reddit_ (preferred over GitHub issues for usage/examples), Gitter_ or the mailing list [email protected].- IMAGEMAGICK_BINARY = "C:\\Program Files\\ImageMagick_VERSION\\convert.exe"-PyGame_ is needed for video and sound previews (useless if you intend to work with MoviePy on a server but really essential for advanced video editing *by hand*).+Maintainers+------------For advanced image processing you will need one or several of these packages. For instance using the method ``clip.resize`` requires that at least one of Scipy, PIL, Pillow or OpenCV are installed.+- Zulko_ (owner)-- The Python Imaging Library (PIL) or, better, its branch Pillow_ .-- Scipy_ (for tracking, segmenting, etc.), and can be used for resizing video clips if PIL and OpenCV aren't installed on your computer.-- `Scikit Image`_ may be needed for some advanced image manipulation.-- `OpenCV 2.4.6`_ or more recent (which provides the package ``cv2``) may be needed for some advanced image manipulation.+- `@Gloin1313`_+- `@earney`_+- Kay `@kerstin`_+- `@mbeacom`_+.. MoviePy links.. _gallery: http://zulko.github.io/moviepy/gallery.html+.. _documentation: http://zulko.github.io/moviepy/+.. _`download MoviePy`: https://github.com/Zulko/moviepy++.. Websites, Platforms.. _Reddit: http://www.reddit.com/r/moviepy/.. _PyPI: https://pypi.python.org/pypi/moviepy-.. _Pillow: http://pillow.readthedocs.org/en/latest/-.. _Zulko : https://github.com/Zulko.. _Github: https://github.com/Zulko/moviepy-.. _here: http://zulko.github.io/moviepy/+.. _Gitter: https://gitter.im/movie-py/Lobby++.. Software, Tools, Libraries+.. _Pillow: http://pillow.readthedocs.org/en/latest/.. _Scipy: http://www.scipy.org/-.. _`download MoviePy`: https://github.com/Zulko/moviepy.. _`OpenCV 2.4.6`: http://sourceforge.net/projects/opencvlibrary/files/.. _Pygame: http://www.pygame.org/download.shtml.. _Numpy: http://www.scipy.org/install.html@@ -96,7 +118,12 @@ For advanced image processing you will need one or several of these packages. Fo.. _`Scikit Image`: http://scikit-image.org/download.html.. _Decorator: https://pypi.python.org/pypi/decorator.. _tqdm: https://github.com/noamraph/tqdm--.. _ffmpeg: http://www.ffmpeg.org/download.html.. _ImageMagick: http://www.imagemagick.org/script/index.php++.. People+.. _Zulko: https://github.com/Zulko+.. _`@Gloin1313`: https://github.com/Gloin1313+.. _`@earney`: https://github.com/earney+.. _`@kerstin`: https://github.com/kerstin+.. _`@mbeacom`: https://github.com/mbeacomdiff --git a/examples/moving_letters.py b/examples/moving_letters.pyindex dc724e47..61034e44 100644--- a/examples/moving_letters.py+++ b/examples/moving_letters.py@@ -8,7 +8,7 @@ screensize = (720,460)txtClip = TextClip('Cool effect',color='white', font="Amiri-Bold",kerning = 5, fontsize=100)cvc = CompositeVideoClip( [txtClip.set_pos('center')],- size=screensize, transparent=True)+ size=screensize)# THE NEXT FOUR FUNCTIONS DEFINE FOUR WAYS OF MOVING THE LETTERSdiff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex 8655d56b..fade174a 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -378,6 +378,10 @@ class Clip:they exist."""+ if t_start < 0: #make this more python like a negative value+ #means to move backward from the end of the clip+ t_start = self.duration + t_start #remeber t_start is negative+if (self.duration is not None) and (t_start>self.duration):raise ValueError("t_start (%.02f) "%t_start +diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.pyindex e895f5d8..6183fd05 100644--- a/moviepy/audio/io/ffmpeg_audiowriter.py+++ b/moviepy/audio/io/ffmpeg_audiowriter.py@@ -2,11 +2,9 @@import numpy as npimport subprocess as sp+from moviepy.compat import PY3, DEVNULL+import os-try:- from subprocess import DEVNULL # py3k-except ImportError:- DEVNULL = open(os.devnull, 'wb')from tqdm import tqdmfrom moviepy.config import get_setting@@ -82,14 +80,17 @@ class FFMPEG_AudioWriter:def write_frames(self,frames_array):try:- self.proc.stdin.write(frames_array.tostring())+ if PY3:+ self.proc.stdin.write(frames_array.tobytes())+ else:+ self.proc.stdin.write(frames_array.tostring())except IOError as err:ffmpeg_error = self.proc.stderr.read()error = (str(err)+ ("\n\nMoviePy error: FFMPEG encountered ""the following error while writing file %s:"%self.filename+ "\n\n"+ffmpeg_error))- if "Unknown encoder" in ffmpeg_error:+ if b"Unknown encoder" in ffmpeg_error:error = (error+("\n\nThe audio export failed because ""FFMPEG didn't find the specified codec for audio "@@ -99,7 +100,7 @@ class FFMPEG_AudioWriter:" >>> to_videofile('myvid.mp4', audio_codec='libmp3lame')")%(self.codec))- elif "incorrect codec parameters ?" in ffmpeg_error:+ elif b"incorrect codec parameters ?" in ffmpeg_error:error = error+("\n\nThe audio export ""failed, possibly because the codec specified for "@@ -108,7 +109,7 @@ class FFMPEG_AudioWriter:"argument in to_videofile. This would be 'libmp3lame' ""for mp3, 'libvorbis' for ogg...")%(self.codec, self.ext)- elif "encoder setup failed":+ elif b"encoder setup failed" in ffmpeg_error:error = error+("\n\nThe audio export ""failed, possily because the bitrate you specified "diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex 86084c96..bfc6e597 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -6,12 +6,8 @@ from moviepy.tools import cvsecsfrom moviepy.video.io.ffmpeg_reader import ffmpeg_parse_infosfrom moviepy.config import get_setting-+from moviepy.compat import PY3, DEVNULLimport os-try:- from subprocess import DEVNULL # py3k-except ImportError:- DEVNULL = open(os.devnull, 'wb')class FFMPEG_AudioReader:@@ -114,12 +110,14 @@ class FFMPEG_AudioReader:def read_chunk(self,chunksize):+ # chunksize is not being autoconverted from float to int+ chunksize = int(round(chunksize))L = self.nchannels*chunksize*self.nbytess = self.proc.stdout.read(L)dt = {1: 'int8',2:'int16',4:'int32'}[self.nbytes]result = np.fromstring(s, dtype=dt)result = (1.0*result / 2**(8*self.nbytes-1)).\- reshape((len(result)/self.nchannels,+ reshape((int(len(result)/self.nchannels),self.nchannels))#self.proc.stdout.flush()self.pos = self.pos+chunksize@@ -238,6 +236,3 @@ class FFMPEG_AudioReader:def __del__(self):self.close_proc()---diff --git a/moviepy/compat.py b/moviepy/compat.pynew file mode 100644index 00000000..ceac4d31--- /dev/null+++ b/moviepy/compat.py@@ -0,0 +1,8 @@+import os+import sys+PY3=sys.version_info.major >= 3++if PY3:+ from subprocess import DEVNULL # py3k+else:+ DEVNULL = open(os.devnull, 'wb')diff --git a/moviepy/config.py b/moviepy/config.pyindex fd40384f..307abf90 100644--- a/moviepy/config.py+++ b/moviepy/config.py@@ -1,9 +1,6 @@import osimport subprocess as sp-try:- from subprocess import DEVNULL # py3k-except ImportError:- DEVNULL = open(os.devnull, 'wb')+from .compat import DEVNULLif os.name == 'nt':try:@@ -103,5 +100,3 @@ if __name__ == "__main__":print( "MoviePy : ImageMagick successfully found." )else:print( "MoviePy : can't find or access ImageMagick." )--diff --git a/moviepy/tools.py b/moviepy/tools.pyindex 686fdf63..4255e9d0 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -8,10 +8,7 @@ import warningsimport reimport os-try:- from subprocess import DEVNULL # py3k-except ImportError:- DEVNULL = open(os.devnull, 'wb')+from .compat import DEVNULLdef sys_write_flush(s):@@ -156,4 +153,4 @@ def find_extension(codec):for ext,infos in extensions_dict.items():if ('codec' in infos) and codec in infos['codec']:return ext- raise ValueError\ No newline at end of file+ raise ValueErrordiff --git a/moviepy/version.py b/moviepy/version.pyindex 47f9323c..66ae4c74 100644--- a/moviepy/version.py+++ b/moviepy/version.py@@ -1 +1 @@-__version__ = "0.2.2.12"+__version__ = "0.2.2.13"diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex bcc6bb2b..6a7a6c8e 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -1,7 +1,7 @@"""This module implements VideoClip (base class for video clips) and itsmain subclasses:-- Animated clips: VideofileClip, DirectoryClip+- Animated clips: VideofileClip, ImageSequenceClip- Static image clips: ImageClip, ColorClip, TextClip,"""@@ -40,10 +40,7 @@ from ..decorators import (apply_to_mask,convert_masks_to_RGB,use_clip_fps_by_default)-try:- from subprocess import DEVNULL # py3k-except ImportError:- DEVNULL = open(os.devnull, 'wb')+from ..compat import PY3, DEVNULLclass VideoClip(Clip):@@ -382,7 +379,7 @@ class VideoClip(Clip):------The resulting image sequence can be read using e.g. the class- ``DirectoryClip``.+ ``ImageSequenceClip``."""@@ -553,7 +550,7 @@ class VideoClip(Clip):# is the position relative (given in % of the clip's size) ?if self.relative_pos:- for i, dim in enumerate(wf, hf):+ for i, dim in enumerate([wf, hf]):if not isinstance(pos[i], str):pos[i] = dim * pos[i]@@ -604,7 +601,7 @@ class VideoClip(Clip):Size (width, height) in pixels of the final clip.By default it will be the size of the current clip.- bg_color+ colorBackground color of the final clip ([R,G,B]).pos@@ -919,8 +916,12 @@ class ImageClip(VideoClip):VideoClip.__init__(self, ismask=ismask, duration=duration)- if isinstance(img, str):- img = imread(img)+ if PY3:+ if isinstance(img, str):+ img = imread(img)+ else:+ if isinstance(img, (str, unicode)):+ img = imread(img)if len(img.shape) == 3: # img is (now) a RGB(a) numpy array@@ -1067,7 +1068,7 @@ class TextClip(ImageClip):for a list of acceptable names.color- Color of the background. See ``TextClip.list('color')`` for a+ Color of the text. See ``TextClip.list('color')`` for alist of acceptable names.font@@ -1202,9 +1203,12 @@ class TextClip(ImageClip):lines = result.splitlines()if arg == 'font':- return [l[8:] for l in lines if l.startswith(" Font:")]+ return [l.decode('UTF-8')[8:] for l in lines if l.startswith(b" Font:")]elif arg == 'color':- return [l.split(" ")[1] for l in lines[2:]]+ return [l.split(b" ")[0] for l in lines[2:]]+ else:+ raise Exception("Moviepy:Error! Argument must equal "+ "'font' or 'color'")@staticmethoddef search(string, arg):diff --git a/moviepy/video/compositing/concatenate.py b/moviepy/video/compositing/concatenate.pyindex 358a9314..94358d20 100644--- a/moviepy/video/compositing/concatenate.py+++ b/moviepy/video/compositing/concatenate.py@@ -1,19 +1,24 @@import numpy as np+from moviepy.compat import PY3++if PY3:+ from functools import reduce+from moviepy.tools import deprecated_version_offrom moviepy.video.VideoClip import VideoClip, ColorClipfrom moviepy.video.compositing.CompositeVideoClip import CompositeVideoClipfrom moviepy.audio.AudioClip import CompositeAudioClip-from moviepy.video.compositing.on_color import on_color+from moviepy.video.compositing.on_color import on_colordef concatenate_videoclips(clips, method="chain", transition=None,bg_color=None, ismask=False, padding = 0):""" Concatenates several video clips-+Returns a video clip made by clip by concatenating several video clips.(Concatenated means that they will be played one after another).-+There are two methods:- method="chain": will produce a clip that simply outputs@@ -33,33 +38,29 @@ def concatenate_videoclips(clips, method="chain", transition=None,will be transparent if mask=True, else it will be of thecolor specified by ``bg_color``.- If all clips with a fps attribute have the same fps, it becomes the fps of- the result.+ The clip with the highest FPS will be the FPS of the result clip.Parameters------------clipsA list of video clips which must all have their ``duration``attributes set.-method"chain" or "compose": see above.-transitionA clip that will be played between each two clips of the list.-+bg_colorOnly for method='compose'. Color of the background.Set to None for a transparent clip-+paddingOnly for method='compose'. Duration during two consecutive clips.Note that for negative padding, a clip will partly play at the sametime as the clip it follows (negative padding is cool for clips who fadein on one another). A non-null padding automatically sets the method to`compose`.-+"""if transition is not None:@@ -67,22 +68,20 @@ def concatenate_videoclips(clips, method="chain", transition=None,clips = reduce(lambda x, y: x + y, l) + [clips[-1]]transition = None-tt = np.cumsum([0] + [c.duration for c in clips])sizes = [v.size for v in clips]-w = max([r[0] for r in sizes])h = max([r[1] for r in sizes])tt = np.maximum(0, tt + padding*np.arange(len(tt)))-+if method == "chain":def make_frame(t):i = max([i for i, e in enumerate(tt) if e <= t])return clips[i].get_frame(t - tt[i])-+result = VideoClip(ismask = ismask, make_frame = make_frame)if any([c.mask is not None for c in clips]):masks = [c.mask if (c.mask is not None) else@@ -91,28 +90,31 @@ def concatenate_videoclips(clips, method="chain", transition=None,for c in clips]result.mask = concatenate_videoclips(masks, method="chain", ismask=True)result.clips = clips--elif method == "compose":result = CompositeVideoClip( [c.set_start(t).set_pos('center')for (c, t) in zip(clips, tt)],size = (w, h), bg_color=bg_color, ismask=ismask)+ else:+ raise Exception("Moviepy Error: The 'method' argument of "+ "concatenate_videoclips must be 'chain' or 'compose'")result.tt = tt-+result.start_times = tt[:-1]result.start, result.duration, result.end = 0, tt[-1] , tt[-1]-+audio_t = [(c.audio,t) for c,t in zip(clips,tt) if c.audio is not None]if len(audio_t)>0:result.audio = CompositeAudioClip([a.set_start(t)for a,t in audio_t])- fps_list = list(set([c.fps for c in clips if hasattr(c,'fps')]))- if len(fps_list)==1:- result.fps= fps_list[0]+ fpss = [c.fps for c in clips if hasattr(c,'fps') and c.fps is not None]+ if len(fpss) == 0:+ result.fps = None+ else:+ result.fps = max(fpss)return result-concatenate = deprecated_version_of(concatenate_videoclips, "concatenate_videoclips")+concatenate = deprecated_version_of(concatenate_videoclips, oldname="concatenate")diff --git a/moviepy/video/fx/resize.py b/moviepy/video/fx/resize.pyindex 8ea7c3e8..deed05b8 100644--- a/moviepy/video/fx/resize.py+++ b/moviepy/video/fx/resize.py@@ -67,7 +67,7 @@ def resize(clip, newsize=None, height=None, width=None, apply_to_mask=True):newsize:Can be either- - ``(height,width)`` in pixels or a float representing+ - ``(width,height)`` in pixels or a float representing- A scaling factor, like 0.5- A function of time returning one of these.diff --git a/moviepy/video/io/ImageSequenceClip.py b/moviepy/video/io/ImageSequenceClip.pyindex a07bbd40..7aa50bd0 100644--- a/moviepy/video/io/ImageSequenceClip.py+++ b/moviepy/video/io/ImageSequenceClip.py@@ -50,8 +50,8 @@ class ImageSequenceClip(VideoClip):ismask=False, load_images=False):# CODE WRITTEN AS IT CAME, MAY BE IMPROVED IN THE FUTURE-- if (fps is None) and (duration is None):++ if (fps is None) and (durations is None):raise ValueError("Please provide either 'fps' or 'durations'.")VideoClip.__init__(self, ismask=ismask)diff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.pyindex 4ebd0275..9b18fa10 100644--- a/moviepy/video/io/VideoFileClip.py+++ b/moviepy/video/io/VideoFileClip.py@@ -11,8 +11,8 @@ class VideoFileClip(VideoClip):A video clip originating from a movie file. For instance: ::- >>> clip = VideofileClip("myHolidays.mp4")- >>> clip2 = VideofileClip("myMaskVideo.avi")+ >>> clip = VideoFileClip("myHolidays.mp4")+ >>> clip2 = VideoFileClip("myMaskVideo.avi")Parameters@@ -54,8 +54,8 @@ class VideoFileClip(VideoClip):# Make a readerpix_fmt= "rgba" if has_mask else "rgb24"- reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)- self.reader = reader+ self.reader = None #need this just in case FFMPEG has issues (__del__ complains)+ self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)# Make some of the reader's attributes accessible from the clipself.duration = self.reader.durationself.end = self.reader.duration@@ -67,15 +67,15 @@ class VideoFileClip(VideoClip):if has_mask:- self.make_frame = lambda t: reader.get_frame(t)[:,:,:3]- mask_mf = lambda t: reader.get_frame(t)[:,:,3]/255.0+ self.make_frame = lambda t: self.reader.get_frame(t)[:,:,:3]+ mask_mf = lambda t: self.reader.get_frame(t)[:,:,3]/255.0self.mask = (VideoClip(ismask = True, make_frame = mask_mf).set_duration(self.duration))self.mask.fps = self.fpselse:- self.make_frame = lambda t: reader.get_frame(t)+ self.make_frame = lambda t: self.reader.get_frame(t)# Make a reader for the audio, if any.if audio and self.reader.infos['audio_found']:@@ -86,5 +86,8 @@ class VideoFileClip(VideoClip):nbytes = audio_nbytes)def __del__(self):- """ Close/delete the internal reader. """- del self.reader+ """ Close/delete the internal reader. """+ try:+ del self.reader+ except AttributeError:+ passdiff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex 420eed10..836fb6a8 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -15,12 +15,9 @@ logging.captureWarnings(True)import numpy as npfrom moviepy.config import get_setting # ffmpeg, ffmpeg.exe, etc...from moviepy.tools import cvsecs+from moviepy.compat import PY3, DEVNULLimport os-try:- from subprocess import DEVNULL # py3k-except ImportError:- DEVNULL = open(os.devnull, 'wb')class FFMPEG_VideoReader:diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex 60501520..e19cd7bd 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -7,11 +7,7 @@ import subprocess as spimport osimport numpy as np-try:- from subprocess import DEVNULL # py3k-except ImportError:- DEVNULL = open(os.devnull, 'wb')-+from moviepy.compat import PY3, DEVNULLfrom moviepy.config import get_settingfrom moviepy.tools import verbose_print@@ -134,14 +130,17 @@ class FFMPEG_VideoWriter:def write_frame(self, img_array):""" Writes one frame in the file."""try:- self.proc.stdin.write(img_array.tostring())+ if PY3:+ self.proc.stdin.write(img_array.tobytes())+ else:+ self.proc.stdin.write(img_array.tostring())except IOError as err:ffmpeg_error = self.proc.stderr.read()error = (str(err) + ("\n\nMoviePy error: FFMPEG encountered ""the following error while writing file %s:""\n\n %s" % (self.filename, ffmpeg_error)))- if "Unknown encoder" in ffmpeg_error:+ if b"Unknown encoder" in ffmpeg_error:error = error+("\n\nThe video export ""failed because FFMPEG didn't find the specified "@@ -150,7 +149,7 @@ class FFMPEG_VideoWriter:"write_videofile. For instance:\n"" >>> clip.write_videofile('myvid.webm', codec='libvpx')")%(self.codec)- elif "incorrect codec parameters ?" in ffmpeg_error:+ elif b"incorrect codec parameters ?" in ffmpeg_error:error = error+("\n\nThe video export ""failed, possibly because the codec specified for "@@ -164,13 +163,13 @@ class FFMPEG_VideoWriter:"video codec.")%(self.codec, self.ext)- elif "encoder setup failed" in ffmpeg_error:+ elif b"encoder setup failed" in ffmpeg_error:error = error+("\n\nThe video export ""failed, possibly because the bitrate you specified ""was too high or too low for the video codec.")- elif "Invalid encoder type" in ffmpeg_error:+ elif b"Invalid encoder type" in ffmpeg_error:error = error + ("\n\nThe video export failed because the codec ""or file extension you provided is not a video")diff --git a/moviepy/video/io/gif_writers.py b/moviepy/video/io/gif_writers.pyindex b82a1d3c..aeb6d953 100644--- a/moviepy/video/io/gif_writers.py+++ b/moviepy/video/io/gif_writers.py@@ -6,10 +6,7 @@ from moviepy.decorators import (requires_duration,use_clip_fps_by_default)from moviepy.tools import verbose_print, subprocess_callimport numpy as np-try:- from subprocess import DEVNULL # py3k-except ImportError:- DEVNULL = open(os.devnull, 'wb')+from moviepy.compat import DEVNULLtry:import imageiodiff --git a/moviepy/video/tools/interpolators.py b/moviepy/video/tools/interpolators.pyindex f5cd030e..f6f5cc7d 100644--- a/moviepy/video/tools/interpolators.py+++ b/moviepy/video/tools/interpolators.py@@ -41,7 +41,7 @@ class Trajectory:def addy(self, y):- return Trajectory(self.tt, self.xx+y, self.yy)+ return Trajectory(self.tt, self.xx, self.yy+y)def update_interpolators(self):self.xi = Interpolator(self.tt, self.xx)diff --git a/moviepy/video/tools/tracking.py b/moviepy/video/tools/tracking.pyindex 21e62e48..e6164dfa 100644--- a/moviepy/video/tools/tracking.py+++ b/moviepy/video/tools/tracking.py@@ -70,7 +70,7 @@ def manual_tracking(clip, t1=None, t2=None, fps=None, nobjects = 1,nobjects=3, savefile="track.txt")>>> # ...>>> # LATER, IN ANOTHER SCRIPT, RECOVER THESE TRAJECTORIES- >>> from moviepy.tools.tracking import Trajectory+ >>> from moviepy.video.tools.tracking import Trajectory>>> traj1, traj2, traj3 = Trajectory.load_list('track.txt')>>> # If ever you only have one object being tracked, recover it with>>> traj, = Trajectory.load_list('track.txt')diff --git a/tests/test_PR.py b/tests/test_PR.pynew file mode 100644index 00000000..cbb4f2d6--- /dev/null+++ b/tests/test_PR.py@@ -0,0 +1,36 @@+"""+Tests meant to be run with pytest+"""++import sys+import os+import pytest++from moviepy.editor import *+++def test_PR_306():+ #put this back in once we get ImageMagick working on travis-ci+ #assert TextClip.list('font') != []+ #assert TextClip.list('color') != []++ #with pytest.raises(Exception, message="Expecting Exception"):+ # TextClip.list('blah')+ pass+++def test_PR_339():+ #in caption mode+ #overlay = TextClip(txt='foo',+ # color='white',+ # size=(640, 480),+ # method='caption',+ # align='center',+ # fontsize=25)++ #in_label_mode+ #overlay = TextClip(txt='foo', method='label')+ pass++if __name__ == '__main__':+ pytest.main()diff --git a/tests/test_install.py b/tests/test_install.pydeleted file mode 100644index f98f9345..00000000--- a/tests/test_install.py+++ /dev/null@@ -1,10 +0,0 @@---from moviepy.editor import *--W,H = (150,180)-color_clips_props = [{ 'color':[0,0,255],- 'init_pos':[]-[0,0,255],[0,255,0],[255,0,0]-red_clip, green_clip, blue_clip = [ColorClip((W,H),color=c)- for c in RED, GREEN, BLUE]diff --git a/tests/test_issues.py b/tests/test_issues.pynew file mode 100644index 00000000..9b932fb6--- /dev/null+++ b/tests/test_issues.py@@ -0,0 +1,60 @@+"""+Tests meant to be run with pytest+"""++import os+import pytest++from moviepy.editor import *++def download_url(url, filename):+ if not os.path.exists(filename):+ print("\nDownloading %s\n" % filename)+ download_webfile(url, filename)+ print("Downloading complete...\n")++def download_youtube_video(youtube_id, filename):+ # FYI.. travis-ci doesn't like youtube-dl+ download_url(youtube_id, filename)++def test_download_media(capsys):+ with capsys.disabled():+ #download_youtube_video("zvCvOC2VwDc", "media/knights.mp4")+ download_url("https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Python_logo_and_wordmark.svg/260px-Python_logo_and_wordmark.svg.png",+ "media/python_logo.png")++ #knights=VideoFileClip("media/knights.mp4")+ #knights10 = knights.subclip(60,70)+++def test_issue_145():+ _video = ColorClip((800, 600), col=(255,0,0)).set_duration(5)+ with pytest.raises(Exception, message="Expecting Exception"):+ _final = concatenation([_video], method = 'composite')++def test_issue_407():+ _red = ColorClip((800, 600), col=(255,0,0)).set_duration(5)+ _red.fps=30+ assert round(_red.fps) == 30++ _green=ColorClip((640, 480), col=(0,255,0)).set_duration(2) #ColorClip has no fps attribute+ _blue=ColorClip((640, 480), col=(0,0,255)).set_duration(2) #ColorClip has no fps attribute++ _video=concatenate_videoclips([_red, _green, _blue])+ assert _video.fps == _red.fps++def test_issue_416():+ _green=ColorClip((640, 480), col=(0,255,0)).set_duration(2) #ColorClip has no fps attribute+ _video1=concatenate_videoclips([_green])+ assert _video1.fps == None++def test_issue_417():+ # failed in python2++ cad = u'media/python_logo.png'+ myclip = ImageClip(cad).fx(vfx.resize, newsize=[1280, 660])+ final = CompositeVideoClip([myclip], size=(1280, 720))+ #final.set_duration(7).write_videofile("test.mp4", fps=30)++if __name__ == '__main__':+ pytest.main()diff --git a/tests/tests.py b/tests/tests.pyindex 541d08fa..3cd55af8 100644--- a/tests/tests.py+++ b/tests/tests.py@@ -1,12 +1,18 @@"""-Tests meant to be run with pytest+To run the tests:+ py.test tests.py"""-import pytest-from moviepy.editor import *+#@pytest.fixture+def test_if_TextClip_crashes_in_caption_mode():+ overlay = TextClip(txt='foo',+ color='white',+ size=(640, 480),+ method='caption',+ align='center',+ fontsize=25)-def example_video1():-+def test_if_TextClip_crashes_in_label_mode():+ overlay = TextClip(txt='foo', method='label')