Video editing with Python
Fixed bugs, neater code, changed docstrings
Tom Burrows4ce665683f78
diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.pyindex 08a008b1..95f02972 100644--- a/moviepy/audio/AudioClip.py+++ b/moviepy/audio/AudioClip.py@@ -2,12 +2,12 @@ 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,- extensions_dict)+from moviepy.tools import deprecated_version_of, extensions_dictfrom moviepy.Clip import Clipfrom tqdm import tqdm+class AudioClip(Clip):""" Base class for audio clips.@@ -42,7 +42,7 @@ class AudioClip(Clip):"""- def __init__(self, make_frame = None, duration=None):+ def __init__(self, make_frame=None, duration=None):Clip.__init__(self)if make_frame is not None:self.make_frame = make_frame@@ -61,7 +61,7 @@ class AudioClip(Clip):""" Iterator that returns the whole sound array of the clip by chunks"""if fps is None:- fps=self.fps+ fps = self.fpsif chunk_duration is not None:chunksize = int(chunk_duration*fps)@@ -75,9 +75,9 @@ class AudioClip(Clip):for i in range(nchunks):size = pospos[i+1] - pospos[i]assert(size <= chunksize)- tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])- yield self.to_soundarray(tt, nbytes= nbytes, quantize=quantize, fps=fps,- buffersize=chunksize)+ tt = (1.0/fps)*np.arange(pospos[i], pospos[i+1])+ yield self.to_soundarray(tt, nbytes=nbytes, quantize=quantize,+ fps=fps, buffersize=chunksize)if progress_bar:return tqdm(generator(), total=nchunks)@@ -85,7 +85,7 @@ class AudioClip(Clip):return generator()@requires_duration- def to_soundarray(self,tt=None, fps=None, quantize=False, nbytes=2, buffersize=50000):+ def to_soundarray(self, tt=None, fps=None, quantize=False, nbytes=2, buffersize=50000):"""Transforms the sound into an array that can be played by pygameor written in a wav file. See ``AudioClip.preview``.@@ -105,12 +105,12 @@ class AudioClip(Clip):if fps is None:fps = self.fps- stacker = np.vstack if self.nchannels==2 else np.hstack+ stacker = np.vstack if self.nchannels == 2 else np.hstackmax_duration = 1.0 * buffersize / fps- if (tt is None):- if self.duration>max_duration:- return stacker(self.iter_chunks(fps=fps, quantize=quantize, nbytes=2,- chunksize=buffersize))+ if tt is None:+ if self.duration > max_duration:+ return stacker(self.iter_chunks(fps=fps, quantize=quantize,+ nbytes=2, chunksize=buffersize))else:tt = np.arange(0, self.duration, 1.0/fps)"""@@ -126,9 +126,9 @@ class AudioClip(Clip):snd_array = self.get_frame(tt)if quantize:- snd_array = np.maximum(-0.99, np.minimum(0.99,snd_array))- inttype = {1:'int8',2:'int16', 4:'int32'}[nbytes]- snd_array= (2**(8*nbytes-1)*snd_array).astype(inttype)+ snd_array = np.maximum(-0.99, np.minimum(0.99, snd_array))+ inttype = {1: 'int8', 2: 'int16', 4: 'int32'}[nbytes]+ snd_array = (2**(8*nbytes-1)*snd_array).astype(inttype)return snd_array@@ -136,20 +136,15 @@ class AudioClip(Clip):stereo = stereo and (self.nchannels == 2)- maxi = np.array([0,0]) if stereo else 0+ maxi = np.array([0, 0]) if stereo else 0for chunk in self.iter_chunks(chunksize=chunksize, progress_bar=progress_bar):- maxi = np.maximum(maxi,abs(chunk).max(axis=0)) if stereo else max(maxi,abs(chunk).max())+ maxi = np.maximum(maxi, abs(chunk).max(axis=0)) if stereo else max(maxi, abs(chunk).max())return maxi---@requires_duration- def write_audiofile(self,filename, fps=44100, nbytes=2,- buffersize=2000, codec=None,- bitrate=None, ffmpeg_params=None,- write_logfile=False, verbose=True,- progress_bar=True):+ def write_audiofile(self, filename, fps=44100, nbytes=2, buffersize=2000,+ codec=None, bitrate=None, ffmpeg_params=None,+ write_logfile=False, verbose=True, progress_bar=True):""" Writes an audio file from the AudioClip.@@ -162,7 +157,7 @@ class AudioClip(Clip):fpsFrames per second- nbyte+ nbytesSample width (set to 2 for 16-bit sound, 4 for 32-bit sound)codec@@ -198,12 +193,13 @@ class AudioClip(Clip):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_videofile.")+ "with the filename. Provide the 'codec' "+ "parameter in write_videofile.")return ffmpeg_audiowrite(self, filename, fps, nbytes, buffersize,- codec=codec, bitrate=bitrate, write_logfile=write_logfile,- verbose=verbose, ffmpeg_params=ffmpeg_params,+ codec=codec, bitrate=bitrate,+ write_logfile=write_logfile, verbose=verbose,+ ffmpeg_params=ffmpeg_params,progress_bar=progress_bar)@@ -212,6 +208,7 @@ AudioClip.to_audiofile = deprecated_version_of(AudioClip.write_audiofile,'to_audiofile')###+class AudioArrayClip(AudioClip):"""@@ -236,16 +233,15 @@ class AudioArrayClip(AudioClip):self.array = arrayself.fps = fpsself.duration = 1.0 * len(array) / fps--+def make_frame(t):""" complicated, but must be able to handle the case where tis a list of the form sin(t) """if isinstance(t, np.ndarray):array_inds = (self.fps*t).astype(int)- in_array = (array_inds>0) & (array_inds < len(self.array))- result = np.zeros((len(t),2))+ in_array = (array_inds > 0) & (array_inds < len(self.array))+ result = np.zeros((len(t), 2))result[in_array] = self.array[array_inds[in_array]]return resultelse:@@ -290,12 +286,12 @@ class CompositeAudioClip(AudioClip):played_parts = [c.is_playing(t) for c in self.clips]- 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) ]+ 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),self.nchannels))+ if isinstance(t, np.ndarray):+ zero = np.zeros((len(t), self.nchannels))else:zero = np.zeros(self.nchannels)@@ -307,6 +303,6 @@ class CompositeAudioClip(AudioClip):def concatenate_audioclips(clips):durations = [c.duration for c in clips]- tt = np.cumsum([0]+durations) # start times, and end time.- newclips= [c.set_start(t) for c,t in zip(clips, tt)]+ tt = np.cumsum([0]+durations) # start times, and end time.+ newclips = [c.set_start(t) for c, t in zip(clips, tt)]return CompositeAudioClip(newclips).set_duration(tt[-1])diff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.pyindex 8b86b892..34b5e970 100644--- a/moviepy/audio/io/AudioFileClip.py+++ b/moviepy/audio/io/AudioFileClip.py@@ -1,10 +1,10 @@from __future__ import division-import numpy as npfrom moviepy.audio.AudioClip import AudioClipfrom moviepy.audio.io.readers import FFMPEG_AudioReader+class AudioFileClip(AudioClip):"""@@ -17,7 +17,7 @@ class AudioFileClip(AudioClip):Parameters------------- snd+ filenameEither a soundfile name (of any extension supported by ffmpeg)or an array representing a sound. If the soundfile is not a .wav,it will be converted to .wav first, using the ``fps`` and@@ -63,35 +63,32 @@ class AudioFileClip(AudioClip):>>> second_reader = snd.coreader()>>> second_reader.close()>>> snd.close()- >>> with AudioFileClip(mySoundArray,fps=44100) as snd: # from a numeric array+ >>> with AudioFileClip(mySoundArray, fps=44100) as snd: # from a numeric array>>> pass # Close is implicitly performed by context manager."""def __init__(self, filename, buffersize=200000, nbytes=2, fps=44100):-AudioClip.__init__(self)self.filename = filename- self.reader = FFMPEG_AudioReader(filename,fps=fps,nbytes=nbytes,+ self.reader = FFMPEG_AudioReader(filename, fps=fps, nbytes=nbytes,buffersize=buffersize)self.fps = fpsself.duration = self.reader.durationself.end = self.reader.duration--- self.make_frame = lambda t: self.reader.get_frame(t)+ self.buffersize = self.reader.buffersize++ self.make_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 pointto the audio file. Use copy when you have different clipswatching the audio file at different times. """return AudioFileClip(self.filename, self.buffersize)-def close(self):""" Close the internal reader. """if self.reader:diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.pyindex 7ec56be6..334704cf 100644--- a/moviepy/audio/io/ffmpeg_audiowriter.py+++ b/moviepy/audio/io/ffmpeg_audiowriter.py@@ -1,19 +1,15 @@--import numpy as npimport subprocess as sp-from moviepy.compat import PY3, DEVNULL+from moviepy.compat import DEVNULLimport os-from tqdm import tqdmfrom moviepy.config import get_settingfrom moviepy.decorators import requires_durationfrom moviepy.tools import verbose_print-class FFMPEG_AudioWriter:"""A class to write an AudioClip into an audio file.@@ -40,33 +36,30 @@ class FFMPEG_AudioWriter:"""--def __init__(self, filename, fps_input, nbytes=2,- nchannels = 2, codec='libfdk_aac', bitrate=None,+ nchannels=2, codec='libfdk_aac', bitrate=None,input_video=None, logfile=None, ffmpeg_params=None):self.filename = filename- self.codec= codec+ self.codec = codecif logfile is None:- logfile = sp.PIPE-- cmd = ([ get_setting("FFMPEG_BINARY"), '-y',- "-loglevel", "error" if logfile==sp.PIPE else "info",- "-f", 's%dle'%(8*nbytes),- "-acodec",'pcm_s%dle'%(8*nbytes),- '-ar', "%d"%fps_input,- '-ac',"%d"%nchannels,- '-i', '-']- + (['-vn'] if input_video is None else- [ "-i", input_video, '-vcodec', 'copy'])- + ['-acodec', codec]- + ['-ar', "%d"%fps_input]- + ['-strict', '-2'] # needed to support codec 'aac'- + (['-ab',bitrate] if (bitrate is not None) else [])- + (ffmpeg_params if ffmpeg_params else [])- + [ filename ])+ logfile = sp.PIPE++ cmd = ([get_setting("FFMPEG_BINARY"), '-y',+ "-loglevel", "error" if logfile == sp.PIPE else "info",+ "-f", 's%dle' % (8*nbytes),+ "-acodec",'pcm_s%dle' % (8*nbytes),+ '-ar', "%d" % fps_input,+ '-ac', "%d" % nchannels,+ '-i', '-']+ + (['-vn'] if input_video is None else ["-i", input_video, '-vcodec', 'copy'])+ + ['-acodec', codec]+ + ['-ar', "%d"%fps_input]+ + ['-strict', '-2'] # needed to support codec 'aac'+ + (['-ab', bitrate] if (bitrate is not None) else [])+ + (ffmpeg_params if ffmpeg_params else [])+ + [filename])popen_params = {"stdout": DEVNULL,"stderr": logfile,@@ -77,53 +70,54 @@ class FFMPEG_AudioWriter:self.proc = sp.Popen(cmd, **popen_params)-- def write_frames(self,frames_array):+ def write_frames(self, frames_array):try:- if PY3:- self.proc.stdin.write(frames_array.tobytes())- else:- self.proc.stdin.write(frames_array.tostring())+ try:+ self.proc.stdin.write(frames_array.tobytes())+ except NameError:+ 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" + str(ffmpeg_error)))+ error = (str(err) + ("\n\nMoviePy error: FFMPEG encountered "+ "the following error while writing file %s:" % self.filename+ + "\n\n" + str(ffmpeg_error)))if b"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))+ 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 b"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)+ 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 b"encoder setup failed" in ffmpeg_error:+ elif b"encoder setup failed" in ffmpeg_error:- error = error+("\n\nThe audio export "- "failed, possily because the bitrate you specified "- "was two high or too low for the video codec.")+ 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)."))- 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):if self.proc:self.proc.stdin.close()@@ -148,11 +142,10 @@ class FFMPEG_AudioWriter:self.close()-@requires_durationdef ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,codec='libvorbis', bitrate=None,- write_logfile = False, verbose=True,+ write_logfile=False, verbose=True,ffmpeg_params=None, progress_bar=True):"""A function that wraps the FFMPEG_AudioWriter to write an AudioClip