Video editing with Python
No Error when frames are missing at the end of Video Files. Instead, a warning is printed. Improved the scroll function too. Corrected the docs.
Zulkof7922e3f0157
diff --git a/docs/crash_course/crash_course.rst b/docs/crash_course/crash_course.rstindex 379fb651..572691bb 100644--- a/docs/crash_course/crash_course.rst+++ b/docs/crash_course/crash_course.rst@@ -58,11 +58,10 @@ Classes of video clipsVideo 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.-- ``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.-+- ``VideoFileClip('myHolidays.mp4')`` will generate a clip from a movie file. The input file can have any format or extension : mp4, flv, mov, ... even gif !+- ``ImageClip('myPicture.png')`` will make a clip displaying a picture, for an *a priori* infinite duration.+- ``ColorClip((height,width),color=(R,G,B))`` makes a special ImageClip of a single color.+- ``TextClip('Hello folks !',font='Impact-Regular')`` generates a special ImageClip representing a text. The generation of the text image is made by the software ImageMagick (see the Installation section).To that list we should add the ``CompositeVideoClips`` which are obtained by putting several clips together... _CompositeVideoClips:@@ -108,18 +107,21 @@ Finally, if ``clip2`` and ``clip3`` are smaller than ``clip1``, you can decide wNote that there are many ways to specify the position: ::- clip2.set_pos((45,150)) # x=45, y=150+ clip2.set_pos((45,150)) # x=45, y=150 , in pixels# clip2 is horizontally centered, and at the top of the pictureclip2.set_pos(("center","top"))++ # clip2 is vertically centered, at the left of the picture+ clip2.set_pos(("left","center"))- # clip2 is at 40% of the width, 70% of the height:+ # clip2 is at 40% of the width, 70% of the height of the screen:clip2.set_pos((0.4,0.7), relative=True)# clip2's position is horizontally centered, and moving down !clip2.set_pos(lambda t: ('center', 50+t) )-Be careful when indicating the position that the ``y`` position has its zero at the top of the picture:+When indicating the position keep in mind that the ``y`` coordinate has its zero at the top of the picture:.. figure:: videoWH.jpeg@@ -222,7 +224,7 @@ but this is not easy to read. To have a clearer syntax you can use ``clip.fx``: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.editor *+ from moviepy.editor import *clip = VideoFileClip("myvideo.avi").\fx( vfx.resize, width=460).\ # resize (keep aspect ratio)fx( vfx.speedx, 2).\ # double speed@@ -244,15 +246,27 @@ You can change the timeline of the clip with ``clip.fl_time`` like this: ::Now the clip ``modifiedClip1`` plays the same as ``myClip``, only three times faster, while ``modifiedClip2`` will play ``myClip`` by oscillating between the times t=0s and t=2s. Note that in the last case you have created a clip of infinite duration (which is not a problem for the moment).-You can also modify the display of a clip with ``clip.fl_image``. The following takes a clip and inverts the green and blue channels: ::+You can also modify the display of a clip with ``clip.fl_image``. The following takes a clip and inverts the green and blue channels of the frames: ::++ def invert_green_blue(image):+ return image[:,:,[0,2,1]]++ modifiedClip = myClip.fl_image( invert_green_blue )- modifiedClip = myClip.fl_image(lambda image: image[:,:,[0,2,1]])+Finally, you may want to process the clip by taking into account both the time and the frame picture. This is possible with the method ``clip.fl(filter)``. The filter must be a function which takes two arguments and returns a picture. the fist argument is a ``get_frame`` method (i.e. a function ``g(t)`` which given a time returns the clip's frame at that time), and the second argument is the time. ::-Finally, you may want to process the clip by taking into account the time and the picture at the same time. This is possible with ``clip.fl``. The filter must be a function which takes two arguments and returns a picture. the fist argument is a ``get_frame`` method (i.e. a function ``g(t)`` which given a time returns the clip's frame at that time), and the second argument is the time. ::+ def scroll(get_frame, t):+ """+ This function returns a 'region' of the current frame.+ The position of this region depends on the time.+ """+ frame = get_frame(t)+ frame_region = frame[int(t):int(t)+360,:]+ return frame_region- modifiedClip = myClip.fl(lambda gf,t: gf(t)[int(t):int(t)+360,:]+ modifiedClip = myClip.fl( scroll )-This will scroll down the clip with a constant height of 360 pixels.+This will scroll down the clip, with a constant height of 360 pixels.When programming a new effect, whenever it is possible, prefer using ``fl_time`` and``fl_image`` instead of ``fl`` if possible when implementingdiff --git a/moviepy/Clip.py b/moviepy/Clip.pyindex 08397d9e..ed3269d2 100644--- a/moviepy/Clip.py+++ b/moviepy/Clip.py@@ -251,6 +251,9 @@ class Clip:set to ``t``.Also sets the duration of the mask and audio, if any, of thereturned clip.+ If change_end is False, the start attribute of the clip will+ be modified in function of the duration and the preset end+ of the clip."""self.duration = tif change_end:diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.pyindex 77f18828..e8b0588f 100644--- a/moviepy/audio/io/readers.py+++ b/moviepy/audio/io/readers.py@@ -110,7 +110,9 @@ class FFMPEG_AudioReader:self.proc.stdout.flush()self.pos = self.pos+chunksizereturn result-+++def seek(self,pos):"""Reads a frame at time t. Note for coders: getting an arbitrary@@ -121,7 +123,6 @@ class FFMPEG_AudioReader:"""if (pos < self.pos) or (pos> (self.pos+1000000)):t = 1.0*pos/self.fps-self.initialize(t)elif pos > self.pos:#print pos@@ -129,6 +130,8 @@ class FFMPEG_AudioReader:# last case standing: pos = current posself.pos = pos++def close_proc(self):if self.proc is not None:self.proc.terminate()diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex 85854cc8..758da598 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -473,18 +473,18 @@ class VideoClip(Clip):>>> newclip = clip.subapply(lambda c:c.speedx(0.5) , 3,6)"""- left = None if (ta == 0) else self.subclip(0, tb=ta)- center = self.subclip(ta, tb).fx(**kwargs)- right = None if (tb is None) else self.subclip(ta=tb)- clips = [c for c in [left, center, right] if c != None]- cc = VideoClip.concat(clips)- if self.start != None:- cc = cc.set_start(self.start)+ left = None if (ta == 0) else self.subclip(0, ta)+ center = self.subclip(ta, tb).fx(fx,**kwargs)+ right = None if (tb is None) else self.subclip(t_start=tb)++ clips = [c for c in [left, center, right] if c != None]- return cc+ # beurk, have to find other solution+ from moviepy.video.compositing.concatenate import concatenate+ return concatenate(clips).set_start(self.start)# IMAGE FILTERS@@ -595,7 +595,7 @@ class VideoClip(Clip):Background color of the final clip ([R,G,B]).pos- Position of the clip in the final clip.+ Position of the clip in the final clip. 'center' is the defaultcol_opacityParameter in 0..1 indicating the opacity of the colored@@ -608,6 +608,7 @@ class VideoClip(Clip):if pos is None:pos = 'center'colorclip = ColorClip(size, color)+if col_opacity is not None:colorclip = colorclip.set_opacity(col_opacity)@@ -617,6 +618,9 @@ class VideoClip(Clip):result = CompositeVideoClip([colorclip, self.set_pos(pos)],transparent=(col_opacity != None))+ if isinstance(self, ImageClip):+ result = result.to_ImageClip()+return resultdiff --git a/moviepy/video/fx/scroll.py b/moviepy/video/fx/scroll.pyindex 51e20abd..59a285c9 100644--- a/moviepy/video/fx/scroll.py+++ b/moviepy/video/fx/scroll.py@@ -1,3 +1,4 @@+import numpy as npdef scroll(clip, h=None, w=None, x_speed=0, y_speed=0,x_start=0, y_start=0, apply_to="mask"):@@ -5,8 +6,13 @@ def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,credits """if h is None: h = clip.hif w is None: w = clip.w++ xmax = clip.w-w-1+ ymax = clip.h-h-1+def f(gf,t):- x = x_start+int(x_speed*t)- y = y_start+ int(y_speed*t)+ x = max(0, min(xmax, x_start+ np.round(x_speed*t)))+ y = max(0, min(ymax, y_start+ np.round(y_speed*t)))return gf(t)[y:y+h, x:x+w]+return clip.fl(f, apply_to = apply_to)diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex 77b0b718..872a5987 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -18,6 +18,7 @@ class FFMPEG_VideoReader:self.fps = infos['video_fps']self.size = infos['video_size']self.duration = infos['video_duration']+ self.ffmpeg_duration = infos['duration']self.nframes = infos['video_nframes']self.infos = infos@@ -82,23 +83,24 @@ class FFMPEG_VideoReader:def read_frame(self):w, h = self.sizenbytes= self.depth*w*h- try:- # Normally, the reader should not read after the last frame.- # if it does, raise an error.- s = self.proc.stdout.read(nbytes)- assert len(s) == nbytes- result = np.fromstring(s,- dtype='uint8').reshape((h, w, len(s)//(w*h)))- #self.proc.stdout.flush()-- except IOError as err:-- self.proc.terminate()- serr = self.proc.stderr.read()- print( "stderr: %s" %serr)- raise err- self.lastread = result+ s = self.proc.stdout.read(nbytes)+ if len(s) != nbytes:++ print( "Warning: in file %s, "%(self.filename)++ "%d bytes wanted but %d bytes read,"%(nbytes, len(s))++ "at frame %d/%d, at time %.02f/%.02f sec. "%(+ self.pos,self.nframes,+ 1.0*self.pos/self.fps,+ self.duration)++ "Using the last valid frame instead.")+ result = self.lastread++ else:++ result = np.fromstring(s, dtype='uint8').\+ reshape((h, w, len(s)//(w*h)))+ self.lastread = resultreturn result@@ -107,23 +109,20 @@ class FFMPEG_VideoReader:Note for coders: getting an arbitrary frame in the video withffmpeg can be painfully slow if some decoding has to be done.- This function tries to avoid fectching arbitrary frames whenever- possible, by moving between adjacent frames.+ This function tries to avoid fectching arbitrary frames+ whenever possible, by moving between adjacent frames."""- if t < 0:- t = 0- elif t > self.duration:- t = self.duration-# these definitely need to be rechecked sometime. Seems to work.- pos = int(np.round(self.fps*t))+1- if pos > self.nframes+1:- raise ValueError("Video file %s has only %d frames but frame"- " #%d asked"%(self.filename, self.nframes, pos))+ #pos = min( self.nframes, int(np.round(self.fps*t))+1 )+ #if pos > self.nframes:+ # raise ValueError(("Video file %s has only %d frames but"+ # " frame #%d asked")%(+ # self.filename, self.nframes, pos))-+ pos = int(np.round(self.fps*t))+1+if pos == self.pos:return self.lastreadelse:@@ -189,14 +188,20 @@ def ffmpeg_parse_infos(filename, print_infos=False):# open the file in a pipe, provoke an error, read output- proc = sp.Popen([FFMPEG_BINARY, "-i", filename, "-"],- bufsize=10**6,+ is_GIF = filename.endswith('.gif')+ cmd = [FFMPEG_BINARY, "-i", filename]+ if is_GIF:+ cmd += ["-f", "null", "/dev/null"]+ proc = sp.Popen(cmd,+ bufsize=10**5,stdout=sp.PIPE,stderr=sp.PIPE)proc.stdout.readline()proc.terminate()infos = proc.stderr.read().decode('utf8')+ del proc+if print_infos:# print the whole info text returned by FFMPEGprint( infos )@@ -210,15 +215,20 @@ def ffmpeg_parse_infos(filename, print_infos=False):# get duration (in seconds)- line = [l for l in lines if 'Duration: ' in l][0]- match = re.search(" [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9]", line)- hms = map(float, line[match.start()+1:match.end()].split(':'))- result['duration'] = cvsecs(*hms)+ try:+ keyword = ('frame=' if is_GIF else 'Duration: ')+ line = [l for l in lines if keyword in l][0]+ match = re.search("[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9]", line)+ hms = map(float, line[match.start()+1:match.end()].split(':'))+ result['duration'] = cvsecs(*hms)+ except:+ raise IOError("Error reading duration in file %s,"%(filename)++ "Text parsed: %s"%infos)# get the output line that speaks about videolines_video = [l for l in lines if ' Video: ' in l]- result['video_found'] = lines_video != []+ result['video_found'] = ( lines_video != [] )if result['video_found']:@@ -238,9 +248,14 @@ def ffmpeg_parse_infos(filename, print_infos=False):match = re.search("( [0-9]*.| )[0-9]* fps", line)result['video_fps'] = float(line[match.start():match.end()].split(' ')[1])- result['video_nframes'] = int(result['duration']*result['video_fps'])- result['video_duration'] = result['video_nframes'] / result['video_fps']-+ result['video_nframes'] = int(result['duration']*result['video_fps'])+1++ result['video_duration'] = result['duration']+ # We could have also recomputed the duration from the number+ # of frames, as follows:+ # >>> result['video_duration'] = result['video_nframes'] / result['video_fps']++lines_audio = [l for l in lines if ' Audio: ' in l]result['audio_found'] = lines_audio != []