Skip to content

Video editing with Python

Included ffmpeg_params. Hope PEP8-related conflicts didn't break anything

Zulko46eb85d0a0d1
diff --cc moviepy/audio/io/ffmpeg_audiowriter.py
index 45bbb477,84298420..604dff72
--- a/moviepy/audio/io/ffmpeg_audiowriter.py
+++ b/moviepy/audio/io/ffmpeg_audiowriter.py
@@@ -39,15 -39,15 +39,15 @@@ class FFMPEG_AudioWriter
bitrate:
A string indicating the bitrate of the final video. Only
relevant for codecs which accept a bitrate.
-
+
"""
-
-
-
+
+
+
def __init__(self, filename, fps_input, nbytes=2,
nchannels = 2, codec='libfdk_aac', bitrate=None,
-- input_video=None,logfile=None):
-
++ input_video=None, logfile=None):
+
self.filename = filename
self.codec= codec
diff --cc moviepy/config_defaults.py
index 06226057,00000000..aedc058b
mode 100644,000000..100644
--- a/moviepy/config_defaults.py
+++ b/moviepy/config_defaults.py
@@@ -1,42 -1,0 +1,42 @@@
+"""
+Configuration MoviePy
+
+
+This file enables you to specify a configuration for MoviePy. In
+particular you can enter the path to the FFMPEG and ImageMagick
+binaries.
+
+Note that at any time in a script you can change the value of these
+variables as follows:
+
+>>> import moviepy.config as cf
- >>> cf.change_setting({"FFMPEG_BINARY": "some/new/path/to/ffmpeg"})
++>>> cf.change_settings({"FFMPEG_BINARY": "some/new/path/to/ffmpeg"})
+>>> print( cf.get_setting("FFMPEG_BINARY") ) # prints the current setting
+
+Instructions
+--------------
+
+
+FFMPEG_BINARY
+ Normally you can leave this one to its default ('auto-detect') and MoviePy
+ will detect automatically the right name, which will be either
+ 'ffmpeg' (on linux) or 'ffmpeg.exe' (on windows). If you want to
+ use a binary at a special location on you disk, enter it like that:
+
+ FFMPEG_BINARY = r"path/to/ffmpeg" # on linux
+ FFMPEG_BINARY = r"path\to\ffmpeg.exe" # on windows
+
+ Warning: the 'r' before the path is important, especially on Windows.
+
+
+IMAGEMAGICK_BINARY
+ For linux users, 'convert' should be fine.
+ For Windows users, you must specify the path to the ImageMagick
+ 'convert' binary. For instance:
+
+ IMAGEMAGICK_BINARY = r"C:\Program Files\ImageMagick-6.8.8-Q16\convert.exe"
+
+"""
+
+FFMPEG_BINARY = 'auto-detect'
+IMAGEMAGICK_BINARY = 'convert'
diff --cc moviepy/video/VideoClip.py
index c5af1558,1c56bbeb..6bf433d8
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@@ -22,31 -19,20 +19,28 @@@ from .io.ffmpeg_writer import ffmpeg_wr
from .io.ffmpeg_reader import ffmpeg_read_image
from .io.ffmpeg_tools import ffmpeg_merge_video_audio
from .io.gif_writers import write_gif, write_gif_with_tempfiles
-
from .tools.drawing import blit
-
from ..Clip import Clip
-from ..conf import FFMPEG_BINARY, IMAGEMAGICK_BINARY
+from ..config import get_setting
+
from ..tools import (subprocess_call,
verbose_print,
is_string,
deprecated_version_of,
extensions_dict, find_extension)
+
- from ..decorators import (apply_to_mask,
- requires_duration,
- outplace,
- add_mask_if_none,
- convert_to_seconds)
-
+ from ..decorators import (apply_to_mask,
+ requires_duration,
+ outplace,
+ add_mask_if_none,
+ convert_to_seconds)
+import os
+try:
+ from subprocess import DEVNULL # py3k
+except ImportError:
+ DEVNULL = open(os.devnull, 'wb')
+
class VideoClip(Clip):
"""Base class for video clips.
@@@ -146,13 -130,14 +138,15 @@@
@requires_duration
def write_videofile(self, filename, fps=24, codec=None,
- bitrate=None, audio=True, audio_fps=44100,
- preset="medium",
- audio_nbytes = 4, audio_codec= None,
- audio_bitrate = None, audio_bufsize = 2000,
- temp_audiofile=None,
- rewrite_audio = True, remove_temp = True,
- write_logfile=False, verbose = True, threads=None):
+ bitrate=None, audio=True, audio_fps=44100,
+ preset="medium",
+ audio_nbytes=4, audio_codec=None,
+ audio_bitrate=None, audio_bufsize=2000,
+ temp_audiofile=None,
+ rewrite_audio=True, remove_temp=True,
+ write_logfile=False, verbose=True,
- ffmpeg_params=None):
++ threads=None, ffmpeg_params=None):
++
"""Write the clip to a videofile.
Parameters
@@@ -234,6 -219,6 +228,14 @@@
size of the video file. So choose ultrafast when you are in a
hurry and file size does not matter.
++ threads
++ Number of threads to use for ffmpeg. Can speed up the writing of
++ the video on multicore computers
++
++ ffmpeg_params
++ Any additional ffmpeg parameters you would like to pass, as a list
++ of terms, like ['-option1', 'value1', '-option2', 'value2']
++
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
@@@ -254,20 -239,20 +256,20 @@@
ext = ext[1:].lower()
if codec is None:
- try:
- codec = extensions_dict[ext]['codec'][0]
- except KeyError:
- raise ValueError("MoviePy couldn't find the codec associated "
- "with the filename. Provide the 'codec' parameter in "
- "write_fideofile.")
++
+ try:
+ codec = extensions_dict[ext]['codec'][0]
+ except KeyError:
+ raise ValueError("MoviePy couldn't find the codec associated "
+ "with the filename. Provide the 'codec' parameter in "
+ "write_fideofile.")
if audio_codec is None:
if (ext in ['ogv', 'webm']):
audio_codec = 'libvorbis'
else:
audio_codec = 'libmp3lame'
--
-- if audio_codec == 'raw16':
++ elif audio_codec == 'raw16':
audio_codec = 'pcm_s16le'
elif audio_codec == 'raw32':
audio_codec = 'pcm_s32le'
@@@ -317,8 -302,9 +319,9 @@@
bitrate=bitrate,
preset=preset,
write_logfile=write_logfile,
- audiofile=audiofile,
- verbose=verbose,
+ audiofile = audiofile,
- verbose=verbose, threads=threads)
++ verbose=verbose, threads=threads,
+ ffmpeg_params=ffmpeg_params)
if remove_temp and make_audio:
os.remove(audiofile)
@@@ -383,11 -369,10 +386,11 @@@
return filenames
+
@requires_duration
- def write_gif(self, filename, fps=None, program= 'ImageMagick',
- opt="OptimizeTransparency", fuzz=1, verbose=True,
- loop=0, dispose=False, colors=None, tempfiles=False):
+ def write_gif(self, filename, fps=None, program='ImageMagick',
+ opt="OptimizeTransparency", fuzz=1, verbose=True,
+ loop=0, dispose=False, colors=None, tempfiles=False):
""" Write the VideoClip to a GIF file.
Converts a VideoClip into an animated GIF using ImageMagick
@@@ -914,11 -882,12 +900,9 @@@ class ImageClip(VideoClip)
VideoClip.to_videofile = deprecated_version_of(VideoClip.write_videofile,
'to_videofile')
VideoClip.to_gif = deprecated_version_of(VideoClip.write_gif, 'to_gif')
-VideoClip.to_images_sequence = deprecated_version_of(
- VideoClip.write_images_sequence,
- 'to_images_sequence')
-
-###
+VideoClip.to_images_sequence = deprecated_version_of(VideoClip.write_images_sequence,
+ 'to_images_sequence')
- ###
-
class ColorClip(ImageClip):
""" An ImageClip showing just one color.
@@@ -1040,24 -1006,24 +1021,24 @@@ class TextClip(ImageClip)
size = ('' if size[0] is None else str(size[0]),
'' if size[1] is None else str(size[1]))
- cmd = ( [IMAGEMAGICK_BINARY,
- "-background", bg_color,
- "-fill", color,
- "-font", font])
+ cmd = ( [get_setting("IMAGEMAGICK_BINARY"),
+ "-background", bg_color,
+ "-fill", color,
+ "-font", font])
- if fontsize !=None:
- cmd += ["-pointsize", "%d"%fontsize]
+ if fontsize != None:
+ cmd += ["-pointsize", "%d" % fontsize]
if kerning != None:
- cmd += ["-kerning", "%0.1f"%kerning]
+ cmd += ["-kerning", "%0.1f" % kerning]
if stroke_color != None:
cmd += ["-stroke", stroke_color, "-strokewidth",
- "%.01f"%stroke_width]
+ "%.01f" % stroke_width]
if size != None:
- cmd += ["-size", "%sx%s"%(size[0], size[1])]
+ cmd += ["-size", "%sx%s" % (size[0], size[1])]
if align != None:
- cmd += ["-gravity",align]
+ cmd += ["-gravity", align]
if interline != None:
- cmd += ["-interline-spacing", "%d"%interline]
+ cmd += ["-interline-spacing", "%d" % interline]
if tempfilename is None:
tempfile_fd, tempfilename = tempfile.mkstemp(suffix='.png')
diff --cc moviepy/video/io/ffmpeg_writer.py
index 85f5e725,b53b280e..eb770aca
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@@ -3,34 -3,31 +3,28 @@@ On the long term this will implement se
out of VideoClips
"""
- import numpy as np
import subprocess as sp
--
+import os
+ import numpy as np
+
-
try:
- from subprocess import DEVNULL # py3k
+ from subprocess import DEVNULL # py3k
except ImportError:
- import os
-
DEVNULL = open(os.devnull, 'wb')
-
-
- from tqdm import tqdm
-
-from moviepy.conf import FFMPEG_BINARY
+from moviepy.config import get_setting
from moviepy.tools import verbose_print
-
-
class FFMPEG_VideoWriter:
""" A class for FFMPEG-based video writing.
-
+
A class to write videos using ffmpeg. ffmpeg will write in a large
choice of formats.
-
+
Parameters
-----------
-
+
filename
Any filename like 'video.mp4' etc. but if you want to avoid
complications it is recommended to use the generic extension
@@@ -53,10 -50,11 +47,11 @@@
is used. If the video dimensions are not both even (e.g. 720x405)
another pixel format is used, and this can cause problem in some
video readers.
-
+
audiofile
- Optional: The name of an audio file that will be incorporated to the video.
+ Optional: The name of an audio file that will be incorporated
+ to the video.
-
+
preset
Sets the time that FFMPEG will take to compress the video. The slower,
the better the compression rate. Possibilities are: ultrafast,superfast,
@@@ -69,59 -68,64 +65,70 @@@
withmask
Boolean. Set to ``True`` if there is a mask in the video to be
encoded.
-
- """
+ """
-
-
def __init__(self, filename, size, fps, codec="libx264", audiofile=None,
preset="medium", bitrate=None, withmask=False,
- logfile=None, threads=None):
- logfile=None, ffmpeg_params=None):
++ logfile=None, threads=None, ffmpeg_params=None):
if logfile is None:
- logfile = sp.PIPE
+ logfile = sp.PIPE
self.filename = filename
self.codec = codec
self.ext = self.filename.split(".")[-1]
- cmd = (
- [ get_setting("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']
- + (["-i", audiofile, "-acodec", "copy"] if (audiofile is not None) else [])
- +['-vcodec', codec,
- '-preset', preset]
- + (['-b:v', bitrate] if (bitrate is not None) else [])
- + (["-threads", str(threads)] if threads is not None else [])
- # http://trac.ffmpeg.org/ticket/658
- + (['-pix_fmt', 'yuv420p']
- if ((codec == 'libx264') and
- (size[0]%2 == 0) and
- (size[1]%2 == 0))
-
- else [])
- + [ '-r', "%.02f"%fps, filename ]
- )
+ # order is important
+ cmd = [
- FFMPEG_BINARY,
++ get_setting("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',
+ ]
+ if audiofile is not None:
+ cmd.extend([
+ '-i', audiofile,
+ '-acodec', 'copy'
+ ])
+ cmd.extend([
+ '-vcodec', codec,
+ '-preset', preset,
+ ])
+ if ffmpeg_params is not None:
+ cmd.extend(ffmpeg_params)
+ if bitrate is not None:
+ cmd.extend([
+ '-b', bitrate
+ ])
+ if ((codec == 'libx264') and
+ (size[0] % 2 == 0) and
+ (size[1] % 2 == 0)):
+ cmd.extend([
+ '-pix_fmt', 'yuv420p'
+ ])
+ cmd.extend([
+ filename
+ ])
- self.proc = sp.Popen(cmd, stdin=sp.PIPE,
- stderr=logfile,
- stdout=DEVNULL)
+ popen_params = {"stdout": DEVNULL,
+ "stderr": logfile,
+ "stdin": sp.PIPE}
+
+ # This was added so that no extra unwanted window opens on windows
+ # when the child process is created
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ self.proc = sp.Popen(cmd, **popen_params)
- def write_frame(self,img_array):
+ def write_frame(self, img_array):
""" Writes one frame in the file."""
try:
self.proc.stdin.write(img_array.tostring())
@@@ -142,24 -147,24 +149,25 @@@
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 write_videofile. This would be 'libx264' "
- "or 'mpeg4' for mp4, 'libtheora' for ogv, 'libvpx for webm. "
- "Another possible reason is that the audio codec was not "
- "compatible with the video codec. For instance the video "
- "extensions 'ogv' and 'webm' only allow 'libvorbis' "
- "(default) as a video codec."
- ) % (self.codec, self.ext)
+ 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 write_videofile. This would be 'libx264' "
+ "or 'mpeg4' for mp4, 'libtheora' for ogv, 'libvpx for webm. "
+ "Another possible reason is that the audio codec was not "
+ "compatible with the video codec. For instance the video "
+ "extensions 'ogv' and 'webm' only allow 'libvorbis' (default) as a"
+ "video codec."
+ )%(self.codec, self.ext)
+
+ elif "encoder setup failed":
- elif "encoder setup failed":
+ error = error+("\n\nThe video export "
+ "failed, possibly because the bitrate you specified "
+ "was too high or too low for the video codec.")
- error = error + ("\n\nThe video export "
- "failed, possibly because the bitrate you specified "
- "was too high or too low for the video codec.")
+
raise IOError(error)
def close(self):
@@@ -170,28 -175,26 +178,28 @@@
del self.proc
-
def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,
preset="medium", withmask=False, write_logfile=False,
- audiofile=None, verbose=True, threads=None):
- audiofile=None, verbose=True, ffmpeg_params=None):
++ audiofile=None, verbose=True, threads=None, ffmpeg_params=None):
+
if write_logfile:
logfile = open(filename + ".log", 'w+')
else:
logfile = 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, audiofile=audiofile,
+ verbose_print(verbose, "\nWriting video into %s\n"%filename)
+ writer = FFMPEG_VideoWriter(filename, clip.size, fps, codec = codec,
+ preset=preset, bitrate=bitrate, logfile=logfile,
- audiofile=audiofile, threads=threads)
++ audiofile=audiofile, threads=threads,
+ ffmpeg_params=ffmpeg_params)
- for t, frame in clip.iter_frames(progress_bar=True, with_times=True,
- fps=fps):
+ nframes = int(clip.duration*fps)
+
+ for t,frame in clip.iter_frames(progress_bar=True, with_times=True,
+ fps=fps):
if withmask:
- mask = 255 * clip.mask.get_frame(t)
- frame = np.dstack([frame, mask])
+ mask = 255*clip.mask.get_frame(t)
+ frame = np.dstack([frame,mask])
writer.write_frame(frame.astype("uint8"))
@@@ -207,35 -210,24 +215,31 @@@ def ffmpeg_write_image(filename, image
""" Writes an image (HxWx3 or HxWx4 numpy array) to a file, using
ffmpeg. """
-
- cmd = [FFMPEG_BINARY, '-y',
- '-s', "%dx%d" % (image.shape[:2][::-1]),
+ cmd = [ get_setting("FFMPEG_BINARY"), '-y',
+ '-s', "%dx%d"%(image.shape[:2][::-1]),
"-f", 'rawvideo',
'-pix_fmt', "rgba" if (image.shape[2] == 4) else "rgb24",
- '-i', '-', filename]
+ '-i','-', filename]
if logfile:
log_file = open(filename + ".log", 'w+')
else:
log_file = sp.PIPE
-
- proc = sp.Popen(cmd, stdin=sp.PIPE, stderr=log_file)
- proc.communicate(image.tostring()) # proc.wait()
+ popen_params = {"stdout": DEVNULL,
+ "stderr": log_file,
+ "stdin": sp.PIPE}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ proc = sp.Popen(cmd, **popen_params)
- proc.communicate(image.tostring()) # proc.wait()
++ proc.communicate(image.tostring())
if proc.returncode:
- err = "\n".join(["MoviePy running : %s"%cmd,
- "WARNING: this command returned an error:",
- proc.stderr.read().decode('utf8')])
+ err = "\n".join(["MoviePy running : %s" % cmd,
+ "WARNING: this command returned an error:",
+ proc.stderr.read().decode('utf8')])
raise IOError(err)
-
-
del proc