Video editing with Python
Now audio-video merge is done at once (no more temp video file). Re-put method="chain" into concatenate, a lighter version.
Zulkocb199dbbb6a4
diff --git a/moviepy/version.py b/moviepy/version.pyindex 111b050d..0ebea03b 100644--- a/moviepy/version.py+++ b/moviepy/version.py@@ -1 +1 @@-__version__ = "0.2.1.8.06"+__version__ = "0.2.1.8.07"diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 896923fe..870242e5 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -226,29 +226,25 @@ class VideoClip(Clip):elif audio_codec == 'raw32':audio_codec = 'pcm_s32le'- if isinstance(audio, str):- # audio is some audiofile it is maybe not a wav file. It is- # NOT temporary file, it will NOT be removed at the end.- temp_audiofile = audio- make_audio = False- merge_audio = True-- elif self.audio is None:- # audio not provided as a file and no clip.audio- make_audio = merge_audio = False-- elif audio:+ audiofile = audio if isinstance(audio, basestring) else None+ make_audio = ((audiofile is None) and (audio==True) and+ (self.audio is not None))++ if make_audio:# The audio will be the clip's audio- if temp_audiofile is None:+ if temp_audiofile is not None:+ audiofile = temp_audiofile++ else:# make a name for the temporary audio fileD_ext = {'libmp3lame': 'mp3',- 'libvorbis':'ogg',- 'libfdk_aac':'m4a',- 'aac':'m4a',- 'pcm_s16le':'wav',- 'pcm_s32le': 'wav'}+ 'libvorbis':'ogg',+ 'libfdk_aac':'m4a',+ 'aac':'m4a',+ 'pcm_s16le':'wav',+ 'pcm_s32le': 'wav'}if audio_codec in D_ext.values():audio_ext = audio_codec@@ -256,64 +252,41 @@ class VideoClip(Clip):if audio_codec in D_ext.keys():audio_ext = D_ext[audio_codec]else:- raise ValueError('audio_codec for file'- '%s unkown !'%filename)+ 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.")- temp_audiofile = (name+Clip._TEMP_FILES_PREFIX ++ audiofile = (name+Clip._TEMP_FILES_PREFIX +"write_videofile_SOUND.%s"%audio_ext)- make_audio = ( (not os.path.exists(temp_audiofile))- or rewrite_audio)- merge_audio = True-- else:-- make_audio = False- merge_audio = False-- if merge_audio:-- # make a name for the temporary video file- videofile = (name + Clip._TEMP_FILES_PREFIX +- "write_videofile%s"%ext)-- else:-- videofile = filename-- # enough cpu for multiprocessing ?- enough_cpu = (multiprocessing.cpu_count() > 1)+ # enough cpu for multiprocessing ? USELESS RIGHT NOW, WILL COME AGAIN+ #enough_cpu = (multiprocessing.cpu_count() > 1)verbose_print(verbose, "\nMoviePy: building video file %s\n"%filename+40*"-"+"\n")if make_audio:- self.audio.write_audiofile(temp_audiofile,audio_fps,+ self.audio.write_audiofile(audiofile,audio_fps,audio_nbytes, audio_bufsize,audio_codec, bitrate=audio_bitrate,write_logfile=write_logfile,verbose=verbose)-- ffmpeg_write_video(self, videofile, fps, codec,++ ffmpeg_write_video(self, filename, fps, codec,bitrate=bitrate,preset=preset,write_logfile=write_logfile,+ audiofile = audiofile,verbose=verbose)- # Merge with audio if any and trash temporary files.+ if remove_temp and make_audio:+ os.remove(audiofile)- if merge_audio:- verbose_print(verbose, "\n\nNow merging video and audio:\n")- ffmpeg_merge_video_audio(videofile,temp_audiofile,- filename, ffmpeg_output=True)+ verbose_print(verbose, "\nYour video is ready !\n")- if remove_temp:- os.remove(videofile)- if make_audio:- os.remove(temp_audiofile)- verbose_print(verbose, "\nYour video is ready !\n")@requires_durationdef write_images_sequence(self, nameformat, fps=None, verbose=True):@@ -370,6 +343,8 @@ class VideoClip(Clip):return filenames++@requires_durationdef write_gif(self, filename, fps=None, program= 'ImageMagick',opt="OptimizeTransparency", fuzz=1, verbose=True,@@ -481,6 +456,7 @@ class VideoClip(Clip):os.remove(f)+@requires_durationdef write_gif2(self, filename, fps=None, program= 'ImageMagick',opt="OptimizeTransparency", fuzz=1, verbose=True,@@ -678,7 +654,6 @@ class VideoClip(Clip):pos = self.pos(ct)-# preprocess short writings of the positionif isinstance(pos,str):pos = { 'center': ['center','center'],@@ -708,6 +683,8 @@ class VideoClip(Clip):return blit(img, picture, pos, mask=mask, ismask=self.ismask)++def add_mask(self, constant_size=True):""" Add a mask VideoClip to the VideoClip.@@ -780,6 +757,7 @@ class VideoClip(Clip):return result+@outplacedef set_get_frame(self, gf):""" Change the clip's ``get_frame``.@@ -791,6 +769,7 @@ class VideoClip(Clip):self.size = gf(0).shape[:2][::-1]+@outplacedef set_audio(self, audioclip):""" Attach an AudioClip to the VideoClip.@@ -801,6 +780,7 @@ class VideoClip(Clip):self.audio = audioclip+@outplacedef set_mask(self, mask):""" Set the clip's mask.@@ -864,6 +844,7 @@ class VideoClip(Clip):# CONVERSIONS TO OTHER TYPES+@convert_to_seconds(['t'])def to_ImageClip(self,t=0, with_mask=True):"""@@ -877,6 +858,7 @@ class VideoClip(Clip):return newclip+def to_mask(self, canal=0):"""Returns a mask a video clip made from the clip.@@ -917,6 +899,7 @@ class VideoClip(Clip):self.audio = None+@outplacedef afx(self, fun, *a, **k):""" Transform the clip's audio.@@ -1241,6 +1224,7 @@ class TextClip(ImageClip):os.remove(temptxt)+@staticmethoddef list(arg):""" Returns the list of all valid entries for the argument ofdiff --git a/moviepy/video/compositing/concatenate.py b/moviepy/video/compositing/concatenate.pyindex 168626b3..068c01f6 100644--- a/moviepy/video/compositing/concatenate.py+++ b/moviepy/video/compositing/concatenate.py@@ -6,20 +6,26 @@ from moviepy.audio.AudioClip import CompositeAudioClipfrom moviepy.video.compositing.on_color import on_color-def concatenate(clipslist, transition=None, bg_color=(0, 0, 0),+def concatenate(clipslist, method="chain", transition=None, bg_color=(0, 0, 0),transparent=False, ismask=False, padding = 0):""" Concatenates several video clipsReturns a video clip made by clip by concatenating several video clips.(Concatenated means that they will be played one after another).- if the clips do not have the same resolution, the final- resolution will be such that no clip has to be resized. As- a consequence the final clip has the height of the highest++ There are two methods: method="chain" will produce a clip that simply outputs+ the frames of the succesive clips, without any correction if they are+ not of the same size of anything.++ With method="compose", if the clips do not have the same+ resolution, the final resolution will be such that no clip has+ to be resized.+ As a consequence the final clip has the height of the highestclip and the width of the widest clip of the list. All theclips with smaller dimensions will appear centered. The borderwill be transparent if mask=True, else it will be of thecolor specified by ``bg_color``.-+Returns a VideoClip instance if all clips have the same size andthere is no transition, else a composite clip.@@ -30,6 +36,9 @@ def concatenate(clipslist, transition=None, bg_color=(0, 0, 0),A 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.@@ -44,8 +53,8 @@ def concatenate(clipslist, transition=None, bg_color=(0, 0, 0),paddingDuration during two consecutive clips. If negative, a clip will- play at the same time as the clip it follows. A non-null padding- automatically sets the method to `compose`.+ play at the same time as the clip it follows. A non-null+ padding automatically sets the method to `compose`."""@@ -53,15 +62,32 @@ def concatenate(clipslist, transition=None, bg_color=(0, 0, 0),l = [[v, transition] for v in clipslist[:-1]]clipslist = reduce(lambda x, y: x + y, l) + [clipslist[-1]]transition = None+tt = np.cumsum([0] + [c.duration for c in clipslist])sizes = [v.size for v in clipslist]++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)))- result = CompositeVideoClip( [c.set_start(t).set_pos('center')++ if method == "chain":+ def gf(t):+ i = max([i for i, e in enumerate(tt) if e <= t])+ return clipslist[i].get_frame(t - tt[i])+ result.get_frame = gf+ result = VideoClip(ismask = ismask, get_frame = gf)+ if transparent:+ clips_w_masks = [(c.add_mask() if c.mask is None else c) for c in clips]+ masks = [c.mask for c in clips_w_masks]+ result.mask = concatenate(masks, method="chain", ismask=True)+++ elif method == "compose":+ result = CompositeVideoClip( [c.set_start(t).set_pos('center')for (c, t) in zip(clipslist, tt)],size = (w, h), bg_color=bg_color, ismask=ismask,transparent=transparent )diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex 008a309d..68b2b935 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -35,7 +35,7 @@ class FFMPEG_VideoWriter:Any filename like 'video.mp4' etc. but if you want to avoidcomplications it is recommended to use the generic extension'.avi' for all your videos.-+sizeSize (width,height) of the output video in pixels.@@ -54,6 +54,9 @@ class FFMPEG_VideoWriter:another pixel format is used, and this can cause problem in somevideo readers.+ audiofile+ Optional: The name of an audio file that will be incorporated to the video.+presetSets the time that FFMPEG will take to compress the video. The slower,the better the compression rate. Possibilities are: ultrafast,superfast,@@ -71,7 +74,7 @@ class FFMPEG_VideoWriter:- def __init__(self, filename, size, fps, codec="libx264",+ def __init__(self, filename, size, fps, codec="libx264", audiofile=None,preset="medium", bitrate=None, withmask=False,logfile=None):@@ -81,20 +84,20 @@ class FFMPEG_VideoWriter:self.filename = filenameself.codec = codecself.ext = self.filename.split(".")[-1]-+cmd = (- [ FFMPEG_BINARY, '-y',- "-loglevel", "error" if logfile==sp.PIPE else "info",+ [ FFMPEG_BINARY, '-y']+ +["-loglevel", "error" if logfile==sp.PIPE else "info","-f", 'rawvideo',"-vcodec","rawvideo",'-s', "%dx%d"%(size[0],size[1]),'-pix_fmt', "rgba" if withmask else "rgb24",'-r', "%.02f"%fps,- '-i', '-', '-an',- '-vcodec', codec,- '-preset', preset]+ '-i', '-', '-an']+ + (["-i", audiofile, "-acodec", "copy"] if (audiofile is not None) else [])+ +['-vcodec', codec,+ '-preset', preset]+ (['-b',bitrate] if (bitrate!=None) else [])-# http://trac.ffmpeg.org/ticket/658+ (['-pix_fmt', 'yuv420p']if ((codec == 'libx264') and@@ -102,8 +105,8 @@ class FFMPEG_VideoWriter:(size[1]%2 == 0))else [])-+ [ '-r', "%d"%fps, filename ]+ #+ (["-acodec", "copy"] if (audiofile is not None) else []))self.proc = sp.Popen(cmd, stdin=sp.PIPE,@@ -158,7 +161,7 @@ class FFMPEG_VideoWriter:def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,preset = "medium", withmask=False, write_logfile=False,- verbose=True):+ audiofile=None, verbose=True):if write_logfile:logfile = open(filename + ".log", 'w+')@@ -168,8 +171,8 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,verbose_print(verbose, "\nWriting video into %s\n"%filename)writer = FFMPEG_VideoWriter(filename, clip.size, fps, codec = codec,- preset=preset, bitrate=bitrate,- logfile=logfile)+ preset=preset, bitrate=bitrate, logfile=logfile,+ audiofile = audiofile)nframes = int(clip.duration*fps)diff --git a/moviepy/video/io/imageMagick_tools.py b/moviepy/video/io/imageMagick_tools.pyindex 7a1139cf..e4273d72 100644--- a/moviepy/video/io/imageMagick_tools.py+++ b/moviepy/video/io/imageMagick_tools.py@@ -1,9 +1,14 @@+""" Operations with ImageMagick. Still in the making."""+import osimport subprocessfrom moviepy.tools import subprocess_calldef gif_to_directory(gif_file,dirName=None):"""++ POSSIBLY VERY DEPRECATED AND BUGGY+Stores all the frames of the given .gif fileinto the directory ``dirName``. If ``dirName``is not provided, the directory has the same name