Skip to content

Video editing with Python

factorized ffmpeg's information reader. Now stderr also outputs to DEVNULL for the audio

Zulkob2b7717b884e
diff --git a/moviepy/audio/io/AudioFileClip.py b/moviepy/audio/io/AudioFileClip.py
index ad3718c5..4709d8b8 100644
--- a/moviepy/audio/io/AudioFileClip.py
+++ b/moviepy/audio/io/AudioFileClip.py
@@ -65,7 +65,7 @@ class AudioFileClip(AudioClip):
self.duration = self.reader.duration
self.end = self.duration
- self.nframes = self.reader.nframes
+
self.get_frame = lambda t: self.reader.get_frame(t)
self.nchannels = self.reader.nchannels
diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.py
index caf778ae..fa1fff06 100644
--- a/moviepy/audio/io/ffmpeg_audiowriter.py
+++ b/moviepy/audio/io/ffmpeg_audiowriter.py
@@ -4,6 +4,12 @@ import sys
import numpy as np
import subprocess as sp
+try:
+ 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.decorators import requires_duration
@@ -38,11 +44,17 @@ class FFMPEG_AudioWriter:
- def __init__(self, filename, fps_input, nbytes=2, nchannels = 2,
- codec='libfdk_aac', bitrate=None, input_video=None):
+ def __init__(self, filename, fps_input, nbytes=2,
+ nchannels = 2, codec='libfdk_aac', bitrate=None,
+ input_video=None,logfile=None):
self.filename = filename
+
+ if logfile is None:
+ logfile = DEVNULL
+
cmd = ([ FFMPEG_BINARY, '-y',
+ "-loglevel", "panic" if logfile==DEVNULL else "info",
"-f", 's%dle'%(8*nbytes),
"-acodec",'pcm_s%dle'%(8*nbytes),
'-ar', "%d"%fps_input,
@@ -56,7 +68,11 @@ class FFMPEG_AudioWriter:
+ (['-ab',bitrate] if (bitrate!=None) else [])
+ [ filename ])
- self.proc = sp.Popen(cmd,stdin=sp.PIPE, stderr=sp.PIPE)
+
+ self.proc = sp.Popen(cmd, stdin=sp.PIPE,
+ stderr=logfile,
+ stdout=DEVNULL)
+
def write_frames(self,frames_array):
self.proc.stdin.write(frames_array.tostring())
@@ -64,7 +80,8 @@ class FFMPEG_AudioWriter:
def close(self):
self.proc.stdin.close()
- self.proc.stderr.close()
+ #self.proc.stderr.close()
+ #self.proc.stdout.close()
self.proc.wait()
del self.proc
@@ -72,7 +89,8 @@ class FFMPEG_AudioWriter:
@requires_duration
def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
- codec='libvorbis', bitrate=None, verbose=True):
+ codec='libvorbis', bitrate=None,
+ write_logfile = False, verbose=True):
"""
A function that wraps the FFMPEG_AudioWriter to write an AudioClip
to a file.
@@ -80,11 +98,17 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
def verbose_print(s):
if verbose: sys_write_flush(s)
+
+ if write_logfile:
+ logfile = open(filename + ".log", 'w+')
+ else:
+ logfile = DEVNULL
verbose_print("Writing audio in %s\n"%filename)
writer = FFMPEG_AudioWriter(filename, fps, nbytes, clip.nchannels,
- codec=codec, bitrate=bitrate)
+ codec=codec, bitrate=bitrate,
+ logfile=logfile)
totalsize = int(fps*clip.duration)
@@ -99,7 +123,11 @@ def ffmpeg_audiowrite(clip, filename, fps, nbytes, buffersize,
tt = (1.0/fps)*np.arange(pospos[i],pospos[i+1])
sndarray = clip.to_soundarray(tt, nbytes= nbytes)
writer.write_frames(sndarray)
-
+
+
writer.close()
+ if write_logfile:
+ logfile.close()
+
verbose_print("Done writing Audio in %s !\n"%filename)
diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.py
index ad68974c..227c3c7c 100644
--- a/moviepy/audio/io/readers.py
+++ b/moviepy/audio/io/readers.py
@@ -3,6 +3,8 @@ import re
import numpy as np
from moviepy.tools import cvsecs
+
+from moviepy.video.io.ffmpeg_reader import ffmpeg_parse_infos
from moviepy.conf import FFMPEG_BINARY
@@ -45,7 +47,13 @@ class FFMPEG_AudioReader:
self.f = 's%dle'%(8*nbytes)
self.acodec = 'pcm_s%dle'%(8*nbytes)
self.nchannels = nchannels
- self.load_infos()
+ infos = ffmpeg_parse_infos(filename)
+ self.duration = infos['duration']
+ if 'video_duration' in infos:
+ self.duration = infos['video_duration']
+ else:
+ self.duration = infos['duration']
+ self.infos = infos
self.proc = None
self.buffersize=buffersize
@@ -53,35 +61,6 @@ class FFMPEG_AudioReader:
self.buffer_startframe = 1
self.initialize()
self.buffer_around(1)
-
-
- def load_infos(self, print_infos=False):
- """ reads the FFMPEG info on the file and sets self.size
- and self.fps """
- # open the file in a pipe, provoke an error, read output
- proc = sp.Popen([FFMPEG_BINARY,"-i",self.filename, "-"],
- stdin=sp.PIPE,
- stdout=sp.PIPE,
- stderr=sp.PIPE)
- proc.stdout.readline()
- proc.terminate()
- infos = proc.stderr.read().decode('utf8')
-
- if print_infos:
- # print the whole info text returned by FFMPEG
- print( infos )
-
- lines = infos.splitlines()
-
- if "No such file or directory" in lines[-1]:
- raise IOError("%s not found ! Wrong path ?"%self.filename)
-
- # 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(':'))
- self.duration = cvsecs(*hms)
- self.nframes = int(self.duration*self.fps)
diff --git a/moviepy/version.py b/moviepy/version.py
index 742901cd..7c7941d8 100644
--- a/moviepy/version.py
+++ b/moviepy/version.py
@@ -1 +1 @@
-__version__ = "0.2.1.7.17"
+__version__ = "0.2.1.7.18"
diff --git a/moviepy/video/io/VideoFileClip.py b/moviepy/video/io/VideoFileClip.py
index 7eb93fce..a36f240c 100644
--- a/moviepy/video/io/VideoFileClip.py
+++ b/moviepy/video/io/VideoFileClip.py
@@ -66,7 +66,7 @@ class VideoFileClip(VideoClip):
self.get_frame = lambda t: self.reader.get_frame(t)
# Make a reader for the audio, if any.
- if audio:
+ if audio and self.reader.infos['audio_found']:
self.audio = AudioFileClip(filename,
buffersize= audio_buffersize,
fps = audio_fps,
diff --git a/moviepy/video/io/ffmpeg_reader.py b/moviepy/video/io/ffmpeg_reader.py
index 9ebe8813..b8272271 100644
--- a/moviepy/video/io/ffmpeg_reader.py
+++ b/moviepy/video/io/ffmpeg_reader.py
@@ -14,7 +14,14 @@ class FFMPEG_VideoReader:
pix_fmt="rgb24"):
self.filename = filename
- self.load_infos(print_infos)
+ infos = ffmpeg_parse_infos(filename, print_infos)
+ self.fps = infos['video_fps']
+ self.size = infos['video_size']
+ self.duration = infos['video_duration']
+ self.nframes = infos['video_nframes']
+
+ self.infos = infos
+
self.pix_fmt = pix_fmt
if pix_fmt == 'rgba':
self.depth = 4
@@ -33,6 +40,7 @@ class FFMPEG_VideoReader:
self.pos = 1
self.lastread = self.read_frame()
+
def initialize(self, starttime=0):
"""Opens the file, creates the pipe. """
@@ -57,48 +65,8 @@ class FFMPEG_VideoReader:
self.proc = sp.Popen(cmd, bufsize= self.bufsize,
stdout=sp.PIPE,
stderr=sp.PIPE)
-
-
- def load_infos(self, print_infos=False):
- """Get file infos using ffmpeg.
-
- Grabs the FFMPEG info on the file and use them to set the
- attributes ``self.size`` and ``self.fps`` """
-
- # open the file in a pipe, provoke an error, read output
- proc = sp.Popen([FFMPEG_BINARY, "-i", self.filename, "-"],
- bufsize=10**6,
- stdout=sp.PIPE,
- stderr=sp.PIPE)
- proc.stdout.readline()
- proc.terminate()
- infos = proc.stderr.read().decode('utf8')
- if print_infos:
- # print the whole info text returned by FFMPEG
- print( infos )
-
- lines = infos.splitlines()
- if "No such file or directory" in lines[-1]:
- raise IOError("%s not found ! Wrong path ?" % self.filename)
-
- # get the output line that speaks about video
- line = [l for l in lines if ' Video: ' in l][0]
- # get the size, of the form 460x320 (w x h)
- match = re.search(" [0-9]*x[0-9]*(,| )", line)
- self.size = list(map(int, line[match.start():match.end()-1].split('x')))
- # get the frame rate
- match = re.search("( [0-9]*.| )[0-9]* (tbr|fps)", line)
- self.fps = float(line[match.start():match.end()].split(' ')[1])
-
- # 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(':'))
- duration = cvsecs(*hms)
- self.nframes = int(duration*self.fps)
- self.duration = self.nframes / self.fps
@@ -146,14 +114,16 @@ class FFMPEG_VideoReader:
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))
-
+
if pos == self.pos:
return self.lastread
else:
@@ -203,3 +173,84 @@ def ffmpeg_read_image(filename, with_mask=True):
im = reader.lastread
del reader
return im
+
+def ffmpeg_parse_infos(filename, print_infos=False):
+ """Get file infos using ffmpeg.
+
+ Returns a dictionnary with the fields:
+ "video_found", "video_fps", "duration", "video_nframes",
+ "video_duration"
+ "audio_found", "audio_fps"
+
+ "video_duration" is slightly smaller than "duration" to avoid
+ fetching the uncomplete frames at the end, which raises an error.
+
+ """
+
+
+ # open the file in a pipe, provoke an error, read output
+ proc = sp.Popen([FFMPEG_BINARY, "-i", filename, "-"],
+ bufsize=10**6,
+ stdout=sp.PIPE,
+ stderr=sp.PIPE)
+
+ proc.stdout.readline()
+ proc.terminate()
+ infos = proc.stderr.read().decode('utf8')
+ if print_infos:
+ # print the whole info text returned by FFMPEG
+ print( infos )
+
+
+ lines = infos.splitlines()
+ if "No such file or directory" in lines[-1]:
+ raise IOError("%s not found ! Wrong path ?"%filename)
+
+ result = dict()
+
+
+ # 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)
+
+ # 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)
+ match = re.search(" [0-9]*x[0-9]*(,| )", line)
+ s = list(map(int, line[match.start():match.end()-1].split('x')))
+ result['video_size'] = s
+
+
+ # get the frame rate
+ try:
+ match = re.search("( [0-9]*.| )[0-9]* tbr", line)
+ result['video_fps'] = float(line[match.start():match.end()].split(' ')[1])
+ except:
+ 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']
+
+ 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:
+ match = re.search(" [0-9]* Hz", line)
+ result['audio_fps'] = int(line[match.start()+1:match.end()])
+ except:
+ result['audio_fps'] = 'unknown'
+
+ return result
diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.py
index 619b6d27..6a7932eb 100644
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@ -74,6 +74,7 @@ class FFMPEG_VideoWriter:
logfile = DEVNULL
self.filename = filename
+
cmd = (
[ FFMPEG_BINARY, '-y',
"-loglevel", "panic" if logfile==DEVNULL else "info",
@@ -109,6 +110,7 @@ class FFMPEG_VideoWriter:
def close(self):
self.proc.stdin.close()
+ #self.proc.stdout.close()
#self.proc.stderr.close()
self.proc.wait()