Video editing with Python
Better error reports and better doctstrings for ffmpeg-related functions. Also: now mp3 is the default export for audio.
Zulkoe64a7fb86b83
diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex 07ceef8b..431b185d 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -92,16 +92,44 @@ class AudioClip(Clip):def to_audiofile(self,filename, fps=44100, nbytes=2,buffersize=2000, codec='libvorbis',bitrate=None, write_logfile=False, verbose=True):- """- codecs = { 'libmp3lame': 'mp3',- 'libvorbis':'ogg',- 'libfdk_aac':'m4a',- 'pcm_s16le':'wav',- 'pcm_s32le': 'wav'}+ """ Writes an audio file from the AudioClip.+++ Parameters+ -----------++ filename+ Name of the output file++ fps+ Frames per second++ nbyte+ 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',+ 'pcm_s16le' for 16-bit wav and 'pcm_s32le' for 32-bit wav.++ bitrate+ Audio bitrate, given as a string like '50k', '500k', '3000k'.+ Will determine the size and quality of the output file.+ Note that it mainly an indicative goal, the bitrate won't+ necessarily be the this in the output file.++ write_logfile+ If true, produces a detailed logfile named filename + '.log'+ when writing the file++ verbose+ If True, displays informations+"""return ffmpeg_audiowrite(self, filename, fps, nbytes, buffersize,- codec=codec, bitrate=bitrate, write_logfile=write_logfile, verbose=verbose)+ codec=codec, bitrate=bitrate, write_logfile=write_logfile,+ verbose=verbose)class AudioArrayClip(AudioClip):diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.pyindex fa1fff06..7bb72d5c 100644--- a/moviepy/audio/io/ffmpeg_audiowriter.py+++ b/moviepy/audio/io/ffmpeg_audiowriter.py@@ -49,12 +49,13 @@ class FFMPEG_AudioWriter:input_video=None,logfile=None):self.filename = filename+ self.codec= codecif logfile is None:- logfile = DEVNULL+ logfile = sp.PIPEcmd = ([ FFMPEG_BINARY, '-y',- "-loglevel", "panic" if logfile==DEVNULL else "info",+ "-loglevel", "error" if logfile==sp.PIPE else "info","-f", 's%dle'%(8*nbytes),"-acodec",'pcm_s%dle'%(8*nbytes),'-ar', "%d"%fps_input,@@ -75,13 +76,51 @@ class FFMPEG_AudioWriter:def write_frames(self,frames_array):- self.proc.stdin.write(frames_array.tostring())+ try:+ self.proc.stdin.write(frames_array.tostring())+ except IOError as err:+ ffmpeg_error = self.proc.stderr.read()+ error = (str(err)+ ("\n\nMoviePy error: FFMPEG encountered "+ "the following error while writing file %s:"%self.filename+ + "\n\n"+ffmpeg_error))++ if "Unknown encoder" in ffmpeg_error:++ error = (error+("\n\nThe audio export failed because "+ "FFMPEG didn't find the specified codec for audio "+ "encoding (%s). Please install this codec or "+ "change the codec when calling to_videofile or "+ "to_audiofile. For instance for mp3:\n"+ " >>> to_videofile('myvid.mp4', audio_codec='libmp3lame')"+ )%(self.codec))++ elif "incorrect codec parameters ?" in ffmpeg_error:++ error = error+("\n\nThe audio export "+ "failed, possibly because the codec specified for "+ "the video (%s) is not compatible with the given "+ "extension (%s). Please specify a valid 'codec' "+ "argument in to_videofile. This would be 'libmp3lame' "+ "for mp3, 'libvorbis' for ogg...")%(self.codec, self.ext)++ elif "encoder setup failed":++ error = error+("\n\nThe audio export "+ "failed, possily because the bitrate you specified "+ "was two high or too low for the video codec.")++ else:++ error = error+("\n\nIn case it helps, make sure you are "+ "using a recent version of FFMPEG (the versions in the "+ "Ubuntu/Debian repos are deprecated).")+ raise IOError(error)+def close(self):self.proc.stdin.close()- #self.proc.stderr.close()- #self.proc.stdout.close()+ self.proc.stderr.close()self.proc.wait()del self.proc@@ -102,7 +141,7 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,if write_logfile:logfile = open(filename + ".log", 'w+')else:- logfile = DEVNULL+ logfile = Noneverbose_print("Writing audio in %s\n"%filename)diff --git a/moviepy/tools.py b/moviepy/tools.pyindex 8160bd1e..ff5fd6fd 100644--- a/moviepy/tools.py+++ b/moviepy/tools.py@@ -32,7 +32,7 @@ def subprocess_call(cmd, verbose=True, errorprint=True):sys_write_flush( "\nMoviePy: WARNING !\n"" The following command returned an error:\n")sys_write_flush( err.decode('utf8'))- raise IOError+ raise IOError(err.decode('utf8'))else:verboseprint( "\n... command successful.\n")diff --git a/moviepy/version.py b/moviepy/version.pyindex 98923f34..e8329ec7 100644--- a/moviepy/version.py+++ b/moviepy/version.py@@ -1 +1 @@-__version__ = "0.2.1.8.01"+__version__ = "0.2.1.8.02"diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.pyindex c84a46a4..da77cc21 100644--- a/moviepy/video/VideoClip.py+++ b/moviepy/video/VideoClip.py@@ -124,7 +124,7 @@ class VideoClip(Clip):def to_videofile(self, filename, fps=24, codec='libx264',bitrate=None, audio=True, audio_fps=44100,- audio_nbytes = 4, audio_codec= 'libvorbis',+ audio_nbytes = 4, audio_codec= 'libmp3lame',audio_bitrate = None, audio_bufsize = 2000,temp_audiofile=None,rewrite_audio = True, remove_temp = True,@@ -144,17 +144,30 @@ class VideoClip(Clip):codecCodec to use for image encoding. Can be any codec supported- by ffmpeg.+ by ffmpeg, but the extension of the output filename must be+ set accordingly.- ``'rawvideo'``, ``'png'`` will produce a raw video,- of perfect quality, but possibly very huge size. 'png' is- is lossless and produces smaller files than 'rawvideo'.+ ``'libx264'`` (default codec, use file extension ``.mp4``)+ makes well-compressed videos (quality tunable using 'bitrate').- ``'mpeg4'`` produces nice quality, very well compressed- videos.- ``'libx264'`` (default) is a little better than 'mpeg4',- a little heavier.+ ``'mpeg4'`` (use file extension ``.mp4``) can be an alternative+ to ``'libx264'``, and produces higher quality videos by default.+++ ``'rawvideo'`` (use file extension ``.avi``) will produce+ a video of perfect quality, of possibly very huge size.++ ``png`` (use file extension ``.avi``) will produce a video+ of perfect quality, of smaller size than with ``rawvideo``++ ``'libvorbis'`` (use file extension ``.ogv``) is a nice video+ format, which is completely free/ open source. However not+ everyone has the codecs installed by default on their machine.++ ``'libvpx'`` (use file extension ``.webm``) is tiny a video+ format well indicated for web videos (with HTML5). Open source.+audioEither ``True``, ``False``, or a file name.@@ -170,6 +183,22 @@ class VideoClip(Clip):the name of the temporary audiofile to be generated andincorporated in the the movie, if any.+ audio_codec+ 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.++ audio_bitrate+ Audio bitrate, given as a string like '50k', '500k', '3000k'.+ Will determine the size/quality of audio in the output file.+ Note that it mainly an indicative goal, the bitrate won't+ necessarily be the this in the final file.++ write_logfile+ If true, will write log files for the audio and the video.+ These will be files ending with '.log' with the name of the+ output file in them.+"""name, ext = os.path.splitext(os.path.basename(filename))@@ -213,7 +242,7 @@ class VideoClip(Clip):audio_ext = D_ext[audio_codec]else:raise ValueError('audio_codec for file'- '%d unkown !'%filename)+ '%s unkown !'%filename)temp_audiofile = (name+Clip._TEMP_FILES_PREFIX +"to_videofile_SOUND.%s"%audio_ext)@@ -445,8 +474,22 @@ class VideoClip(Clip):'-r',str(fps),filename]+ try:++ subprocess_call( cmd, verbose = verbose )++ except IOError as err:- subprocess_call( cmd, verbose = verbose )+ error = ("MoviePy Error: creation of %s failed because "+ "of the following error:\n\n%s.\n\n."%(filename, str(err)))++ if program == "ImageMagick":+ error = error + ("This can be due to the fact that "+ "ImageMagick is not installed on your computer, or "+ "(for Windows users) that you didn't specify the "+ "path to the ImageMagick binary in file conf.py." )++ raise IOError(error)for f in tempfiles:os.remove(f)diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.pyindex 7c086c18..4bb35fce 100644--- a/moviepy/video/io/ffmpeg_reader.py+++ b/moviepy/video/io/ffmpeg_reader.py@@ -33,7 +33,6 @@ class FFMPEG_VideoReader:w, h = self.sizebufsize = self.depth * w * h + 100- self.proc= Noneself.bufsize= bufsizeself.initialize()@@ -94,6 +93,16 @@ class FFMPEG_VideoReader:1.0*self.pos/self.fps,self.duration)+"Using the last valid frame instead.")++ if not hasattr(self, 'lastread'):+ raise IOError(("MoviePy error: failed to read the first frame of "+ "video file %s. That might mean that the file is "+ "corrupted. That may also mean that you are using "+ "a deprecated version of FFMPEG. On Ubuntu/Debian "+ "for instance the version in the repos is deprecated. "+ "Please update to a recent version from the website.")%(+ self.filename))+result = self.lastreadelse:@@ -134,7 +143,7 @@ class FFMPEG_VideoReader:return resultdef close(self):- if self.proc is not None:+ if hasattr(self,'proc'):self.proc.terminate()self.proc.stdout.close()self.proc.stderr.close()@@ -142,7 +151,8 @@ class FFMPEG_VideoReader:def __del__(self):self.close()- del self.lastread+ if hasattr(self,'lastread'):+ del self.lastread@@ -208,7 +218,9 @@ def ffmpeg_parse_infos(filename, print_infos=False):lines = infos.splitlines()if "No such file or directory" in lines[-1]:- raise IOError("%s not found ! Wrong path ?"%filename)+ raise IOError(("MoviePy error: the file %s could not be found !\n"+ "Please check that you entered the correct "+ "path.")%filename)result = dict()@@ -221,8 +233,9 @@ def ffmpeg_parse_infos(filename, print_infos=False):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)+ raise IOError(("MoviePy error: failed to read the duration of file %s.\n"+ "Here are the file infos returned by ffmpeg:\n\n%s")%(+ filename, infos))# get the output line that speaks about videolines_video = [l for l in lines if ' Video: ' in l]@@ -239,7 +252,7 @@ def ffmpeg_parse_infos(filename, print_infos=False):result['video_size'] = s- # get the frame rate+ # get the frame rate. Sometimes it's 'tbr', sometimes 'fps'...try:match = re.search("( [0-9]*.| )[0-9]* tbr", line)result['video_fps'] = float(line[match.start():match.end()].split(' ')[1])diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.pyindex 6a7932eb..fc0f25b3 100644--- a/moviepy/video/io/ffmpeg_writer.py+++ b/moviepy/video/io/ffmpeg_writer.py@@ -71,13 +71,15 @@ class FFMPEG_VideoWriter:bitrate=None, withmask=False, logfile=None):if logfile is None:- logfile = DEVNULL+ logfile = sp.PIPEself.filename = filename+ self.codec = codec+ self.ext = self.filename.split(".")[-1]cmd = ([ FFMPEG_BINARY, '-y',- "-loglevel", "panic" if logfile==DEVNULL else "info",+ "-loglevel", "error" if logfile==sp.PIPE else "info","-f", 'rawvideo',"-vcodec","rawvideo",'-s', "%dx%d"%(size[0],size[1]),@@ -105,13 +107,43 @@ class FFMPEG_VideoWriter:def write_frame(self,img_array):""" Writes 1 frame in the file ! """- self.proc.stdin.write(img_array.tostring())- #self.proc.stdin.flush()+ try:+ self.proc.stdin.write(img_array.tostring())+ except IOError as err:+ ffmpeg_error = self.proc.stderr.read()+ error = (str(err)+ ("\n\nMoviePy error: FFMPEG encountered "+ "the following error while writing file %s:"%self.filename+ + "\n\n"+ffmpeg_error))++ if "Unknown encoder" in ffmpeg_error:++ error = error+("\n\nThe video export "+ "failed because FFMPEG didn't find the specified "+ "codec for video encoding (%s). Please install "+ "this codec or change the codec when calling "+ "to_videofile. For instance:\n"+ " >>> to_videofile('myvid.webm', codec='libvpx')")%(self.codec)++ elif "incorrect codec parameters ?" in ffmpeg_error:++ error = error+("\n\nThe video export "+ "failed, possibly because the codec specified for "+ "the video (%s) is not compatible with the given "+ "extension (%s). Please specify a valid 'codec' "+ "argument in to_videofile. This would be 'libx264' "+ "or 'mpeg4' for mp4, 'libtheora' for ogv, 'libvpx' "+ "for webm.")%(self.codec, self.ext)++ elif "encoder setup failed":++ error = error+("\n\nThe video export "+ "failed, possibly because the bitrate you specified "+ "was two high or too low for the video codec.")++ raise IOError(error)def close(self):self.proc.stdin.close()- #self.proc.stdout.close()- #self.proc.stderr.close()self.proc.wait()del self.proc@@ -125,7 +157,7 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,if write_logfile:logfile = open(filename + ".log", 'w+')else:- logfile = DEVNULL+ logfile = Noneverbose_print("\nWriting video into %s\n"%filename)@@ -164,7 +196,7 @@ def ffmpeg_write_image(filename, image, logfile=False):if logfile:log_file = open(filename + ".log", 'w+')else:- log_file = DEVNULL+ log_file = sp.PIPEproc = sp.Popen( cmd, stdin=sp.PIPE, stderr=log_file)