Skip to content

Video editing with Python

make compatible with cx_freeze in gui32 mode

Florian Zierer05b4f38109a0
diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.py
index 84298420..b7f65cc2 100644
--- a/moviepy/audio/io/ffmpeg_audiowriter.py
+++ b/moviepy/audio/io/ffmpeg_audiowriter.py
@@ -19,35 +19,35 @@ from moviepy.tools import verbose_print
class FFMPEG_AudioWriter:
"""
A class to write an AudioClip into an audio file.
-
+
Parameters
------------
-
+
filename
Name of any video or audio file, like ``video.mp4`` or ``sound.wav`` etc.
-
+
size
Size (width,height) in pixels of the output video.
-
+
fps_input
Frames per second of the input audio (given by the AUdioClip being
written down).
-
+
codec
Name of the ffmpeg codec to use for the output.
-
+
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):
-
+
self.filename = filename
self.codec= codec
@@ -68,13 +68,17 @@ class FFMPEG_AudioWriter:
+ ['-strict', '-2'] # needed to support codec 'aac'
+ (['-ab',bitrate] if (bitrate!=None) else [])
+ [ filename ])
-
- self.proc = sp.Popen(cmd, stdin=sp.PIPE,
- stderr=logfile,
- stdout=DEVNULL)
+ popen_params = {"stdout": DEVNULL,
+ "stderr": logfile,
+ "stdin": sp.PIPE}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ self.proc = sp.Popen(cmd, **popen_params)
+
-
def write_frames(self,frames_array):
try:
self.proc.stdin.write(frames_array.tostring())
@@ -95,7 +99,7 @@ class FFMPEG_AudioWriter:
)%(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 "
@@ -108,7 +112,7 @@ class FFMPEG_AudioWriter:
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 "
@@ -116,18 +120,18 @@ class FFMPEG_AudioWriter:
"Ubuntu/Debian repos are deprecated).")
raise IOError(error)
-
-
+
+
def close(self):
self.proc.stdin.close()
if self.proc.stderr is not None:
self.proc.stderr.close()
self.proc.wait()
del self.proc
-
-
-
-@requires_duration
+
+
+
+@requires_duration
def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
codec='libvorbis', bitrate=None,
write_logfile = False, verbose=True):
@@ -140,22 +144,22 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
logfile = open(filename + ".log", 'w+')
else:
logfile = None
-
+
verbose_print(verbose, "Writing audio in %s\n"%filename)
-
+
writer = FFMPEG_AudioWriter(filename, fps, nbytes, clip.nchannels,
codec=codec, bitrate=bitrate,
logfile=logfile)
-
+
totalsize = int(fps*clip.duration)
-
+
if (totalsize % buffersize == 0):
nchunks = totalsize // buffersize
else:
nchunks = totalsize // buffersize + 1
-
+
pospos = list(range(0, totalsize, buffersize))+[totalsize]
-
+
for i in tqdm(range(nchunks)):
tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])
sndarray = clip.to_soundarray(tt, nbytes= nbytes)
@@ -163,7 +167,7 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
writer.close()
-
+
if write_logfile:
logfile.close()
diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.py
index 15afb96c..83e65d80 100644
--- a/moviepy/audio/io/readers.py
+++ b/moviepy/audio/io/readers.py
@@ -7,40 +7,45 @@ from moviepy.tools import cvsecs
from moviepy.video.io.ffmpeg_reader import ffmpeg_parse_infos
from moviepy.conf import FFMPEG_BINARY
-
+try:
+ from subprocess import DEVNULL # py3k
+except ImportError:
+ import os
+ DEVNULL = open(os.devnull, 'wb')
+
class FFMPEG_AudioReader:
"""
A class to read the audio in either video files or audio files
using ffmpeg. ffmpeg will read any audio and transform them into
raw data.
-
+
Parameters
------------
-
+
filename
Name of any video or audio file, like ``video.mp4`` or
``sound.wav`` etc.
-
+
buffersize
The size of the buffer to use. Should be bigger than the buffer
used by ``to_audiofile``
-
+
print_infos
Print the ffmpeg infos on the file being read (for debugging)
-
+
fps
Desired frames per second in the decoded signal that will be
received from ffmpeg
-
+
nbytes
Desired number of bytes (1,2,4) in the signal that will be
received from ffmpeg
-
+
"""
-
+
def __init__(self, filename, buffersize, print_infos=False,
fps=44100, nbytes=2, nchannels=2):
-
+
self.filename = filename
self.nbytes = nbytes
self.fps = fps
@@ -55,21 +60,21 @@ class FFMPEG_AudioReader:
self.duration = infos['duration']
self.infos = infos
self.proc = None
-
+
self.nframes = int(self.fps * self.duration)
self.buffersize= min( self.nframes+1, buffersize )
self.buffer= None
self.buffer_startframe = 1
self.initialize()
self.buffer_around(1)
-
-
-
+
+
+
def initialize(self, starttime = 0):
""" Opens the file, creates the pipe. """
-
+
self.close_proc() # if any
-
+
if starttime !=0 :
offset = min(1,starttime)
i_arg = ["-ss", "%.05f"%(starttime-offset),
@@ -77,29 +82,36 @@ class FFMPEG_AudioReader:
"-ss", "%.05f"%offset]
else:
i_arg = [ '-i', self.filename, '-vn']
-
-
- cmd = ([FFMPEG_BINARY] + i_arg +
+
+
+ cmd = ([FFMPEG_BINARY] + i_arg +
[ '-loglevel', 'error',
'-f', self.f,
'-acodec', self.acodec,
'-ar', "%d"%self.fps,
'-ac', '%d'%self.nchannels, '-'])
- self.proc = sp.Popen( cmd, bufsize=self.buffersize,
- stdout=sp.PIPE,
- stderr=sp.PIPE)
-
+
+ popen_params = {"bufsize": self.buffersize,
+ "stdout": sp.PIPE,
+ "stderr": sp.PIPE,
+ "stdin": DEVNULL}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ self.proc = sp.Popen( cmd, **popen_params)
+
self.pos = np.round(self.fps*starttime)
-
-
-
+
+
+
def skip_chunk(self,chunksize):
s = self.proc.stdout.read(self.nchannels*chunksize*self.nbytes)
self.proc.stdout.flush()
self.pos = self.pos+chunksize
-
-
-
+
+
+
def read_chunk(self,chunksize):
L = self.nchannels*chunksize*self.nbytes
s = self.proc.stdout.read(L)
@@ -111,7 +123,7 @@ class FFMPEG_AudioReader:
#self.proc.stdout.flush()
self.pos = self.pos+chunksize
return result
-
+
def seek(self,pos):
@@ -130,7 +142,7 @@ class FFMPEG_AudioReader:
self.skip_chunk(pos-self.pos)
# last case standing: pos = current pos
self.pos = pos
-
+
def close_proc(self):
@@ -140,25 +152,25 @@ 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
-
-
+
+
# elements of t that are actually in the range of the
# audio file.
-
+
in_time = (tt>=0) & (tt < self.duration)
-
+
# The np.round in the next line is super-important.
# Removing it results in artifacts in the noise.
frames = np.round((self.fps*tt)).astype(int)[in_time]
fr_min, fr_max = frames.min(), frames.max()
-
+
if not (0 <=
(fr_min - self.buffer_startframe)
< len(self.buffer)):
@@ -167,7 +179,7 @@ class FFMPEG_AudioReader:
(fr_max - self.buffer_startframe)
< len(self.buffer)):
self.buffer_around(fr_max)
-
+
try:
result = np.zeros((len(tt),self.nchannels))
indices = frames - self.buffer_startframe
@@ -178,20 +190,20 @@ class FFMPEG_AudioReader:
"At time t=%.02f-%.02f seconds, "%(tt[0], tt[-1])+
"indices wanted: %d-%d, "%(indices.min(), indices.max())+
"but len(buffer)=%d\n"%(len(self.buffer))+ str(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):
"""
@@ -201,8 +213,8 @@ class FFMPEG_AudioReader:
# start-frame for the buffer
new_bufferstart = max(0, framenumber - self.buffersize // 2)
-
-
+
+
if (self.buffer!=None):
current_f_end = self.buffer_startframe + self.buffersize
if (new_bufferstart <
@@ -219,12 +231,12 @@ class FFMPEG_AudioReader:
else:
self.seek(new_bufferstart)
self.buffer = self.read_chunk(self.buffersize)
-
+
self.buffer_startframe = new_bufferstart
-
-
+
+
def __del__(self):
self.close_proc()
-
-
+
+
diff --git a/moviepy/conf.py b/moviepy/conf.py
index e434a958..44b5bedb 100644
--- a/moviepy/conf.py
+++ b/moviepy/conf.py
@@ -17,16 +17,16 @@ FFMPEG_BINARY
use a binary at a special location on you disk, enter it like that:
FFMPEG_BINARY = r"path/to/ffmpeg(.exe)"
-
+
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"
+ IMAGEMAGICK_BINARY = r"C:\Program Files\ImageMagick-6.8.8-Q16\convert.exe"
You can run this file to check that FFMPEG has been detected.
"""
@@ -41,7 +41,7 @@ IMAGEMAGICK_BINARY = 'convert'
import subprocess as sp
-def try_cmd(cmd):
+def try_cmd(cmd):
try:
proc = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
proc.communicate()
@@ -52,20 +52,20 @@ def try_cmd(cmd):
if FFMPEG_BINARY is None:
-
+
if try_cmd(['ffmpeg']):
FFMPEG_BINARY = 'ffmpeg'
elif try_cmd(['ffmpeg.exe']):
FFMPEG_BINARY = 'ffmpeg.exe'
else:
- raise IOError("FFMPEG binary not found. Try installing MoviePy"
- " manually and specify the path to the binary in"
- " the file conf.py")
+ print ("FFMPEG binary not found. Try installing MoviePy"
+ " manually and specify the path to the binary in"
+ " the file conf.py")
if __name__ == "__main__":
if try_cmd([FFMPEG_BINARY]):
print( "MoviePy : ffmpeg successfully found." )
else:
print( "MoviePy : can't find ffmpeg." )
-
-
+
+
diff --git a/moviepy/tools.py b/moviepy/tools.py
index 72da7fa1..16f4aa16 100644
--- a/moviepy/tools.py
+++ b/moviepy/tools.py
@@ -7,11 +7,17 @@ import sys
import warnings
import re
+try:
+ from subprocess import DEVNULL # py3k
+except ImportError:
+ import os
+ DEVNULL = open(os.devnull, 'wb')
+
def sys_write_flush(s):
""" Writes and flushes without delay a text in the console """
sys.stdout.write(s)
sys.stdout.flush()
-
+
def verbose_print(verbose, s):
""" Only prints s (with sys_write_flush) if verbose is True."""
@@ -23,18 +29,25 @@ def subprocess_call(cmd, verbose=True, errorprint=True):
""" Executes the given subprocess command."""
verbose_print(verbose, "\nMoviePy Running:\n>>> "+ " ".join(cmd))
-
- proc = sp.Popen(cmd, stderr = sp.PIPE)
-
+
+ popen_params = {"stdout": DEVNULL,
+ "stderr": sp.PIPE,
+ "stdin": DEVNULL}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ proc = sp.Popen(cmd, **popen_params)
+
out, err = proc.communicate() # proc.wait()
proc.stderr.close()
-
+
if proc.returncode:
verbose_print(errorprint, "\nMoviePy: This command returned an error !")
raise IOError(err.decode('utf8'))
else:
verbose_print(verbose, "\n... command successful.\n")
-
+
del proc
def is_string(obj):
@@ -48,7 +61,7 @@ def is_string(obj):
def cvsecs(time):
""" Will convert any time into seconds.
Here are the accepted formats:
-
+
>>> cvsecs(15.4) -> 15.4 # seconds
>>> cvsecs( (1,21.5) ) -> 81.5 # (min,sec)
>>> cvsecs( (1,1,2) ) -> 3662 # (hr, min, sec)
@@ -67,35 +80,35 @@ def cvsecs(time):
+ 60*int(finds[1])
+ int(finds[2])
+ nums[3]/(10**len(finds[3])))
-
+
elif isinstance(time, tuple):
if len(time)== 3:
hr, mn, sec = time
elif len(time)== 2:
- hr, mn, sec = 0, time[0], time[1]
+ hr, mn, sec = 0, time[0], time[1]
return 3600*hr + 60*mn + sec
-
+
else:
return time
def deprecated_version_of(f, oldname, newname=None):
""" Indicates that a function is deprecated and has a new name.
-
+
`f` is the new function, `oldname` the name of the deprecated
function, `newname` the name of `f`, which can be automatically
found.
-
+
Returns
========
-
+
f_deprecated
A function that does the same thing as f, but with a docstring
and a printed message on call which say that the function is
deprecated and that you should use f instead.
-
+
Examples
=========
-
+
>>> # The badly named method 'to_file' is replaced by 'write_file'
>>> class Clip:
>>> def write_file(self, some args):
@@ -103,18 +116,18 @@ def deprecated_version_of(f, oldname, newname=None):
>>>
>>> Clip.to_file = deprecated_version_of(Clip.write_file, 'to_file')
"""
-
+
if newname is None: newname = f.__name__
-
+
warning= ("The function ``%s`` is deprecated and is kept temporarily "
"for backwards compatibility.\nPlease use the new name, "
"``%s``, instead.")%(oldname, newname)
-
+
def fdepr(*a, **kw):
warnings.warn("MoviePy: " + warning, PendingDeprecationWarning)
return f(*a, **kw)
fdepr.__doc__ = warning
-
+
return fdepr
@@ -126,7 +139,7 @@ def deprecated_version_of(f, oldname, newname=None):
extensions_dict = { "mp4": {'type':'video', 'codec':['libx264','libmpeg4']},
'ogv': {'type':'video', 'codec':['libtheora']},
'webm': {'type':'video', 'codec':['libvpx']},
- 'avi': {'type':'video'},
+ 'avi': {'type':'video'},
'mov': {'type':'video'},
'ogg': {'type':'audio', 'codec':['libvorbis']},
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index 5cd32dfa..8df8878f 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -32,7 +32,7 @@ from ..tools import (subprocess_call,
verbose_print,
is_string,
deprecated_version_of,
- extensions_dict, find_extension)
+ extensions_dict, find_extension)
from ..decorators import (apply_to_mask,
requires_duration,
@@ -41,6 +41,12 @@ from ..decorators import (apply_to_mask,
convert_to_seconds)
+try:
+ from subprocess import DEVNULL # py3k
+except ImportError:
+ import os
+ DEVNULL = open(os.devnull, 'wb')
+
class VideoClip(Clip):
"""Base class for video clips.
@@ -126,7 +132,7 @@ class VideoClip(Clip):
Saves the frame of clip corresponding to time ``t`` in
'filename'. ``t`` can be expressed in seconds (15.35), in
(min, sec), in (hour, min, sec), or as a string: '01:03:05.35'.
-
+
If ``savemask`` is ``True`` the mask is saved in
the alpha layer of the picture.
@@ -177,7 +183,7 @@ class VideoClip(Clip):
to ``'libx264'``, and produces higher quality videos by default.
- ``'rawvideo'`` (use file extension ``.avi``) will produce
+ ``'rawvideo'`` (use file extension ``.avi``) will produce
a video of perfect quality, of possibly very huge size.
@@ -213,7 +219,7 @@ class VideoClip(Clip):
for '.mp3', 'libvorbis' for 'ogg', 'libfdk_aac':'m4a',
'pcm_s16le' for 16-bit wav and 'pcm_s32le' for 32-bit wav.
Default is 'libmp3lame', unless the video extension is 'ogv'
- or 'webm', at which case the default is 'libvorbis'.
+ or 'webm', at which case the default is 'libvorbis'.
audio_bitrate
Audio bitrate, given as a string like '50k', '500k', '3000k'.
@@ -254,7 +260,7 @@ class VideoClip(Clip):
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'
@@ -299,14 +305,14 @@ class VideoClip(Clip):
verbose_print(verbose, "\nMoviePy: building video file %s\n"%filename
+40*"-"+"\n")
-
+
if make_audio:
self.audio.write_audiofile(audiofile,audio_fps,
audio_nbytes, audio_bufsize,
audio_codec, bitrate=audio_bitrate,
write_logfile=write_logfile,
verbose=verbose)
-
+
ffmpeg_write_video(self, filename, fps, codec,
bitrate=bitrate,
preset=preset,
@@ -375,7 +381,7 @@ class VideoClip(Clip):
verbose_print(verbose, "MoviePy: Done writing frames %s."%(nameformat))
return filenames
-
+
@requires_duration
@@ -424,7 +430,7 @@ class VideoClip(Clip):
>>> myClip.speedx(0.5).to_gif('myClip.gif')
"""
-
+
if tempfiles:
write_gif_with_tempfiles(self, filename, fps=fps,
program= program, opt=opt, fuzz=fuzz, verbose=verbose,
@@ -438,7 +444,7 @@ class VideoClip(Clip):
# F I L T E R I N G
-
+
def subfx(self, fx, ta=0, tb=None, **kwargs):
""" Apply a transformation to a part of the clip.
@@ -480,7 +486,7 @@ class VideoClip(Clip):
#--------------------------------------------------------------
# C O M P O S I T I N G
-
+
def blit_on(self, picture, t):
"""
Returns the result of the blit of the clip's frame at time `t`
@@ -905,10 +911,10 @@ class ImageClip(VideoClip):
# The old functions to_videofile, to_gif, to_images sequences have been
# replaced by the more explicite write_videofile, write_gif, etc.
-VideoClip.to_videofile = deprecated_version_of(VideoClip.write_videofile,
+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,
+VideoClip.to_images_sequence = deprecated_version_of(VideoClip.write_images_sequence,
'to_images_sequence')
###
@@ -1015,7 +1021,7 @@ class TextClip(ImageClip):
tempfilename=None, temptxt=None,
transparent=True, remove_temp=True,
print_cmd=False):
-
+
if txt is not None:
if temptxt is None:
@@ -1083,8 +1089,14 @@ class TextClip(ImageClip):
""" Returns the list of all valid entries for the argument of
``TextClip`` given (can be ``font``, ``color``, etc...) """
- process = sp.Popen([IMAGEMAGICK_BINARY, '-list', arg],
- stdout=sp.PIPE)
+ popen_params = {"stdout": sp.PIPE,
+ "stderr": DEVNULL,
+ "stdin": DEVNULL}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ process = sp.Popen([IMAGEMAGICK_BINARY, '-list', arg], **popen_params)
result = process.communicate()[0]
lines = result.splitlines()
diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.py
index c07f4a64..e4e77e3d 100644
--- a/moviepy/video/io/ffmpeg_reader.py
+++ b/moviepy/video/io/ffmpeg_reader.py
@@ -12,6 +12,12 @@ import numpy as np
from moviepy.conf import FFMPEG_BINARY # ffmpeg, ffmpeg.exe, etc...
from moviepy.tools import cvsecs
+try:
+ from subprocess import DEVNULL # py3k
+except ImportError:
+ import os
+ DEVNULL = open(os.devnull, 'wb')
+
class FFMPEG_VideoReader:
@@ -48,28 +54,33 @@ class FFMPEG_VideoReader:
def initialize(self, starttime=0):
"""Opens the file, creates the pipe. """
-
+
self.close() # if any
-
+
if starttime !=0 :
- offset = min(1,starttime)
+ offset = min(1, starttime)
i_arg = ['-ss', "%.03f" % (starttime - offset),
- '-i', self.filename,
- '-ss', "%.03f" % offset]
+ '-i', self.filename,
+ '-ss', "%.03f" % offset]
else:
i_arg = [ '-i', self.filename]
-
-
+
+
cmd = ([FFMPEG_BINARY]+ i_arg +
- ['-loglevel', 'error',
+ ['-loglevel', 'error',
'-f', 'image2pipe',
"-pix_fmt", self.pix_fmt,
'-vcodec', 'rawvideo', '-'])
-
-
- self.proc = sp.Popen(cmd, bufsize= self.bufsize,
- stdout=sp.PIPE,
- stderr=sp.PIPE)
+
+ popen_params = {"bufsize": self.bufsize,
+ "stdout": sp.PIPE,
+ "stderr": sp.PIPE,
+ "stdin": DEVNULL}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ self.proc = sp.Popen(cmd, **popen_params)
@@ -98,7 +109,7 @@ 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 "
@@ -120,7 +131,7 @@ class FFMPEG_VideoReader:
def get_frame(self, t):
""" Read a file video frame at time t.
-
+
Note for coders: getting an arbitrary frame in the video with
ffmpeg can be painfully slow if some decoding has to be done.
This function tries to avoid fectching arbitrary frames
@@ -128,7 +139,7 @@ class FFMPEG_VideoReader:
"""
# these definitely need to be rechecked sometime. Seems to work.
-
+
pos = int(self.fps*t)+1
if pos == self.pos:
@@ -141,40 +152,40 @@ class FFMPEG_VideoReader:
result = self.read_frame()
self.pos = pos
return result
-
+
def close(self):
if hasattr(self,'proc'):
self.proc.terminate()
self.proc.stdout.close()
self.proc.stderr.close()
del self.proc
-
+
def __del__(self):
self.close()
if hasattr(self,'lastread'):
del self.lastread
-
+
def ffmpeg_read_image(filename, with_mask=True):
""" Read an image file (PNG, BMP, JPEG...).
-
+
Wraps FFMPEG_Videoreader to read just one image.
Returns an ImageClip.
This function is not meant to be used directly in MoviePy,
use ImageClip instead to make clips out of image files.
-
+
Parameters
-----------
-
+
filename
Name of the image file. Can be of any format supported by ffmpeg.
-
+
with_mask
If the image has a transparency layer, ``with_mask=true`` will save
this layer as the mask of the returned ImageClip
-
+
"""
if with_mask:
pix_fmt = 'rgba'
@@ -196,17 +207,23 @@ def ffmpeg_parse_infos(filename, print_infos=False, check_duration=True):
fetching the uncomplete frames at the end, which raises an error.
"""
-
+
# open the file in a pipe, provoke an error, read output
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)
+
+ popen_params = {"bufsize": 10**5,
+ "stdout": sp.PIPE,
+ "stderr": sp.PIPE,
+ "stdin": DEVNULL}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ proc = sp.Popen(cmd, **popen_params)
proc.stdout.readline()
proc.terminate()
@@ -223,9 +240,9 @@ def ffmpeg_parse_infos(filename, print_infos=False, check_duration=True):
raise IOError(("MoviePy error: the file %s could not be found !\n"
"Please check that you entered the correct "
"path.")%filename)
-
+
result = dict()
-
+
# get duration (in seconds)
result['duration'] = None
@@ -243,11 +260,11 @@ def ffmpeg_parse_infos(filename, print_infos=False, check_duration=True):
# get the output line that speaks about video
lines_video = [l for l in lines if ' Video: ' in l]
-
+
result['video_found'] = ( lines_video != [] )
-
+
if result['video_found']:
-
+
line = lines_video[0]
# get the size, of the form 460x320 (w x h)
@@ -260,7 +277,7 @@ def ffmpeg_parse_infos(filename, print_infos=False, check_duration=True):
# tbc, and sometimes tbc/2...
# Current policy: Trust tbr first, then fps. If result is near from x*1000/1001
# where x is 23,24,25,50, replace by x*1000/1001 (very common case for the fps).
-
+
try:
match = re.search("( [0-9]*.| )[0-9]* tbr", line)
tbr = float(line[match.start():match.end()].split(' ')[1])
@@ -278,7 +295,7 @@ def ffmpeg_parse_infos(filename, print_infos=False, check_duration=True):
for x in [23,24,25,30,50]:
if (fps!=x) and abs(fps - x*coef) < .01:
result['video_fps'] = x*coef
-
+
if check_duration:
result['video_nframes'] = int(result['duration']*result['video_fps'])+1
result['video_duration'] = result['duration']
@@ -291,9 +308,9 @@ def ffmpeg_parse_infos(filename, print_infos=False, check_duration=True):
lines_audio = [l for l in lines if ' Audio: ' in l]
-
+
result['audio_found'] = lines_audio != []
-
+
if result['audio_found']:
line = lines_audio[0]
try:
diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.py
index 01b1d496..794d79e1 100644
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@ -24,13 +24,13 @@ 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
@@ -38,10 +38,10 @@ class FFMPEG_VideoWriter:
size
Size (width,height) of the output video in pixels.
-
+
fps
Frames per second in the output video file.
-
+
codec
FFMPEG codec. It seems that in terms of quality the hierarchy is
'rawvideo' = 'png' > 'mpeg4' > 'libx264'
@@ -53,10 +53,10 @@ class FFMPEG_VideoWriter:
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.
-
+
preset
Sets the time that FFMPEG will take to compress the video. The slower,
the better the compression rate. Possibilities are: ultrafast,superfast,
@@ -65,15 +65,15 @@ class FFMPEG_VideoWriter:
bitrate
Only relevant for codecs which accept a bitrate. "5000k" offers
nice results in general.
-
+
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):
@@ -84,7 +84,7 @@ class FFMPEG_VideoWriter:
self.filename = filename
self.codec = codec
self.ext = self.filename.split(".")[-1]
-
+
cmd = (
[ FFMPEG_BINARY, '-y']
+["-loglevel", "error" if logfile==sp.PIPE else "info",
@@ -96,24 +96,29 @@ class FFMPEG_VideoWriter:
'-i', '-', '-an']
+ (["-i", audiofile, "-acodec", "copy"] if (audiofile is not None) else [])
+['-vcodec', codec,
- '-preset', preset]
+ '-preset', preset]
+ (['-b',bitrate] if (bitrate!=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 ]
#+ (["-acodec", "copy"] if (audiofile is not None) else [])
)
- self.proc = sp.Popen(cmd, stdin=sp.PIPE,
- stderr=logfile,
- stdout=DEVNULL)
+ popen_params = {"stdout": DEVNULL,
+ "stderr": logfile,
+ "stdin": sp.PIPE}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
+ self.proc = sp.Popen(cmd, **popen_params)
+
-
def write_frame(self,img_array):
""" Writes one frame in the file."""
try:
@@ -125,14 +130,14 @@ class FFMPEG_VideoWriter:
+ "\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 "
"write_videofile. For instance:\n"
" >>> clip.write_videofile('myvid.webm', codec='libvpx')")%(self.codec)
-
+
elif "incorrect codec parameters ?" in ffmpeg_error:
error = error+("\n\nThe video export "
@@ -152,21 +157,21 @@ class FFMPEG_VideoWriter:
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):
self.proc.stdin.close()
if self.proc.stderr is not None:
self.proc.stderr.close()
self.proc.wait()
-
+
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):
-
+
if write_logfile:
logfile = open(filename + ".log", 'w+')
else:
@@ -177,25 +182,25 @@ def ffmpeg_write_video(clip, filename, fps, codec="libx264", bitrate=None,
writer = FFMPEG_VideoWriter(filename, clip.size, fps, codec = codec,
preset=preset, bitrate=bitrate, logfile=logfile,
audiofile = audiofile)
-
+
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])
-
+
writer.write_frame(frame.astype("uint8"))
-
+
writer.close()
if write_logfile:
logfile.close()
-
+
verbose_print(verbose, "Done writing video in %s !"%filename)
-
-
+
+
def ffmpeg_write_image(filename, image, logfile=False):
""" Writes an image (HxWx3 or HxWx4 numpy array) to a file, using
ffmpeg. """
@@ -206,16 +211,23 @@ def ffmpeg_write_image(filename, image, logfile=False):
"-f", 'rawvideo',
'-pix_fmt', "rgba" if (image.shape[2] == 4) else "rgb24",
'-i','-', filename]
-
- if logfile:
+
+ if logfile:
log_file = open(filename + ".log", 'w+')
else:
log_file = sp.PIPE
- proc = sp.Popen( cmd, stdin=sp.PIPE, stderr=log_file)
+ 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()
-
+
if proc.returncode:
err = "\n".join(["MoviePy running : %s"%cmd,
"WARNING: this command returned an error:",
@@ -223,5 +235,5 @@ def ffmpeg_write_image(filename, image, logfile=False):
raise IOError(err)
-
+
del proc
diff --git a/moviepy/video/io/gif_writers.py b/moviepy/video/io/gif_writers.py
index bb76096f..4f00282d 100644
--- a/moviepy/video/io/gif_writers.py
+++ b/moviepy/video/io/gif_writers.py
@@ -79,13 +79,13 @@ def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick',
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:
@@ -149,7 +149,7 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',
# if program == 'ImageMagick' and optimize == (None, False)
# frames --ffmpeg--> bmp frames --ImageMagick--> gif
#
- #
+ #
# if program == 'ImageMagick' and optimize != (None, False)
# frames -ffmpeg-> bmp frames -ImagMag-> gif -ImagMag-> better gif
#
@@ -164,34 +164,53 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',
'-s', "%dx%d"%(clip.w, clip.h), '-pix_fmt', 'rgb24',
'-i', '-']
+ popen_params = {"stdout": DEVNULL,
+ "stderr": DEVNULL,
+ "stdin": DEVNULL}
+
+ if os.name == "nt":
+ popen_params["creationflags"] = 0x08000000
+
if program == "ffmpeg":
- proc1 = sp.Popen(cmd1+['-r', "%.02f"%fps, filename],
- stdin=sp.PIPE, stdout=DEVNULL)
+ popen_params["stdin"] = sp.PIPE
+ popen_params["stdout"] = DEVNULL
+
+ proc1 = sp.Popen(cmd1+['-r', "%.02f"%fps, filename], **popen_params)
else:
+
+ popen_params["stdin"] = sp.PIPE
+ popen_params["stdout"] = sp.PIPE
+
proc1 = sp.Popen(cmd1+['-f', 'image2pipe',
'-vcodec', 'bmp', '-'],
- stdin=sp.PIPE, stdout=sp.PIPE)
+ **popen_params)
if program == 'ImageMagick':
-
+
cmd2 = [IMAGEMAGICK_BINARY, '-delay', "%.02f"%(delay),
"-dispose" ,"%d"%(2 if dispose else 1),
'-loop', '%d'%loop, '-', '-coalesce']
-
+
if (opt in [False, None]):
- proc2 = sp.Popen(cmd2+[filename], stdin=proc1.stdout)
-
+ popen_params["stdin"] = proc1.stdout
+ popen_params["stdout"] = DEVNULL
+ proc2 = sp.Popen(cmd2+[filename], **popen_params)
+
else:
- proc2 = sp.Popen(cmd2+['gif:-'] , stdin=proc1.stdout,
- stdout=sp.PIPE)
-
+ popen_params["stdin"] = proc1.stdout
+ popen_params["stdout"] = sp.PIPE
+ proc2 = sp.Popen(cmd2+['gif:-'], **popen_params)
+
if opt:
-
+
cmd3 = [IMAGEMAGICK_BINARY, '-', '-layers', opt,
'-fuzz', '%d'%fuzz+'%'
]+(["-colors", "%d"%colors] if colors is not None else [])+[
filename]
- proc3 = sp.Popen(cmd3, stdin=proc2.stdout)
+
+ popen_params["stdin"] = proc2.stdout
+ popen_params["stdout"] = DEVNULL
+ proc3 = sp.Popen(cmd3, **popen_params)
# We send all the frames to the first process
verbose_print(verbose, "\nMoviePy: building GIF file %s\n"%filename
@@ -208,13 +227,13 @@ def write_gif(clip, filename, fps=None, program= 'ImageMagick',
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)
verbose_print(verbose, "Writing GIF... ")
proc1.stdin.close()