Video editing with Python
stderr in ffmpeg_write redirected (file/DEVNULL). Cleaned docs.
Zulko77b6b2351a45
diff --git a/docs/FAQ.rst b/docs/FAQ.rstnew file mode 100644index 00000000..d07ff0a7--- /dev/null+++ b/docs/FAQ.rst@@ -0,0 +1,33 @@+FAQ and troubleshooting+=========================++This section will fill up as MoviePy advances through the next steps of+development (currently on the roadmap: MoviePy Studio, MoviePy WebApp, MoviePy OS, MoviePy+Trust Inc., and the MoviePy Charity Fundation).++Common errors that are not bugs+--------------------------------++These are very common errors which are not considered as bugs to be+solved (but you can still ask for this to change). If these answers+don't work for you, please open a bug report on Github_, or on the dedicated forum on Reddit_, or on the librelist_.++- **MoviePy generated a video that cannot be read by my favorite player.**+Known reason : one of the video's dimensions were not even,+for instance 720x405, and you used a MPEG4 codec like libx264 (default+in MoviePy). In this case the video generated uses a format that is+readable only on some readers like VLC.++- **I can't seem to read any video with MoviePy**. Known reason: you+have a deprecated version of FFMPEG, install a recent version from the+website, not from your OS's repositories ! (see :ref:`installation`).++- **I get an error when I use texts in my video**: If you are on+Windows, this is due to a name clash, see :ref:`installation`. Also,+make sure that you are using a recent version of ImageMagick.+++.. _Github: https://github.com/Zulko/moviepy+.. _Reddit: http://www.reddit.com/r/moviepy/+.. _librelist: mailto:[email protected]+diff --git a/docs/crash_course/crash_course.rst b/docs/crash_course/crash_course.rstindex 74c4f325..379fb651 100644--- a/docs/crash_course/crash_course.rst+++ b/docs/crash_course/crash_course.rst@@ -29,8 +29,8 @@ So let us load a movie of my last holidays, lower the volume, add a title in the# Write the result to a filevideo.to_videofile("myHolidays_edited.avi",fps=24, codec='mpeg4')-How it works, in a nutshell-~~~~~~~~~~~~~~~~~~~~~~~~~~~~+How MoviePy works, in a nutshell+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MoviePy uses mainly ``ffmpeg`` for reading/writing multimedia files, and Numpy/Scipy for image and sound manipulations.@@ -41,17 +41,29 @@ MoviePy uses mainly ``ffmpeg`` for reading/writing multimedia files, and Numpy/SYou can do pretty much any effect you want with MoviePy, but it is just a framework, and in many cases you will need to code a little (or find someone who will !) to come to your goal.+The clip objects+~~~~~~~~~~~~~~~~~~~++In MoviePy you manipulate mostly two kind of objects: audio clips, and+video clips. These clips have different attributes (indicating their+duration, their size, their starting time...) which can change as the clips are cut and+mixed with other clips.++A video clip can carry around a soundtrack (which is an+audioclip) and, for more complex effects, a mask (which is a special+video clip).+Classes of video clips~~~~~~~~~~~~~~~~~~~~~~Video clips are the building blocks of longer videos. They can be created with one of the following:-- ``VideoFileClip('myHolidays.mp4')`` for clips read from a movie file. See :class:`~moviepy.video.io.VideoFileClip.VideoFileClip`.-- ``ImageClip('myPic.png')`` for clips displaying a picture, for an *a priori* infinite duration. See :class:`~moviepy.video.ImageClip.ImageClip`.-- ``ColorClip((height,width),color=(R,G,B))`` for special ImageClips of a single color. See :class:`~moviepy.video.ImageClip.ColorClip`.-- ``TextClip('Hello folks !',font='Impact-Regular')`` for special ImageClips representing a text. They are automatically generated using ImageMagick. See :class:`~moviepy.video.ImageClip.TextClip`.+- ``VideoFileClip('myHolidays.mp4')`` for clips read from a movie file.+- ``ImageClip('myPic.png')`` for clips displaying a picture, for an *a priori* infinite duration.+- ``ColorClip((height,width),color=(R,G,B))`` for special ImageClips of a single color.+- ``TextClip('Hello folks !',font='Impact-Regular')`` for special ImageClips representing a text. They are automatically generated using ImageMagick.-To that list we should add the ``CompositeVideoClips`` that are obtained by mixing several clips together.+To that list we should add the ``CompositeVideoClips`` which are obtained by putting several clips together... _CompositeVideoClips:@@ -116,13 +128,16 @@ Be careful when indicating the position that the ``y`` position has its zero atRendering a video clip~~~~~~~~~~~~~~~~~~~~~~~-To preview one frame of the clip, use one of these: ::+A clip can be previewed (i.e. generated and displayed at the same time)+or be rendered directly to a file. Note that previewing requires to+have the Python package PyGame installed.++To preview just one frame of the clip, use one of these: ::myClip.show() # shows the first frame of the clipmyClip.show(10.5) # shows the frame of the clip at t=10.5s- myClip.show(10.5,frontend="matplotlib") # show in a matplotlib window-To preview the clip, you type ::+To preview the clip, type ::myClip.preview() # preview with default fps=15myClip.preview(fps=25)@@ -135,6 +150,13 @@ To write a clip as a video file, use ::myClip.to_videofile("myEditedMovie.avi") # default: codec 'libx264' fps 24myClip.to_videofile("myEditedMovie.avi",fps=15, codec='mpeg4')myClip.to_videofile("myEditedMovie.avi",audio=False) # don't render the audio.++Alternatively you can also save a video clip as an animated GIF with ::++ myClip.to_gif('test.gif')++See `this blog post <http://zulko.github.io/blog/2014/01/23/making-animated-gifs-from-video-files-with-python>`_ for more informations on making GIFs with MoviePy.+Sometimes it is impossible for MoviePy to guess the ``duration`` attribute of the clip (keep in mind that some clips, like ImageClips displaying a picture, have *a priori* an infinite duration). Then, the ``duration`` must be set manually with ``clip.set_duration``: ::@@ -150,7 +172,7 @@ Audio clipsThe second important objects of MoviePy are the audio clips. If ``myHolidays.mp4`` is a video with sound, then ::- clip = VideoFileClip('myHolidays.mp4', audio=True)+ clip = VideoFileClip('myHolidays.mp4')will create a clip with a ``clip.audio`` attribute which is an audio clip. This is the sound that you will hear if you render the clip with ``clip.preview`` or ``clip.to_videofile``. You can also create an audio clip from a sound file and then attach it to a video clip: ::@@ -198,9 +220,9 @@ but this is not easy to read. To have a clearer syntax you can use ``clip.fx``:fx( effect_2, args2).\fx( effect_3, args3)-Much better ! There are already many effects implemented in the modules ``moviepy.video.fx`` and ``moviepy.audio.fx``. The fx methods in these modules are automatically applied to the sound and the mask of the clip if it is relevant, so that you don't have to worry about modifying these. For practicality, when you use ``from moviepy import.all *``, these two modules are loaded as ``vfx`` and ``afx``, so you may write something like ::+Much better ! There are already many effects implemented in the modules ``moviepy.video.fx`` and ``moviepy.audio.fx``. The fx methods in these modules are automatically applied to the sound and the mask of the clip if it is relevant, so that you don't have to worry about modifying these. For practicality, when you use ``from moviepy import.editor *``, these two modules are loaded as ``vfx`` and ``afx``, so you may write something like ::- from moviepy import.all *+ from moviepy import.editor *clip = VideoFileClip("myvideo.avi").\fx( vfx.resize, width=460).\ # resize (keep aspect ratio)fx( vfx.speedx, 2).\ # double speed@@ -232,7 +254,11 @@ Finally, you may want to process the clip by taking into account the time and thThis will scroll down the clip with a constant height of 360 pixels.-Prefer using ``fl_time`` and ``fl_image`` if possible when implementing new effects. The reason is that for image clips MoviePy will recognize that these methods do not need to be applied to each frames, which will result in shorter computation times.+When programming a new effect, whenever it is possible, prefer using ``fl_time`` and+``fl_image`` instead of ``fl`` if possible when implementing+new effects. The reason is that, when these effects are applied to+ImageClips, MoviePy will recognize that these methods do not need to be applied to each frame, which will+result in faster renderings.Tools~~~~~~@@ -253,7 +279,10 @@ MoviePy works fine on my 1.5 petaflops supercomputer but when a clip gets very c- [wishful thinking] Check on the internet or in the examples of this documentation that what you do hasn't been done before. Code shared on the internet has more chances to be optimized.-To go further and learn about all the available options and functionalities of MoviePy, see the :ref:`examples` and the reference manual. You can also browse the code of different fx+To go further and learn about all the available options and+functionalities of MoviePy, see the :ref:`examples` and the reference+manual. You can also browse the code of the different video effects in+``moviepy/video/fx`` to give you ideas on how to code your own effects.diff --git a/docs/index.rst b/docs/index.rstindex 98fa014a..247b18bf 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -27,7 +27,9 @@ Let us put together a few demonstration clips (you will find the code for most o</center>MoviePy is an open source software originally written by Zulko_ and released under the MIT licence.-It is hosted on Github_, where you can push improvements or ask for help.+It is hosted on Github_, where you can push improvements, report bugs and ask for help.++**Very New:** there is now a MoviePy forum on Reddit_ and a mailing list on librelist_ ... raw:: html@@ -57,11 +59,13 @@ User's Guideinstallcrash_course/crash_courseexamples/examples+ FAQref/ref.. _PyPI: https://pypi.python.org/pypi/moviepy-.. _Github: https://github.com/Zulko/moviepy.. _Zulko: https://github.com/Zulko/.. _Stackoverflow: http://stackoverflow.com/-+.. _Github: https://github.com/Zulko/moviepy+.. _Reddit: http://www.reddit.com/r/moviepy/+.. _librelist: mailto:[email protected]diff --git a/docs/install.rst b/docs/install.rstindex e299b025..9d632c52 100644--- a/docs/install.rst+++ b/docs/install.rst@@ -4,9 +4,11 @@ Download and InstallationCore dependencies--------------------MoviePy requires the Python modules Numpy_, Decorator_, and tqdm_. All of these will all be automatically installed during MoviePy's installation.+MoviePy requires the Python modules Numpy_, Decorator_, and tqdm_. All+of these will be automatically installed during MoviePy's installation.-You will also need a **recent version** of the software ffmpeg_ , preferably downloaded directly from the ffmpeg website.+You will also need a **recent version** of the software ffmpeg_ ,+preferably downloaded directly from the ffmpeg website.Installation--------------@@ -25,6 +27,15 @@ Linking to ffmpegIf you put have a ffmpeg binary in you executable folder (on Linux it will be ``/usr/bin``) it will be detected automatically by MoviePy. Else make sure that MoviePy can locate ffmpeg on your computer by running the script ``moviepy/conf.py`` that is in the sources. It it fails, then you must enter the path to the FFMPEG executable in the first line of this file ::FFMPEG_BINARY = path/to/your/ffmpeg++Linking to ImageMagick (Windows only)+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++For the moment MoviePy cannot detect ImageMagick on Windows. You need+to go into the ``moviepy/conf.py`` file and provide the path, it+should look something like this ::++ IMAGEMAGICK_BINARY = "C:\Program Files\ImageMagick_VERSION\convert"(Not so) Optional dependenciesdiff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex ddd92753..9f3e5edd 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -122,6 +122,7 @@ class VideoClip(Clip):audio_bitrate = None, audio_bufsize = 2000,temp_audiofile=None,rewrite_audio = True, remove_temp = True,+ write_logfile=False,para = False, verbose = True):"""Write the clip to a videofile.@@ -164,6 +165,8 @@ class VideoClip(Clip):"""+ name, ext = os.path.splitext(os.path.basename(filename))+if audio_codec == 'raw16':audio_codec = 'pcm_s16le'elif audio_codec == 'raw32':@@ -187,7 +190,7 @@ class VideoClip(Clip):# The audio will be the clip's audioif temp_audiofile is None:- # make a name for the temporary file+ # make a name for the temporary audio fileD_ext = {'libmp3lame': 'mp3','libvorbis':'ogg',@@ -197,16 +200,16 @@ class VideoClip(Clip):'pcm_s32le': 'wav'}if audio_codec in D_ext.values():- ext = audio_codec+ audio_ext = audio_codecelse:if audio_codec in D_ext.keys():- ext = D_ext[audio_codec]+ audio_ext = D_ext[audio_codec]else:raise ValueError('audio_codec for file''%d unkown !'%filename)temp_audiofile = (Clip._TEMP_FILES_PREFIX +- "to_videofile_SOUND." + ext)+ "to_videofile_SOUND_%s."%name + audio_ext)make_audio = ( (not os.path.exists(temp_audiofile))or rewrite_audio)@@ -219,8 +222,8 @@ class VideoClip(Clip):if merge_audio:- name, ext = os.path.splitext(os.path.basename(filename))- videofile = Clip._TEMP_FILES_PREFIX + "to_videofile" + ext+ # make a name for the temporary video file+ videofile = Clip._TEMP_FILES_PREFIX + "to_videofile_"+ filenameelse:@@ -233,28 +236,39 @@ class VideoClip(Clip):+40*"-"+"\n")if para and make_audio and enough_cpu:+# Parallelizeverbose_print("Writing audio/video in parrallel.\n")audioproc = multiprocessing.Process(target=self.audio.to_audiofile,args=(temp_audiofile,audio_fps,audio_nbytes,audio_bufsize,audio_codec, audio_bitrate,verbose))+audioproc.start()- ffmpeg_write_video(self, videofile, fps, codec,- bitrate=bitrate, verbose=verbose)++ ffmpeg_write_video(self,+ videofile, fps, codec,+ bitrate=bitrate,+ write_logfile=write_logfile,+ verbose=verbose)audioproc.join()if audioproc.exitcode:print ("WARNING: something went wrong with the audio"+" writing, Exit code %d"%audioproc.exitcode)else:+# Don't parallelizeif make_audio:self.audio.to_audiofile(temp_audiofile,audio_fps,audio_nbytes, audio_bufsize,audio_codec, audio_bitrate,verbose)- ffmpeg_write_video(self, videofile, fps, codec,- bitrate=bitrate, verbose=verbose)++ ffmpeg_write_video(self,+ videofile, fps, codec,+ bitrate=bitrate,+ write_logfile=write_logfile,+ verbose=verbose)# Merge with audio if any and trash temporary files.if merge_audio:diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex 230390f3..211ee677 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -7,12 +7,22 @@ import sysimport numpy as npimport subprocess as sp+try:+ from subprocess import DEVNULL # py3k+except ImportError:+ import os+ DEVNULL = open(os.devnull, 'wb')+++from tqdm import tqdmfrom moviepy.conf import FFMPEG_BINARYfrom moviepy.tools import sys_write_flush++class FFMPEG_VideoWriter:""" A class for FFMPEG-based video writing.@@ -39,7 +49,12 @@ class FFMPEG_VideoWriter:'png' manages the same lossless quality as 'rawvideo' but yieldssmaller files. Type ``ffmpeg -codecs`` in a terminal to get a listof accepted codecs.-++ Note for default 'libx264': by default the pixel format yuv420p+ is used. If the video dimensions are not both even (e.g. 720x405)+ another pixel format is used, and this can cause problem in some+ video readers.+bitrateOnly relevant for codecs which accept a bitrate. "5000k" offersnice results in general.@@ -53,8 +68,11 @@ class FFMPEG_VideoWriter:def __init__(self, filename, size, fps, codec="libx264",- bitrate=None, withmask=False):-+ bitrate=None, withmask=False, logfile=None):++ if logfile is None:+ logfile = DEVNULL+self.filename = filenamecmd = ([ FFMPEG_BINARY, '-y',@@ -68,13 +86,20 @@ class FFMPEG_VideoWriter:+ (['-b',bitrate] if (bitrate!=None) else [])# http://trac.ffmpeg.org/ticket/658- + (['-pix_fmt', 'yuv420p'] if (codec == 'libx264') else [])+ + (['-pix_fmt', 'yuv420p']+ if ((codec == 'libx264') and+ (size[0]%2 == 0) and+ (size[1]%2 == 0))++ else [])+ [ '-r', "%d"%fps, filename ])- self.proc = sp.Popen(cmd,stdin=sp.PIPE, stderr=sp.PIPE)- self.proc.stderr.close()+ self.proc = sp.Popen(cmd, stdin=sp.PIPE,+ stderr=logfile,+ stdout=DEVNULL)+def write_frame(self,img_array):""" Writes 1 frame in the file ! """@@ -83,20 +108,28 @@ class FFMPEG_VideoWriter:def close(self):self.proc.stdin.close()- self.proc.stderr.close()+ #self.proc.stderr.close()self.proc.wait()del self.procdef ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,- withmask=False, verbose=True):+ withmask=False, write_logfile=False, verbose=True):def verbose_print(s):if verbose: sys_write_flush(s)+ if write_logfile:+ logfile = open(filename + ".log", 'w+')+ else:+ logfile = DEVNULL++ print logfile++verbose_print("\nWriting video into %s\n"%filename)writer = FFMPEG_VideoWriter(filename, clip.size, fps, codec = codec,- bitrate=bitrate)+ bitrate=bitrate, logfile=logfile)nframes = int(clip.duration*fps)@@ -109,22 +142,31 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,writer.write_frame(frame.astype("uint8"))writer.close()++ if write_logfile:+ logfile.close()verbose_print("Done writing video in %s !"%filename)-def ffmpeg_write_image(filename, image):+def ffmpeg_write_image(filename, image, logfile=False):""" Writes an image (HxWx3 or HxWx4 numpy array) to a file, usingffmpeg. """++cmd = [ FFMPEG_BINARY, '-y','-s', "%dx%d"%(image.shape[:2][::-1]),"-f", 'rawvideo','-pix_fmt', "rgba" if (image.shape[2] == 4) else "rgb24",'-i','-', filename]-- proc = sp.Popen( cmd, stdin=sp.PIPE, stderr=sp.PIPE)- #proc.stdin.write()- #proc.stdin.close()++ if logfile:+ log_file = open(filename + ".log", 'w+')+ else:+ log_file = DEVNULL+++ proc = sp.Popen( cmd, stdin=sp.PIPE, stderr=log_file)proc.communicate(image.tostring()) # proc.wait()if proc.returncode:@@ -132,5 +174,7 @@ def ffmpeg_write_image(filename, image):"WARNING: this command returned an error:",proc.stderr.read().decode('utf8')])raise IOError(err)++del proc