Skip to content

Video editing with Python

Test some ffmpeg video tools and document them (#1587)

Álvaro Mondéjare6764f5bf491
diff --git a/moviepy/video/io/ffmpeg_tools.py b/moviepy/video/io/ffmpeg_tools.py
index 4d540797..610a8cc9 100644
--- a/moviepy/video/io/ffmpeg_tools.py
+++ b/moviepy/video/io/ffmpeg_tools.py
@@ -3,21 +3,37 @@
import os
from moviepy.config import FFMPEG_BINARY
-from moviepy.decorators import convert_path_to_string
+from moviepy.decorators import convert_parameter_to_seconds, convert_path_to_string
from moviepy.tools import subprocess_call
@convert_path_to_string(("inputfile", "outputfile"))
+@convert_parameter_to_seconds(("start_time", "end_time"))
def ffmpeg_extract_subclip(
inputfile, start_time, end_time, outputfile=None, logger="bar"
):
- """Makes a new video file playing video file ``inputfile`` between
- the times ``start_time`` and ``end_time``.
+ """Makes a new video file playing video file between two times.
+
+ Parameters
+ ----------
+
+ inputfile : str
+ Path to the file from which the subclip will be extracted.
+
+ start_time : float
+ Moment of the input clip that marks the start of the produced subclip.
+
+ end_time : float
+ Moment of the input clip that marks the end of the produced subclip.
+
+ outputfile : str, optional
+ Path to the output file. Defaults to
+ ``<inputfile_name>SUB<start_time>_<end_time><ext>``.
"""
- name, ext = os.path.splitext(inputfile)
if not outputfile:
- T1, T2 = [int(1000 * t) for t in [start_time, end_time]]
- outputfile = "%sSUB%d_%d%s" % (name, T1, T2, ext)
+ name, ext = os.path.splitext(inputfile)
+ t1, t2 = [int(1000 * t) for t in [start_time, end_time]]
+ outputfile = "%sSUB%d_%d%s" % (name, t1, t2, ext)
cmd = [
FFMPEG_BINARY,
@@ -49,8 +65,25 @@ def ffmpeg_merge_video_audio(
audio_codec="copy",
logger="bar",
):
- """Merges video file ``videofile`` and audio file ``audiofile`` into one
- movie file ``outputfile``.
+ """Merges video file and audio file into one movie file.
+
+ Parameters
+ ----------
+
+ videofile : str
+ Path to the video file used in the merge.
+
+ audiofile : str
+ Path to the audio file used in the merge.
+
+ outputfile : str
+ Path to the output file.
+
+ video_codec : str, optional
+ Video codec used by FFmpeg in the merge.
+
+ audio_codec : str, optional
+ Audio codec used by FFmpeg in the merge.
"""
cmd = [
FFMPEG_BINARY,
@@ -71,7 +104,23 @@ def ffmpeg_merge_video_audio(
@convert_path_to_string(("inputfile", "outputfile"))
def ffmpeg_extract_audio(inputfile, outputfile, bitrate=3000, fps=44100, logger="bar"):
- """Extract the sound from a video file and save it in ``outputfile``."""
+ """Extract the sound from a video file and save it in ``outputfile``.
+
+ Parameters
+ ----------
+
+ inputfile : str
+ The path to the file from which the audio will be extracted.
+
+ outputfile : str
+ The path to the file to which the audio will be stored.
+
+ bitrate : int, optional
+ Bitrate for the new audio file.
+
+ fps : int, optional
+ Frame rate for the new audio file.
+ """
cmd = [
FFMPEG_BINARY,
"-y",
@@ -88,8 +137,19 @@ def ffmpeg_extract_audio(inputfile, outputfile, bitrate=3000, fps=44100, logger=
@convert_path_to_string(("inputfile", "outputfile"))
def ffmpeg_resize(inputfile, outputfile, size, logger="bar"):
- """Resizes ``inputfile`` to new size ``size`` and write the result
- in file ``outputfile``.
+ """Resizes a file to new size and write the result in another.
+
+ Parameters
+ ----------
+
+ inputfile : str
+ Path to the file to be resized.
+
+ outputfile : str
+ Path to the output file.
+
+ size : list or tuple
+ New size in format ``[width, height]`` for the output file.
"""
cmd = [
FFMPEG_BINARY,
@@ -105,7 +165,7 @@ def ffmpeg_resize(inputfile, outputfile, size, logger="bar"):
@convert_path_to_string(("inputfile", "outputfile", "output_dir"))
def ffmpeg_stabilize_video(
- inputfile, outputfile=None, output_dir="", overwrite_file=True
+ inputfile, outputfile=None, output_dir="", overwrite_file=True, logger="bar"
):
"""
Stabilizes ``filename`` and write the result to ``output``.
@@ -113,20 +173,20 @@ def ffmpeg_stabilize_video(
Parameters
----------
- inputfile
- The name of the shaky video
+ inputfile : str
+ The name of the shaky video.
- outputfile
- The name of new stabilized video
- Optional: defaults to appending '_stabilized' to the input file name
+ outputfile : str, optional
+ The name of new stabilized video. Defaults to appending '_stabilized' to
+ the input file name.
- output_dir
- The directory to place the output video in
- Optional: defaults to the current working directory
+ output_dir : str, optional
+ The directory to place the output video in. Defaults to the current
+ working directory.
- overwrite_file
- If ``outputfile`` already exists in ``output_dir``, then overwrite ``outputfile``
- Optional: defaults to True
+ overwrite_file : bool, optional
+ If ``outputfile`` already exists in ``output_dir``, then overwrite
+ ``outputfile`` Defaults to True.
"""
if not outputfile:
without_dir = os.path.basename(inputfile)
@@ -137,4 +197,4 @@ def ffmpeg_stabilize_video(
cmd = [FFMPEG_BINARY, "-i", inputfile, "-vf", "deshake", outputfile]
if overwrite_file:
cmd.append("-y")
- subprocess_call(cmd)
+ subprocess_call(cmd, logger=logger)
diff --git a/tests/test_ffmpeg_tools.py b/tests/test_ffmpeg_tools.py
index d1e7c1c1..7c817f18 100644
--- a/tests/test_ffmpeg_tools.py
+++ b/tests/test_ffmpeg_tools.py
@@ -1,10 +1,119 @@
+"""FFmpeg tools tests for moviepy."""
+
import os
+import shutil
+
+import pytest
-from moviepy.video.io.ffmpeg_tools import ffmpeg_stabilize_video
+from moviepy.video.io.ffmpeg_tools import (
+ ffmpeg_extract_subclip,
+ ffmpeg_resize,
+ ffmpeg_stabilize_video,
+)
+from moviepy.video.io.VideoFileClip import VideoFileClip
from tests.test_helper import TMP_DIR
-def test_stabilize_video():
- ffmpeg_stabilize_video("media/fire2.mp4", output_dir=TMP_DIR, overwrite_file=True)
- assert os.path.exists(os.path.join(TMP_DIR, "fire2_stabilized.mp4"))
+def test_ffmpeg_extract_subclip():
+ extract_subclip_tempdir = os.path.join(TMP_DIR, "moviepy_ffmpeg_extract_subclip")
+ if os.path.isdir(extract_subclip_tempdir):
+ shutil.rmtree(extract_subclip_tempdir)
+ os.mkdir(extract_subclip_tempdir)
+
+ inputfile = os.path.join(extract_subclip_tempdir, "fire2.mp4")
+ shutil.copyfile("media/fire2.mp4", inputfile)
+
+ # default name
+ expected_outputfile = os.path.join(extract_subclip_tempdir, "fire2SUB300_500.mp4")
+ ffmpeg_extract_subclip(inputfile, 0.3, "00:00:00,5", logger=None)
+ assert os.path.isfile(expected_outputfile)
+
+ # custom name
+ expected_outputfile = os.path.join(extract_subclip_tempdir, "foo.mp4")
+ ffmpeg_extract_subclip(
+ inputfile, 0.3, "00:00:00,5", outputfile=expected_outputfile, logger=None
+ )
+ assert os.path.isfile(expected_outputfile)
+
+ # assert subclip duration
+ clip = VideoFileClip(expected_outputfile)
+ assert 0.18 <= clip.duration <= 0.22 # not accurate
+
+ if os.path.isdir(extract_subclip_tempdir):
+ try:
+ shutil.rmtree(extract_subclip_tempdir)
+ except PermissionError:
+ pass
+
+
+def test_ffmpeg_resize():
+ outputfile = os.path.join(TMP_DIR, "moviepy_ffmpeg_resize.mp4")
+ if os.path.isfile(outputfile):
+ os.remove(outputfile)
+
+ expected_size = (30, 30)
+
+ ffmpeg_resize("media/bitmap.mp4", outputfile, expected_size, logger=None)
+ assert os.path.isfile(outputfile)
+
+ # overwrite file
+ with pytest.raises(OSError):
+ ffmpeg_resize("media/bitmap.mp4", outputfile, expected_size, logger=None)
+
+ clip = VideoFileClip(outputfile)
+ assert clip.size[0] == expected_size[0]
+ assert clip.size[1] == expected_size[1]
+
+ if os.path.isfile(outputfile):
+ try:
+ os.remove(outputfile)
+ except PermissionError:
+ pass
+
+
+def test_ffmpeg_stabilize_video():
+ stabilize_video_tempdir = os.path.join(TMP_DIR, "moviepy_ffmpeg_stabilize")
+ if os.path.isdir(stabilize_video_tempdir):
+ shutil.rmtree(stabilize_video_tempdir)
+ os.mkdir(stabilize_video_tempdir)
+
+ # no output file
+ ffmpeg_stabilize_video(
+ "media/bitmap.mp4",
+ output_dir=stabilize_video_tempdir,
+ logger=None,
+ )
+
+ expected_filepath = os.path.join(stabilize_video_tempdir, "bitmap_stabilized.mp4")
+ assert os.path.isfile(expected_filepath)
+
+ # with output file
+ ffmpeg_stabilize_video(
+ "media/bitmap.mp4",
+ output_dir=stabilize_video_tempdir,
+ outputfile="foo.mp4",
+ logger=None,
+ )
+ expected_filepath = os.path.join(stabilize_video_tempdir, "foo.mp4")
+ assert os.path.isfile(expected_filepath)
+
+ # don't overwrite file
+ with pytest.raises(OSError):
+ ffmpeg_stabilize_video(
+ "media/bitmap.mp4",
+ output_dir=stabilize_video_tempdir,
+ outputfile="foo.mp4",
+ overwrite_file=False,
+ logger=None,
+ )
+
+ if os.path.isdir(stabilize_video_tempdir):
+ try:
+ shutil.rmtree(stabilize_video_tempdir)
+ except PermissionError:
+ pass
+
+
+if __name__ == "__main__":
+ pytest.main()