Video editing with Python
made 'outplace' decorator (bad idea ?). Fixed 'is_playing'. Put most of the audio reading engine in FFMPEGAudioReader
Zulkoad5a7a8e0c9d
diff --git a/examples/example_with_sound.py b/examples/example_with_sound.pyindex 2b364fe0..87231b61 100644--- a/examples/example_with_sound.py+++ b/examples/example_with_sound.py@@ -14,31 +14,40 @@ duration = 6 # duration of the final clip# LOAD THE MAIN SCENE# this small video contains the two scenes that we will put together.-main_clip = VideoFileClip("../../charadePhone.mp4")+main_clip = VideoFileClip("../../videos/charadePhone.mp4")W,H = main_clip.size# MAKE THE LEFT CLIP : cut, crop, add a mask--clip_left = main_clip.coreader().subclip(0,duration).\- crop( x1=60, x2=60 + 2*W/3)-mask = color_split((2*W/3,H), p1=(W/3,H), p2=(2*W/3,0),- col1=1, col2=0, grad_width=2)+mask = color_split((2*W/3,H),+ p1=(W/3,H), p2=(2*W/3,0),+ col1=1, col2=0,+ grad_width=2)++mask_clip = ImageClip(mask, ismask=True)-clip_left.mask = ImageClip(mask, ismask=True)+clip_left = (main_clip.coreader()+ .subclip(0,duration)+ .crop( x1=60, x2=60 + 2*W/3)+ .set_mask(mask_clip))# MAKE THE RIGHT CLIP : cut, crop, add a mask--clip_right = main_clip.coreader().subclip(21,21+duration).\- crop(x1=70, x2=70+2*W/3)--mask = color_split((2*W/3,H), p1=(2,H), p2=(W/3+2,0),- col1=0, col2=1, grad_width=2)-clip_right.mask = ImageClip(mask, ismask=True)+mask = color_split((2*W/3,H),+ p1=(2,H), p2=(W/3+2,0),+ col1=0, col2=1,+ grad_width=2)++mask_clip = ImageClip(mask, ismask=True)++clip_right = (main_clip.coreader()+ .subclip(21,21+duration)+ .crop(x1=70, x2=70+2*W/3)+ .set_mask(mask_clip))+diff --git a/examples/star_worms.py b/examples/star_worms.pyindex 3d688638..b4bf9719 100644--- a/examples/star_worms.py+++ b/examples/star_worms.py@@ -87,7 +87,7 @@ warped_txt.mask = warped_txt.mask.fl_image(fl_mask)# BACKGROUND IMAGE, DARKENED AT 60%-stars = ImageClip('../../starworms/stars.jpg')+stars = ImageClip('../../videos/stars.jpg')stars_darkened = stars.fl_image(lambda pic: (0.6*pic).astype('int16'))@@ -100,7 +100,7 @@ final = CompositeVideoClip([# WRITE TO A FILE-final.set_duration(8).to_videofile("starworms.avi")+final.set_duration(8).to_videofile("starworms.avi", fps=5)# This script is heavy (30s of computations to render 8s of video)@@ -175,5 +175,5 @@ annotated_clips = [ annotate(clip,text) for clip,text in [# Concatenate and write to a file-concatenate(annotated_clips).to_videofile('tutorial.avi')+concatenate(annotated_clips).to_videofile('tutorial.avi', fps=5)diff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex 5a4ab208..18995e23 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -7,8 +7,10 @@ and AudioClip.from copy import copyimport numpy as np-from moviepy.decorators import ( apply_to_mask, apply_to_audio,- time_can_be_tuple)+from moviepy.decorators import ( apply_to_mask,+ apply_to_audio,+ time_can_be_tuple,+ outplace)class Clip:@@ -48,7 +50,6 @@ class Clip:self.duration = None-def copy(self):"""Shallow copy of the clip. This method is intensively used@@ -111,7 +112,8 @@ class Clip:if hasattr(newclip, attr):a = getattr(newclip, attr)if a != None:- setattr(newclip, attr, a.fl(fl))+ new_a = a.fl(fun, keep_duration=keep_duration)+ setattr(newclip, attr, new_a)return newclip@@ -183,6 +185,7 @@ class Clip:@apply_to_mask@apply_to_audio@time_can_be_tuple+ @outplacedef set_start(self, t, change_end=True):"""Returns a copy of the clip, with the ``start`` attribute set@@ -199,41 +202,38 @@ class Clip:These changes are also applied to the ``audio`` and ``mask``clips of the current clip, if they exist."""- newclip = self.copy()- newclip.start = t- if (newclip.duration != None) and change_end:- newclip.end = t + newclip.duration- elif (newclip.end !=None):- newclip.duration = newclip.end - newclip.start-- return newclip++ self.start = t+ if (self.duration != None) and change_end:+ self.end = t + self.duration+ elif (self.end !=None):+ self.duration = self.end - self.start@apply_to_mask@apply_to_audio@time_can_be_tuple+ @outplacedef set_end(self, t):"""Returns a copy of the clip, with the ``end`` attribute set to``t``. Also sets the duration of the mask and audio, if any,of the returned clip."""- newclip = self.copy()- newclip.end = t- if newclip.start is None:- if newclip.duration != None:- newclip.start = max(0, t - newclip.duration)+ self.end = t+ if self.start is None:+ if self.duration != None:+ self.start = max(0, t - newclip.duration)else:- newclip.duration = newclip.end - newclip.start-- return newclip+ self.duration = self.end - self.start@apply_to_mask@apply_to_audio@time_can_be_tuple+ @outplacedef set_duration(self, t, change_end=True):"""Returns a copy of the clip, with the ``duration`` attribute@@ -241,41 +241,54 @@ class Clip:Also sets the duration of the mask and audio, if any, of thereturned clip."""- newclip = copy(self)- newclip.duration = t+ self.duration = tif change_end:- newclip.end = newclip.start + t+ self.end = self.start + telse:- newclip.start = newclip.end - t--- return newclip+ self.start = self.end - t-+ @outplacedef set_get_frame(self, gf):"""Sets a ``get_frame`` attribute for the clip. Useful for settingarbitrary/complicated videoclips."""-- newclip = copy(self)- newclip.get_frame = gf- return newclip+ self.get_frame = gf@time_can_be_tupledef is_playing(self, t):"""- Return true if t is between the start and the end of the clip.++ If t is a number, returns true if t is between the start and the+ end of the clip.+ If t is a numpy array, returns False if none of the t is in the+ clip, else returns a vector [b_1, b_2, b_3...] where b_i is true+ iff tti is in the clip."""+if isinstance(t, np.ndarray):- t = t.max()- return (((self.end is None) and (t >= self.start)) or- (self.start <= t <= self.end))--+ # is the whole list of t outside the clip ?+ tmin, tmax = t.min(), t.max()++ if (self.end != None) and (tmin > self.end) :+ return False++ if tmax < self.start:+ return False++ # If we arrive here, a part of t falls in the clip+ result = 1 * (t >= self.start)+ if (self.end != None):+ result *= (t <= self.end)+ return result++ else:++ return( (t >= self.start) and+ ((self.end is None) or (t <= self.end) ) )@time_can_be_tuple@apply_to_maskdiff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex 70ad95df..90ffa7d8 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -47,8 +47,15 @@ class AudioClip(Clip):"""- def __init__(self):+ def __init__(self, get_frame = None):Clip.__init__(self)+ if get_frame:+ self.get_frame = get_frame+ frame0 = self.get_frame(0)+ if hasattr(frame0, '__iter__'):+ self.nchannels = len(list(frame0))+ else:+ self.nchannels = 1@requires_durationdef to_soundarray(self,tt=None,fps=None, nbytes=2):@@ -72,19 +79,24 @@ class AudioClip(Clip):tt = np.arange(0,self.duration, 1.0/fps)snd_array = self.get_frame(tt)- snd_array = np.maximum(-0.999, np.minimum(0.999,snd_array))+ snd_array = np.maximum(-0.99,+ np.minimum(0.99,snd_array))inttype = {1:'int8',2:'int16',4:'int32'}[nbytes]return (2**(8*nbytes-1)*snd_array).astype(inttype)-- @property- def nchannels(self):- return len(list(self.get_frame(0)))+@requires_durationdef to_audiofile(self,filename, fps=44100, nbytes=2,- buffersize=5000, codec='libvorbis',+ buffersize=2000, codec='libvorbis',bitrate=None, verbose=True):+ """+ codecs = { 'libmp3lame': 'mp3',+ 'libvorbis':'ogg',+ 'libfdk_aac':'m4a',+ 'pcm_s16le':'wav',+ 'pcm_s32le': 'wav'}+ """return ffmpeg_audiowrite(self,filename, fps, nbytes, buffersize,codec, bitrate, verbose)@@ -142,6 +154,7 @@ class AudioArrayClip(AudioClip):return self.array[i]self.get_frame = get_frame+ self.nchannels = len(list(self.get_frame(0)))class CompositeAudioClip(AudioClip):@@ -166,19 +179,26 @@ class CompositeAudioClip(AudioClip):self.clips = clipsends = [c.end for c in self.clips]+ self.nchannels = max([c.nchannels for c in self.clips])if not any([(e is None) for e in ends]):self.duration = max(ends)+ self.end = max(ends)def get_frame(t):+ # buggy+++ played_parts = [c.is_playing(t) for c in self.clips]- sounds= [c.get_frame(t - c.start)- for c in clips if c.is_playing(t)]+ sounds= [c.get_frame(t - c.start)*np.array([part]).T+ for c,part in zip(self.clips, played_parts)+ if (part is not False) ]if isinstance(t,np.ndarray):- zero = np.zeros((len(t),2))+ zero = np.zeros((len(t),self.nchannels))else:- zero = np.zeros(2)+ zero = np.zeros(self.nchannels)return zero + sum(sounds)diff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.pyindex e838057e..ad3718c5 100644--- a/moviepy/audio/io/AudioFileClip.py+++ b/moviepy/audio/io/AudioFileClip.py@@ -60,92 +60,15 @@ class AudioFileClip(AudioClip):self.filename = filenameself.reader = FFMPEG_AudioReader(filename,fps=fps,nbytes=nbytes,- bufsize=buffersize+100)+ buffersize=buffersize)self.fps = fpsself.duration = self.reader.durationself.end = self.durationself.nframes = self.reader.nframes- self.buffersize= buffersize- self.buffer= None- self._fstart_buffer = 1- self._buffer_around(1)-- def gf(t):- bufsize = self.buffersize- if isinstance(t,np.ndarray):- # lazy implementation, but should not cause problems in- # 99.99 % of the cases- result = np.zeros((len(t),2))- in_time = (t>=0) & (t < self.duration)- inds = (self.fps*t+1).astype(int)[in_time]- f_tmin, f_tmax = inds.min(), inds.max()-- if not (0 <= (f_tmin - self._fstart_buffer) < len(self.buffer)):- self._buffer_around(f_tmin)- elif not (0 <= (f_tmax - self._fstart_buffer) < len(self.buffer)):- self._buffer_around(f_tmax)-- try:- tup = in_time.nonzero()- inds2 = inds - self._fstart_buffer- result[in_time] = self.buffer[inds - self._fstart_buffer]- return result- except IndexError as error:- print ("Error: wrong indices in video buffer. Maybe"+- " buffer too small.")- raise error-- else:- ind = int(self.fps*t)- if ind<0 or ind> self.nframes: # out of time: return 0- return np.zeros(self.nchannels)-- if not (0 <= (ind - self._fstart_buffer) <len(self.buffer)):- # out of the buffer: recenter the buffer- self._buffer_around(ind)-- # read the frame in the buffer- return self.buffer[ind - self._fstart_buffer]-- self.get_frame = gf-- @property- def nchannels(self):- """- R eturns the number of channels of the reader- (1: mono, 2: stereo)- """- return self.reader.nchannels-- def _buffer_around(self,framenumber):- """- Fills the buffer with frames, centered on ``framenumber``- if possible- """-- # start-frame for the buffer- fbuffer = framenumber - self.buffersize//2-- fbuffer = max(0, fbuffer)--- if (self.buffer!=None):- current_f_end =self._fstart_buffer + self.buffersize-1- if (fbuffer < current_f_end < fbuffer+ self.buffersize):- # We already have one bit of what must be read- conserved = current_f_end - fbuffer+1- chunksize = self.buffersize-conserved- array = self.reader.read_chunk(chunksize)- self.buffer = np.vstack([self.buffer[-conserved:], array])- else:- self.reader.seek(fbuffer)- self.buffer = self.reader.read_chunk(self.buffersize)- else:- self.reader.seek(fbuffer)- self.buffer = self.reader.read_chunk(self.buffersize)-- self._fstart_buffer = fbuffer+ self.get_frame = lambda t: self.reader.get_frame(t)+ self.nchannels = self.reader.nchannels+def coreader(self):""" Returns a copy of the AudioFileClip, i.e. a new entrance pointdiff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.pyindex 66e2fc45..f7637707 100644--- a/moviepy/audio/io/ffmpeg_audiowriter.py+++ b/moviepy/audio/io/ffmpeg_audiowriter.py@@ -45,13 +45,14 @@ class FFMPEG_AudioWriter:cmd = ([ FFMPEG_BINARY, '-y',"-f", 's%dle'%(8*nbytes),"-acodec",'pcm_s%dle'%(8*nbytes),- '-r', "%d"%fps_input,+ '-ar', "%d"%fps_input,'-ac',"%d"%nchannels,'-i', '-']+ (['-vn'] if input_video==None else[ "-i", input_video, '-vcodec', 'copy'])+ ['-acodec', codec]- + (['-b',bitrate] if (bitrate!=None) else [])+ + ['-ar', "%d"%fps_input]+ + (['-ab',bitrate] if (bitrate!=None) else [])+ [ filename ])self.proc = sp.Popen(cmd,stdin=sp.PIPE, stderr=sp.PIPE)diff --git a/moviepy/audio/io/preview.py b/moviepy/audio/io/preview.pyindex 70fe8620..a715fb1c 100644--- a/moviepy/audio/io/preview.py+++ b/moviepy/audio/io/preview.py@@ -10,7 +10,7 @@ pg.display.set_caption('MoviePy')@requires_duration-def preview(clip, fps=22050, buffersize=50000, nbytes= 2,+def preview(clip, fps=22050, buffersize=4000, nbytes= 2,audioFlag=None, videoFlag=None):"""Plays the sound clip with pygame.@@ -48,7 +48,6 @@ def preview(clip, fps=22050, buffersize=50000, nbytes= 2,tt = (1.0/fps)*np.arange(pospos[0],pospos[1])sndarray = clip.to_soundarray(tt,nbytes)chunk = pg.sndarray.make_sound(sndarray)- Delta = tt[1]-tt[0]if (audioFlag !=None) and (videoFlag!= None):audioFlag.set()diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex 79af1e8c..e075f668 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -19,7 +19,7 @@ class FFMPEG_AudioReader:Name of any video or audio file, like ``video.mp4`` or``sound.wav`` etc.- bufsize+ buffersizeThe size of the buffer to use. Should be bigger than the bufferused by ``to_audiofile``@@ -36,19 +36,24 @@ class FFMPEG_AudioReader:"""- def __init__(self, filename, bufsize, print_infos=False,- fps=44100, nbytes=2):-+ def __init__(self, filename, buffersize, print_infos=False,+ fps=44100, nbytes=2, nchannels=2):+self.filename = filenameself.nbytes = nbytes- self.bufsize=bufsizeself.fps = fpsself.f = 's%dle'%(8*nbytes)self.acodec = 'pcm_s%dle'%(8*nbytes)- self.nchannels = 2+ self.nchannels = nchannelsself.load_infos()self.proc = None++ self.buffersize=buffersize+ self.buffer= None+ self.buffer_startframe = 1self.initialize()+ self.buffer_around(1)+def load_infos(self, print_infos=False):""" reads the FFMPEG info on the file and sets self.size@@ -99,10 +104,10 @@ class FFMPEG_AudioReader:'-acodec', self.acodec,'-ar', "%d"%self.fps,'-ac', '%d'%self.nchannels, '-'])- self.proc = sp.Popen( cmd, bufsize=self.bufsize,+ self.proc = sp.Popen( cmd, bufsize=self.buffersize,stdout=sp.PIPE,stderr=sp.PIPE)- self.pos = int(self.fps*starttime)+ self.pos = int(self.fps*starttime+1)@@ -148,40 +153,85 @@ class FFMPEG_AudioReader:self.proc.stderr]:std.close()del self.proc++ def get_frame(self, tt):++ buffersize = self.buffersize+ if isinstance(tt,np.ndarray):+ # lazy implementation, but should not cause problems in+ # 99.99 % of the cases- def __del__(self):- self.close_proc()- del self.lastread++ # elements of t that are actually in time+ in_time = (tt>=0) & (tt < self.duration)++ frames = (self.fps*tt+1).astype(int)[in_time]+ fr_min, fr_max = frames.min(), frames.max()++ if not (0 <=+ (fr_min - self.buffer_startframe)+ < len(self.buffer)):+ self.buffer_around(fr_min)+ elif not (0 <=+ (fr_max - self.buffer_startframe)+ < len(self.buffer)):+ self.buffer_around(fr_max)++ try:+ result = np.zeros((len(tt),self.nchannels))+ result[in_time] = self.buffer[frames - self.buffer_startframe]+ return result+ except IndexError as error:+ print ("Error: wrong indices in video buffer. Maybe"++ " buffer too small.")+ raise error++ else:++ ind = int(self.fps*tt)+ if ind<0 or ind> self.nframes: # out of time: return 0+ return np.zeros(self.nchannels)++ if not (0 <= (ind - self.buffer_startframe) <len(self.buffer)):+ # out of the buffer: recenter the buffer+ self.buffer_around(ind)++ # read the frame in the buffer+ return self.buffer[ind - self.buffer_startframe]+++ def buffer_around(self,framenumber):+ """+ Fills the buffer with frames, centered on ``framenumber``+ if possible+ """+ # start-frame for the buffer+ new_bufferstart = max(0, framenumber - self.buffersize // 2)--class WaveReader:- """ DEPRECATED - Do not use if you can avoid. """++ if (self.buffer!=None):+ current_f_end = self.buffer_startframe + self.buffersize+ if (new_bufferstart <+ current_f_end <+ new_bufferstart + self.buffersize):+ # We already have one bit of what must be read+ conserved = current_f_end - new_bufferstart + 1+ chunksize = self.buffersize-conserved+ array = self.read_chunk(chunksize)+ self.buffer = np.vstack([self.buffer[-conserved:], array])+ else:+ self.seek(new_bufferstart)+ self.buffer = self.read_chunk(self.buffersize)+ else:+ self.seek(new_bufferstart)+ self.buffer = self.read_chunk(self.buffersize)++ self.buffer_startframe = new_bufferstart- def __init__(self, filename):++ def __del__(self):+ self.close_proc()- import os- from moviepy.Clip import Clip- if not filename.endswith('.wav'):- name, ext = os.path.splitext(os.path.basename(filename))- if temp_wav is None:- filename = Clip._TEMP_FILES_PREFIX + filename+'.wav'- if not os.exists(filename):- ffmpeg.extract_sound(filename, temp, fps, bitrate)-- self.filename = filename- wavf = wave.open(filename)- self.nchannels = wavf.getnchannels()- self.fps = wavf.getframerate()- self.nframes = wavf.getnframes()- self.nbytes = wavf.getsampwidth()- self._wavfile = wavf-- self.duration = (1.0*self.nframes/self.fps)- self.end = self.duration- self.np_dtype = {1:'int8',2:'int16',4:'int32'}[self.nbytes]-- self.buffersize= buffersize- self._buffer_around(0)diff --git a/moviepy/decorators.py b/moviepy/decorators.pyindex 81787772..d1ab14a0 100644--- a/moviepy/decorators.py+++ b/moviepy/decorators.py@@ -6,6 +6,14 @@ import decoratorfrom moviepy.tools import cvsecs+def outplace(f, clip, *a, **k):+ """ Enables to make operations outplace """+ newclip = clip.copy()+ f(newclip, *a, **k)+ return newclip++@decorator.decoratordef apply_to_mask(f, clip, *a, **k):""" This decorator will apply the same function f to the mask of@@ -30,8 +38,7 @@ def apply_to_audio(f, clip, *a, **k):@decorator.decoratordef add_mask_if_none(f, clip, *a, **k):- """ This decorator will apply the function f to the audio of- the clip created with f """+ """ Add a mask to the clip if there is none. """if clip.mask is None:clip = clip.add_mask()@@ -40,7 +47,7 @@ def add_mask_if_none(f, clip, *a, **k):@decorator.decoratordef requires_duration(f, clip, *a, **k):- """ will raise an error if the clip has no duration."""+ """ Raise an error if the clip has no duration."""if clip.duration is None:raise ValueError("Attribute 'duration' not set")@@ -49,10 +56,11 @@ def requires_duration(f, clip, *a, **k):@decorator.decoratordef audio_video_fx(f, clip, *a, **k):- """+ """ Use an audio function on a video/audio clip+This decorator tells that the function f (audioclip -> audioclip)can be also used on a video clip, at which case it returns a- videoclip with modified audio.+ videoclip with unmodified video and modified audio."""if hasattr(clip, "audio"):@@ -66,9 +74,8 @@ def audio_video_fx(f, clip, *a, **k):@decorator.decoratordef time_can_be_tuple(f, clip, *a, **k):"""- This decorator tells that the function f (audioclip -> audioclip)- can be also used on a video clip, at which case it returns a- videoclip with modified audio.+ All tuples in the arguments of f will be considered as time and+ converted to seconds."""fun = lambda e: e if (not isinstance(e,tuple)) else cvsecs(*e)diff --git a/moviepy/tools.py b/moviepy/tools.pyindex 32795e44..3f4b959f 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -17,7 +17,8 @@ def subprocess_call(cmd, stdout=None, stdin = None,executes the subprocess command"""- verboseprint = sys_write_flush if verbose else (lambda *a : None)+ def verboseprint(s):+ if verbose: sys_write_flush(s)verboseprint( "\nMoviePy Running:\n>>> "+ " ".join(cmd) )@@ -26,10 +27,11 @@ def subprocess_call(cmd, stdout=None, stdin = None,stderr = stderr )proc.wait()- if proc.returncode and errorprint:- sys_write_flush( "\nMoviePy: WARNING !\n"+ if proc.returncode:+ if errorprint:+ sys_write_flush( "\nMoviePy: WARNING !\n"" The following command returned an error:\n")- sys_write_flush( proc.stderr.read().decode('utf8'))+ sys_write_flush( proc.stderr.read().decode('utf8'))raise IOErrorelse:verboseprint( "\n... command successful.\n")diff --git a/moviepy/version.py b/moviepy/version.pyindex 0370c18e..c9ae20bb 100644--- a/moviepy/version.py+++ b/moviepy/version.py@@ -1 +1 @@-__version__ = '0.2.1.7.07'+__version__ = '0.2.1.7.08'diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex e97cedda..50ad3ae3 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -15,7 +15,9 @@ from tqdm import tqdmimport numpy as npfrom moviepy.decorators import (apply_to_mask,- requires_duration)+ requires_duration,+ outplace,+ add_mask_if_none)from moviepy.tools import subprocess_call, sys_write_flush@@ -29,8 +31,6 @@ from ..Clip import Clipfrom ..conf import FFMPEG_BINARY--class VideoClip(Clip):"""Base class for video clips.@@ -89,8 +89,6 @@ class VideoClip(Clip):self.size =get_frame(0).shape[:2][::-1]self.ismask = ismask--@propertydef w(self):return self.size[0]@@ -116,69 +114,12 @@ class VideoClip(Clip):mask = 255 * self.mask.get_frame(t)im = np.dstack([im, mask]).astype('uint8')ffmpeg_write_image(filename, im)---- @requires_duration- def to_directory(self, foldername, fps, transparent=True,- overwrite=True, startFrame=0):- """ Write the frames of the clip into a folder.-- Writes the frames of the clip into a folder as png format,- and returns the :class:DirectoryClip associated with this- folder-- Parameters- ------------ foldername- Name of the folder (what did you expect ?)-- fps- Number of frames per second of movie.-- transparent- If `True`, the png images generated will possess an alpha- layer representing the mask of the clip.-- overwrite- If `True`, will overwrite the content of `folder`- if already existing.-- startFrame:- Useless for the moment, but may come in handy once- parallelization is fully implemented.-- """- print( "writing frames in [%s]" % foldername )-- try:- os.mkdir(foldername)- except:- if not overwrite:- print( "Error: Maybe set overwrite =true ")-- tt = np.arange(0, self.duration, 1.0 / fps)- tt_feedback = tt[::len(tt) / 10]-- for i, t in tqdm(list(enumerate(tt))[startFrame:]):-- picname = "%s/%s%06d.png" % (foldername, foldername, i)- pic = self.get_frame(t)- if transparent and (self.mask is not None):- fmask = self.mask.get_frame(t)- pic = np.dstack([pic, 255 * fmask]).astype('uint8')- imsave(picname, pic)-- print( "done." )- return DirectoryClip(foldername, fps=fps)--+def to_videofile(self, filename, fps=24, codec='libx264',bitrate=None, audio=True, audio_fps=44100,audio_nbytes = 2, audio_codec= 'libvorbis',- audio_bitrate = None, audio_bufsize = 40000,+ audio_bitrate = None, audio_bufsize = 2000,temp_audiofile=None,rewrite_audio = True, remove_temp = True,para = False, verbose = True):@@ -322,7 +263,6 @@ class VideoClip(Clip):filename, ffmpeg_output=True)if remove_temp:- print("print")os.remove(videofile)if not isinstance(audio,str):os.remove(temp_audiofile)@@ -596,60 +536,51 @@ class VideoClip(Clip):return result-+ @outplacedef set_get_frame(self, gf):""" Change the clip's ``get_frame``.Returns a copy of the VideoClip instance, with the get_frameattribute set to `gf`."""- newclip = Clip.set_get_frame(self, gf)- newclip.size = newclip.get_frame(0).shape[:2][::-1]- return newclip-+ self.get_frame = gf+ self.size = gf(0).shape[:2][::-1]+ @outplacedef set_audio(self, audioclip):""" Attach an AudioClip to the VideoClip.Returns a copy of the VideoClip instance, with the `audio`attribute set to ``audio``, hich must be an AudioClip instance."""- newclip = copy(self)- newclip.audio = audioclip- return newclip-+ self.audio = audioclip+ @outplacedef set_mask(self, mask):""" Set 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) VideoClip"""- assert mask.ismask- newclip = copy(self)- newclip.mask = mask- return newclip--+ assert ( (mask is None) or mask.ismask )+ self.mask = mask+ @outplace+ @add_mask_if_nonedef set_opacity(self, op):""" Set the opacity/transparency level of the clip.Returns a semi-transparent copy of the clip where the mask ismultiplied by ``op`` (any float, normally between 0 and 1)."""- newclip = copy(self)- if not newclip.mask:- newclip = newclip.add_mask()-- newclip.mask = newclip.mask.fl_image(lambda pic: op * pic)- return newclip+ self.mask = self.mask.fl_image(lambda pic: op * pic)@apply_to_mask+ @outplacedef set_pos(self, pos, relative=False):""" Set the clip's position in compositions.@@ -674,15 +605,13 @@ class VideoClip(Clip):>>> clip.set_pos(lambda t: ('center', 50+t) )"""-- newclip = copy(self)- newclip.relative_pos = relative++ self.relative_pos = relativeif hasattr(pos, '__call__'):- newclip.pos = pos+ self.pos = poselse:- newclip.pos = lambda t: pos-- return newclip+ self.pos = lambda t: pos+#--------------------------------------------------------------# CONVERSIONS@@ -716,9 +645,8 @@ class VideoClip(Clip):Return a non-mask video clip made from the mask video clip."""if self.ismask:- newclip = self.fl_image(- lambda pic: np.dstack(3 * [255 * pic]- ).astype('uint8'))+ f = lambda pic: np.dstack(3 * [255 * pic]).astype('uint8')+ newclip = self.fl_image( f )newclip.ismask = Falsereturn newclipelse:@@ -729,28 +657,24 @@ class VideoClip(Clip):# Audio-+ @outplacedef without_audio(self):""" Remove the clip's audio.Return a copy of the clip with audio set to None."""- newclip = copy(self)- newclip.audio = None- return newclip-+ self.audio = None+ @outplacedef afx(self, fun, *a, **k):""" Transform the clip's audio.Return a new clip whose audio has been transformed by ``fun``."""- newclip = self.copy()- newclip.audio = newclip.audio.fx(fun, *a, **k)- return newclip+ self.audio = self.audio.fx(fun, *a, **k)#-----------------------------------------------------------------# Previews:@@ -850,11 +774,12 @@ class ImageClip(VideoClip):def fl(self, fl, apply_to=[], keep_duration=True):- """ General filter+ """ General transformation filter.Equivalent to VideoClip.fl . The result is no more anImageClip, it has the class VideoClip (since it may be animated)"""+# When we use fl on an image clip it may become animated.#Therefore the result is not an ImageClip, just a VideoClip.newclip = VideoClip.fl(self,fl, apply_to=apply_to,@@ -863,7 +788,7 @@ class ImageClip(VideoClip):return newclip-+ @outplacedef fl_image(self, image_func, apply_to= []):""" Image-transformation filter.@@ -872,23 +797,21 @@ class ImageClip(VideoClip):and not for each 'frame'."""- newclip = self.copy()arr = image_func(self.get_frame(0))- newclip.size = arr.shape[:2][::-1]- newclip.get_frame = lambda t: arr- newclip.img = arr+ self.size = arr.shape[:2][::-1]+ self.get_frame = lambda t: arr+ self.img = arrfor attr in apply_to:- if hasattr(newclip, attr):- a = getattr(newclip, attr)+ if hasattr(self, attr):+ a = getattr(self, attr)if a != None:- setattr(newclip, attr, a.fl_image(image_func))-- return newclip+ new_a = a.fl(image_func)+ setattr(newclip, attr, new_a)-- def fl_time(self, timefun, apply_to =['mask', 'audio']):+ @outplace+ def fl_time(self, time_func, apply_to =['mask', 'audio']):""" Time-transformation filter.Applies a transformation to the clip's timeline@@ -897,15 +820,13 @@ class ImageClip(VideoClip):This method does nothing for ImageClips (but it may affect theirmasks of their audios). The result is still an ImageClip."""- newclip = self.copy()for attr in apply_to:- if hasattr(newclip, attr):- a = getattr(newclip, attr)+ if hasattr(self, attr):+ a = getattr(self, attr)if a != None:- setattr(newclip, attr, a.fl_image(image_func))-- return newclip+ new_a = a.fl_image(time_func)+ setattr(self, attr, new_a)@@ -1045,7 +966,7 @@ class TextClip(ImageClip):if print_cmd:print( " ".join(cmd) )- subprocess_call(cmd)+ subprocess_call(cmd, verbose=False )ImageClip.__init__(self, tempfile, transparent=transparent)self.txt = txtdiff --git a/moviepy/video/compositing/CompositeVideoClip.py b/moviepy/video/compositing/CompositeVideoClip.pyindex 2a314fdf..26c9c66a 100644--- a/moviepy/video/compositing/CompositeVideoClip.py+++ b/moviepy/video/compositing/CompositeVideoClip.py@@ -58,6 +58,7 @@ class CompositeVideoClip(VideoClip):ends = [c.end for c in self.clips]if not any([(e is None) for e in ends]):self.duration = max(ends)+ self.end = max(ends)# compute audioaudioclips = [v.audio for v in self.clips if v.audio != None]diff --git a/moviepy/video/io/DirectoryClip.py b/moviepy/video/io/DirectoryClip.pyindex 547af61a..4290451e 100644--- a/moviepy/video/io/DirectoryClip.py+++ b/moviepy/video/io/DirectoryClip.py@@ -1,90 +1,38 @@from moviepy.video.VideoClip import VideoClip+from .ffmpeg_reader import ffmpeg_read_imageclass DirectoryClip(VideoClip):"""A VideoClip read from a directory containing pictures.- Still experimental and subject to changes.-- DEPRECATED - needs update"""- def __init__(self, foldername, fps, transparent=True, ismask=False):+ def __init__(self, foldername, fps, withmask=True, ismask=False):VideoClip.__init__(self, ismask=ismask)self.directory = foldernameself.fps = fps- allfiles = os.listdir(foldername)- self.pics = sorted(["%s/%s" % (foldername, f) for f in allfiles- if not f.endswith(('.txt','.wav'))])+ self.imagefiles = sorted(os.listdir(foldername))- audio = [f for f in allfiles if f.endswith('.wav')]+ self.duration = 1.0* len(self.imagefiles) / self.fps+ self.end = self.duration- if len(audio) > 0:- self.audio = AudioFileClip(audio[0])- self.audiofile =audio[0]-- self.size = imread(self.pics[0]).shape[:2][::-1]-- if imread(self.pics[0]).shape[2] == 4: # transparent png-- if ismask:- def get_frame(t):- return 1.0 * imread(self.pics[int(self.fps * t)])[:, :, 3] / 255- else:- def get_frame(t):- return imread(self.pics[int(self.fps * t)])[:, :, :2]-- if transparent:- self.mask = DirectoryClip(foldername, fps, ismask=True)-- else:-- def get_frame(t):- return imread(self.pics[int(self.fps * t)])-- self.get_frame = get_frame- self.duration = 1.0 * len(self.pics) / self.fps-- def to_videofile(self, filename, bitrate=3000, audio=True):- """- Transforms the directory clip into a movie using ffmpeg.- Uses the framerate specified by ``clip.fps``.+ self.lastpos = None+ self.lastimage = None- :param filename: name of the video file to write in, like- 'myMovie.ogv' or 'myFilm.mp4'.- :param bitrate: final bitrate of the video file (in kilobytes/s).- 3000-6000 gives generally light files and an acceptable quality.- :param audio: the name of an audiofile to be incorporated in the- the movie.- """-- if audio != None:- # if there is audio, then ``videofile`` is a temporary file- # that will then be merged with audio and removed.- name, ext = os.path.splitext(os.path.basename(filename))- videofile = Clip._TEMP_FILES_PREFIX + name + ext- else:- videofile = filename+++ def get_frame(t):- cmd = ["ffmpeg", "-y", "-f", "image2",- "-r","%d"%self.fps,- "-i", os.path.join(self.directory,self.directory,"%06d.png"),- "-b", "%dk"%bitrate,- "-r", "%d"%self.fps, videofile]-- print "running : "+ " ".join(cmd)- subprocess.call(cmd)-- if audio:- # Merge video and audio, and remove temporary files- subprocess.call(["ffmpeg", "-y",- "-i", self.audiofile +- "-i", videofile,- "-strict experimental", filename])-- print "running: %s" % cmd- os.system(cmd)- os.remove(videofile)+ pos = int(self.fps*t)+ if pos != self.lastpos:+ self.lastimage = ffmpeg_read_image(self.imagefiles[ind],+ withmask=withmask)+ self.lastpos = pos++ return self.lastimage++ self.get_frame = get_frame+ self.size = get_frame(0).shape[:2][::-1]diff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.pyindex 3711c4cd..7eb93fce 100644--- a/moviepy/video/io/VideoFileClip.py+++ b/moviepy/video/io/VideoFileClip.py@@ -27,10 +27,10 @@ class VideoFileClip(VideoClip):has_mask:Set this to 'True' if there is a mask included in the videofile.- Video files rarely contain masks, but some video codecs enable- that. For istance if you have a MoviePy VideoClip with a mask you- can save it to a videofile with a mask. (see also- ``VideoClip.to_videofile`` for more details).+ Video files rarely contain masks, but some video codecs enable+ that. For istance if you have a MoviePy VideoClip with a mask you+ can save it to a videofile with a mask. (see also+ ``VideoClip.to_videofile`` for more details).audio:Set to `False` if the clip doesn't have any audio or if you do not@@ -53,13 +53,6 @@ class VideoFileClip(VideoClip):VideoClip.__init__(self, ismask)- # We store the construction parameters in case we need to make- # a copy (a 'co-reader').-- self.parameters = {'filename':filename, 'ismask':ismask,- 'has_mask':has_mask, 'audio':audio,- 'audio_buffersize':audio_buffersize}-# Make a readerpix_fmt= "rgba" if has_mask else "rgb24"self.reader = FFMPEG_VideoReader(filename, pix_fmt=pix_fmt)@@ -78,19 +71,3 @@ class VideoFileClip(VideoClip):buffersize= audio_buffersize,fps = audio_fps,nbytes = audio_nbytes)-- def coreader(self, audio=True):- """- Returns a copy of the AudioFileClip with an autonomous reader.- Maybe REMOVED in the coming versions. Wait and see. ::-- >>> clip = VideofileClip("myHolidays.mp4", ismask=True)- >>> clip2 = VideofileClip("myHolidays.mp4", ismask=True)-- is equivalent to ::-- >>> clip = VideofileClip("myHolidays.mp4", ismask=True)- >>> clip2 = clip.coreader()- """-- return VideoFileClip(**self.parameters)diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex 5e715d59..42cc97c7 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -67,7 +67,6 @@ class FFMPEG_VideoReader:# open the file in a pipe, provoke an error, read outputproc = sp.Popen([FFMPEG_BINARY, "-i", self.filename, "-"],bufsize=10**6,- stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.PIPE)proc.stdout.readline()diff --git a/setup.py b/setup.pyindex 522eab94..e8613a00 100644--- a/setup.py+++ b/setup.py@@ -9,7 +9,7 @@ from setuptools import setup, find_packagessetup(name='moviepy',version=__version__,- author='Zulko 2013',+ author='Zulko 2014',description='Module for script-based video editing',long_description=open('README.rst').read(),license='see LICENSE.txt',