Video editing with Python
Added ipython_display !!! Simplified codec/extension handling. Started doc rewrites. Rechanges fps computation from videofiles. Life's getting easier in MoviePy land.
Zulko7a4afe31a19e
diff --git a/docs/advanced_uses/advanced_uses.rst b/docs/advanced_uses/advanced_uses.rstnew file mode 100644index 00000000..5ecea179--- /dev/null+++ b/docs/advanced_uses/advanced_uses.rst@@ -0,0 +1,21 @@+.. _advanceduses:++Advanced uses of MoviePy+--------------------------++These pages give a few tips, tricks and tutorials. You can read more about each feature in the documentation of each function.++++.. toctree::+ :maxdepth: 1++ being_efficient+ gifmaking+ subtitles+ coordinates++Being efficient with MoviePy+=============================++MoviePy works well with the IPython Notebook, first because IPython has autocompletion and can display the documentation of the different functions, but also because working with code blocks in the browser enables to experiment.\ No newline at end of filediff --git a/docs/advanced_uses/ipynb_example.jpeg b/docs/advanced_uses/ipynb_example.jpegnew file mode 100644index 00000000..8256573fBinary files /dev/null and b/docs/advanced_uses/ipynb_example.jpeg differdiff --git a/docs/index.rst b/docs/index.rstindex 09d43927..954fa80e 100644--- a/docs/index.rst+++ b/docs/index.rst@@ -11,6 +11,7 @@ User's Guideinstallcrash_course/crash_course+ advanced/advanced_usesgalleryexamples/examplesFAQdiff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex 65f5f99e..8d9693bb 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -1,8 +1,9 @@-+import osimport numpy as npfrom moviepy.audio.io.ffmpeg_audiowriter import ffmpeg_audiowritefrom moviepy.decorators import requires_duration-from moviepy.tools import deprecated_version_of+from moviepy.tools import (deprecated_version_of,+ extensions_dict)from moviepy.Clip import Clip@@ -84,7 +85,7 @@ class AudioClip(Clip):@requires_durationdef write_audiofile(self,filename, fps=44100, nbytes=2,- buffersize=2000, codec='libvorbis',+ buffersize=2000, codec=None,bitrate=None, write_logfile=False, verbose=True):""" Writes an audio file from the AudioClip.@@ -102,8 +103,8 @@ class AudioClip(Clip):Sample width (set to 2 for 16-bit sound, 4 for 32-bit sound)codec- Which audio codec should be used. Examples are 'libmp3lame'- for '.mp3', 'libvorbis' for 'ogg', 'libfdk_aac':'m4a',+ Which audio codec should be used. If None provided, the codec is+ determined based on the extension of the filename. Choose'pcm_s16le' for 16-bit wav and 'pcm_s32le' for 32-bit wav.bitrate@@ -120,7 +121,16 @@ class AudioClip(Clip):If True, displays informations"""-++ if codec is None:+ name, ext = os.path.splitext(os.path.basename(filename))+ try:+ codec = extensions_dict[ext[1:]]['codec'][0]+ except KeyError:+ raise ValueError("MoviePy couldn't find the codec associated "+ "with the filename. Provide the 'codec' parameter in "+ "write_fideofile.")+return ffmpeg_audiowrite(self, filename, fps, nbytes, buffersize,codec=codec, bitrate=bitrate, write_logfile=write_logfile,verbose=verbose)diff --git a/moviepy/editor.py b/moviepy/editor.pyindex 0f32bd8a..9c97ee8c 100644--- a/moviepy/editor.py+++ b/moviepy/editor.py@@ -38,6 +38,7 @@ import moviepy.video.compositing.transitions as transfximport moviepy.video.tools as videotoolsimport moviepy.video.io.ffmpeg_tools as ffmpeg_tools+from .video.io.ipython_display import ipython_displayfrom .tools import cvsecstry:@@ -103,7 +104,4 @@ except ImportError:""" NOT AVAILABLE : clip.preview requires Pygame installed."""raise ImportError("clip.preview requires Pygame installed")-AudioClip.preview = preview---+AudioClip.preview = preview\ No newline at end of filediff --git a/moviepy/tools.py b/moviepy/tools.pyindex 6172e3ec..9d88ff3a 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -11,7 +11,7 @@ def sys_write_flush(s):""" Writes and flushes without delay a text in the console """sys.stdout.write(s)sys.stdout.flush()-+def verbose_print(verbose, s):""" Only prints s (with sys_write_flush) if verbose is True."""@@ -115,4 +115,31 @@ def deprecated_version_of(f, oldname, newname=None):return f(*a, **kw)fdepr.__doc__ = warning- return fdepr\ No newline at end of file+ return fdepr+++# non-exhaustive dictionnary to store default informations.+# any addition is most welcome.+# Note that 'gif' is complicated to place. From a VideoFileClip point of view,+# it is a video, but from a HTML5 point of view, it is an image.++extensions_dict = { "mp4": {'type':'video', 'codec':['libx264','libmpeg4']},+ 'ogv': {'type':'video', 'codec':['libtheora']},+ 'webm': {'type':'video', 'codec':['libvpx']},+ 'avi': {'type':'video' },+ 'mov': {'type':'video'},++ 'ogg': {'type':'audio', 'codec':['libvorbis']},+ 'mp3': {'type':'audio', 'codec':['libmp3lame']},+ 'wav': {'type':'audio', 'codec':['pcm_s16le', 'pcm_s32le']},+ 'm4a': {'type':'audio', 'codec':['libfdk_aac']}+ }++for ext in ["jpg", "jpeg", "png" "bmp", "tiff"]:+ extensions_dict[ext] = {'type':'image'}++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 filediff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex a85362fd..1ad695c8 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -30,7 +30,8 @@ from ..conf import FFMPEG_BINARY, IMAGEMAGICK_BINARYfrom ..tools import (subprocess_call,verbose_print,is_string,- deprecated_version_of)+ deprecated_version_of,+ extensions_dict, find_extension)from ..decorators import (apply_to_mask,requires_duration,@@ -141,15 +142,14 @@ class VideoClip(Clip):@requires_duration- def write_videofile(self, filename, fps=24, codec='libx264',+ def write_videofile(self, filename, fps=24, codec=None,bitrate=None, audio=True, audio_fps=44100,preset="medium",- audio_nbytes = 4, audio_codec= 'libmp3lame',+ audio_nbytes = 4, audio_codec= None,audio_bitrate = None, audio_bufsize = 2000,temp_audiofile=None,rewrite_audio = True, remove_temp = True,- write_logfile=False,- para = False, verbose = True):+ write_logfile=False, verbose = True):"""Write the clip to a videofile.Parameters@@ -165,29 +165,34 @@ class VideoClip(Clip):codecCodec to use for image encoding. Can be any codec supported- by ffmpeg, but the extension of the output filename must be- set accordingly.+ 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, use file extension ``.mp4``)+ ``'libx264'`` (default codec for file extension ``.mp4``)makes well-compressed videos (quality tunable using 'bitrate').- ``'mpeg4'`` (use file extension ``.mp4``) can be an alternative+ ``'mpeg4'`` (other codec for extension ``.mp4``) can be an alternativeto ``'libx264'``, and produces higher quality videos by default.``'rawvideo'`` (use file extension ``.avi``) will producea video of perfect quality, of possibly very huge size.+``png`` (use file extension ``.avi``) will produce a videoof perfect quality, of smaller size than with ``rawvideo``+``'libvorbis'`` (use file extension ``.ogv``) is a nice videoformat, which is completely free/ open source. However noteveryone has the codecs installed by default on their machine.+``'libvpx'`` (use file extension ``.webm``) is tiny a videoformat well indicated for web videos (with HTML5). Open source.@@ -210,6 +215,8 @@ class VideoClip(Clip):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_bitrateAudio bitrate, given as a string like '50k', '500k', '3000k'.@@ -217,11 +224,20 @@ class VideoClip(Clip):Note that it mainly an indicative goal, the bitrate won'tnecessarily be the this in the final file.+ preset+ Sets the time that FFMPEG will spend optimizing the compression.+ Choices are: ultrafast, superfast, fast, medium, slow, superslow.+ 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.+write_logfileIf true, will write log files for the audio and the video.These will be files ending with '.log' with the name of theoutput file in them.++Examples========@@ -232,6 +248,21 @@ class VideoClip(Clip):"""name, ext = os.path.splitext(os.path.basename(filename))+ ext = ext[1:].lower()++ if codec is None:+ try:+ codec = extensions_dict[ext]['codec'][0]+ except KeyError:+ raise ValueError("MoviePy couldn't find the codec associated "+ "with the filename. Provide the 'codec' parameter in "+ "write_fideofile.")++ if audio_codec is None:+ if (ext in ['ogv', 'webm']):+ audio_codec = 'libvorbis'+ else:+ audio_codec=='libmp3lame'if audio_codec == 'raw16':audio_codec = 'pcm_s16le'@@ -251,23 +282,16 @@ class VideoClip(Clip):# make a name for the temporary audio file- D_ext = {'libmp3lame': 'mp3',- 'libvorbis':'ogg',- 'libfdk_aac':'m4a',- 'aac':'m4a',- 'pcm_s16le':'wav',- 'pcm_s32le': 'wav'}-- if audio_codec in D_ext.values():+ if audio_codec in extensions_dict:audio_ext = audio_codecelse:- if audio_codec in D_ext.keys():- audio_ext = D_ext[audio_codec]- else:- raise ValueError('The extension for the audio_codec you '- 'chose is unknown by MoviePy. You should report this. '- "In the meantime, you can specify a temp_audiofile with the "- "right extension in write_videofile.")+ try:+ audio_ext = find_extension(audio_codec)+ except ValueError:++ raise ValueError("The audio_codec you chose is unknown by MoviePy. "+ "You should report this. In the meantime, you can specify a "+ "temp_audiofile with the right extension in write_videofile.")audiofile = (name+Clip._TEMP_FILES_PREFIX +"write_videofile_SOUND.%s"%audio_ext)@@ -532,29 +556,37 @@ class VideoClip(Clip):if fps is None:fps=self.fps-+ delay= 100.0/fps+cmd1 = [FFMPEG_BINARY, '-y', '-loglevel', 'error','-f', 'rawvideo','-vcodec','rawvideo', '-r', "%.02f"%fps,'-s', "%dx%d"%(self.w, self.h), '-pix_fmt', 'rgb24','-i', '-']- cmd1a = cmd1+['-r', "%.02f"%fps, filename]- cmd1b = cmd1+['-f', 'image2pipe','-vcodec', 'bmp', '-']-- cmd2 = [IMAGEMAGICK_BINARY, '-delay', "%.02f"%(100.0/fps),- "-dispose" ,"%d"%(2 if dispose else 1),- '-loop', '%d'%loop,- '-', '-coalesce']- cmd2a = cmd2+[filename]- cmd2b = cmd2+['gif:-']-- proc1 = (sp.Popen(cmd1a, stdin=sp.PIPE, stdout=DEVNULL) if (program =='ffmpeg')- else sp.Popen(cmd1b, stdin=sp.PIPE, stdout=sp.PIPE))+ if program == "ffmpeg":+ proc1 = sp.Popen(cmd1+['-r', "%.02f"%fps, filename],+ stdin=sp.PIPE, stdout=DEVNULL)+ else:+ proc1 = sp.Popen(cmd1+['-f', 'image2pipe',+ '-vcodec', 'bmp', '-'],+ stdin=sp.PIPE, stdout=sp.PIPE)+if program == 'ImageMagick':- proc2 = (sp.Popen(cmd2a, stdin=proc1.stdout) if (opt in [False, None])- else sp.Popen(cmd2b, stdin=proc1.stdout, stdout=sp.PIPE))++ cmd2 = [IMAGEMAGICK_BINARY, '-delay', "%.02f"%(delay),+ "-dispose" ,"%d"%(2 if dispose else 1),+ '-loop', '%d'%loop, '-', '-coalesce']++ if (opt in [False, None]):+ proc2 = sp.Popen(cmd2+[filename], stdin=proc1.stdout)++ else:+ proc2 = sp.Popen(cmd2+['gif:-'] , stdin=proc1.stdout,+ stdout=sp.PIPE)+if opt:+cmd3 = [IMAGEMAGICK_BINARY, '-', '-layers', opt,'-fuzz', '%d'%fuzz+'%',filename]proc3 = sp.Popen(cmd3, stdin=proc2.stdout)diff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.pyindex abd03e5f..28ae6677 100644--- a/moviepy/video/compositing/CompositeVideoClip.py+++ b/moviepy/video/compositing/CompositeVideoClip.py@@ -97,7 +97,7 @@ class CompositeVideoClip(VideoClip):def clips_array(array, rows_widths=None, cols_widths=None,- transparent = False, bg_color = (0,0,0)):+ transparent = False, bg_color = None):array = np.array(array)sizes_array = np.array([[c.size for c in line] for line in array])@@ -118,7 +118,7 @@ def clips_array(array, rows_widths=None, cols_widths=None,clip = (CompositeVideoClip([clip.set_pos('center')],size = (cw,rw),transparent = transparent,- bg_color = (bg_color)).+ bg_color = bg_color).set_duration(clip.duration))array[i,j] = clip.set_pos((x,y))diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex 6258f0ed..9563652f 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -254,21 +254,14 @@ def ffmpeg_parse_infos(filename, print_infos=False):# get the frame rate. Sometimes it's 'tbr', sometimes 'fps', sometimes- # tbc, and sometimes tbc/2... Trust tbc first, then tbr, then fps.+ # tbc, and sometimes tbc/2...+ # Current policy: Trust tbr first, then fps. If result is near from x*1000/1001+ # where x is 23,24,25,50, replace by x*1000/1001 (very common case for the fps).+try:match = re.search("( [0-9]*.| )[0-9]* tbr", line)tbr = float(line[match.start():match.end()].split(' ')[1])-- try:- match = re.search("( [0-9]*.| )[0-9]* tbc", line)- tbc = float(line[match.start():match.end()].split(' ')[1])- if abs(tbr - tbc/2) < abs(tbr-tbc):- result['video_fps'] = 1.0*tbc /2- else:- result['video_fps'] = tbc- except:- result['video_fps'] = tbr-+ result['video_fps'] = tbrexcept:match = re.search("( [0-9]*.| )[0-9]* fps", line)@@ -279,7 +272,7 @@ def ffmpeg_parse_infos(filename, print_infos=False):# but then ffmpeg nicely rounds it to 23.98, which we hate.coef = 1000.0/1001.0fps = result['video_fps']- for x in [23,24,25]:+ for x in [23,24,25,30,50]:if (fps!=x) and abs(fps - x*coef) < .01:result['video_fps'] = x*coefdiff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex 4adc2805..01b1d496 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -140,8 +140,12 @@ class FFMPEG_VideoWriter:"the video (%s) is not compatible with the given ""extension (%s). Please specify a valid 'codec' ""argument in write_videofile. This would be 'libx264' "- "or 'mpeg4' for mp4, 'libtheora' for ogv, 'libvpx' "- "for webm.")%(self.codec, self.ext)+ "or 'mpeg4' for mp4, 'libtheora' for ogv, 'libvpx for webm. "+ "Another possible reason is that the audio codec was not "+ "compatible with the video codec. For instance the video "+ "extensions 'ogv' and 'webm' only allow 'libvorbis' (default) as a"+ "video codec."+ )%(self.codec, self.ext)elif "encoder setup failed":diff --git a/moviepy/video/io/ipython_display.py b/moviepy/video/io/ipython_display.pynew file mode 100644index 00000000..883adfd4--- /dev/null+++ b/moviepy/video/io/ipython_display.py@@ -0,0 +1,112 @@+"""+This module implements ipython_display+A function to embed images/videos/audio in the IPython Notebook+"""++# Notes:+# All media are physically embedded in the IPython Notebook+# (instead of simple links to the original files)+# That is because most browsers use a cache system and they won't+# properly refresh the media when the original files are changed.++import os+from base64 import b64encode+from moviepy.tools import extensions_dict+from itertools import count++try:+ from IPython.display import HTML+ ipython_available = True+except ImportError:+ ipython_available = False++from .ffmpeg_reader import ffmpeg_parse_infos++sorry = "Sorry, seems like your browser doesn't support HTML5 audio/video"+templates = {"audio":("<center><audio controls>"+ "<source %(options)s src='data:audio/%(ext)s;base64,%(data)s'>"+ +sorry+"</audio></center>"),+ "image":"<center><img %(options)s "+ "src='data:image/%(ext)s;base64,%(data)s'></center>",+ "video":("<center><video %(options)s"+ "src='data:video/%(ext)s;base64,%(data)s' controls>"+ +sorry+"</video></center>")}+++def ipython_display(filename, filetype=None, maxduration=60, **kwargs):+ """ Displays a video, picture, or sound in IPython.++ filename:+ Either the name of a file, or the link to a web document.++ filetype:+ One of 'video','image','audio'. If None is given, it is determined+ based on the extension of ``filename``, but this can bug.++ **kwargs:+ Allow you to give some options, like width=260, etc.++ Remarks: If your browser doesn't support HTML5, this should warn you.+ If nothing is displayed, maybe your file or filename is wrong.+ The media will be physically embedded in the notebook.++ Examples+ =========++ >>> import moviepy.editor as mpy+ >>> # later ...+ >>> clip.write_videofile("test.mp4")+ >>> mpy.ipython_display("test.mp4", width=360)++ >>> clip.audio.write_audiofile('test.ogg') # Sound !+ >>> mpy.ipython_display('test.ogg')++ >>> clip.write_gif("test.gif")+ >>> mpy.ipython_display('test.gif')++ >>> clip.save_frame("first_frame.jpeg")+ >>> mpy.ipython_display("first_frame.jpeg")++ """++ options = " ".join(["%s='%s'"%(str(k), str(v)) for k,v in kwargs.items()])+ name, ext = os.path.splitext(filename)+ ext = ext[1:]++ if filetype is None:+ ext = filename.split('.')[-1].lower()+ if ext == "gif":+ filetype = 'image'+ elif ext in extensions_dict:+ filetype = extensions_dict[ext]['type']+ else:+ raise ValueError("No file type is known for the provided file. Please provide "+ "argument `filetype` (one of 'image', 'video', 'sound') to the "+ "ipython display function.")+++ if filetype== 'video':+ # The next lines set the HTML5-cvompatible extension and check that the+ # extension is HTML5-valid+ exts_htmltype = {'mp4': 'mp4', 'webm':'webm', 'ogv':'ogg'}+ allowed_exts = " ".join(exts_htmltype.keys())+ try:+ ext = exts_htmltype[ext]+ except:+ raise ValueError("This video extension cannot be displayed in the "+ "IPython Notebook. Allowed extensions: "+allowed_exts)++ if filetype in ['audio', 'video']:++ duration = ffmpeg_parse_infos(filename)['duration']+ if duration > maxduration:+ raise ValueError("The duration of video %s exceeds the 'max_duration' "%filename++ "attribute in ipython_display. You can increase 'max_duration', "+ "but note that embedding large videos may take all the memory away !")++ with open(filename, "rb") as f:+ data= b64encode(f.read())++ template = templates[filetype]++ return HTML(template%{'data':data, 'options':options, 'ext':ext})\ No newline at end of file