Skip to content

Video editing with Python

Add tests for ffmpeg_writer module (#1604)

Álvaro Mondéjar2aff1cfc1562
diff --git a/moviepy/video/io/ffmpeg_writer.py b/moviepy/video/io/ffmpeg_writer.py
index 38963c07..7032be0a 100644
--- a/moviepy/video/io/ffmpeg_writer.py
+++ b/moviepy/video/io/ffmpeg_writer.py
@@ -15,24 +15,21 @@ from moviepy.tools import cross_platform_popen_params
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
- '.avi' for all your videos.
+ filename : str
+ Any filename like ``"video.mp4"`` etc. but if you want to avoid
+ complications it is recommended to use the generic extension ``".avi"``
+ for all your videos.
- size
- Size (width,height) of the output video in pixels.
+ size : tuple or list
+ Size of the output video in pixels (width, height).
- fps
+ fps : int
Frames per second in the output video file.
- codec
+ codec : str, optional
FFMPEG codec. It seems that in terms of quality the hierarchy is
'rawvideo' = 'png' > 'mpeg4' > 'libx264'
'png' manages the same lossless quality as 'rawvideo' but yields
@@ -44,29 +41,37 @@ class FFMPEG_VideoWriter:
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.
+ audiofile : str, optional
+ The name of an audio file that will be incorporated to the video.
- preset
+ preset : str, optional
Sets the time that FFMPEG will take to compress the video. The slower,
- the better the compression rate. Possibilities are: ultrafast,superfast,
- veryfast, faster, fast, medium (default), slow, slower, veryslow,
- placebo.
+ the better the compression rate. Possibilities are: ``"ultrafast"``,
+ ``"superfast"``, ``"veryfast"``, ``"faster"``, ``"fast"``, ``"medium"``
+ (default), ``"slow"``, ``"slower"``, ``"veryslow"``, ``"placebo"``.
- bitrate
+ bitrate : str, optional
Only relevant for codecs which accept a bitrate. "5000k" offers
nice results in general.
- with_mask
- Boolean. Set to ``True`` if there is a mask in the video to be
- encoded.
+ with_mask : bool, optional
+ Set to ``True`` if there is a mask in the video to be encoded.
- pixel_format
+ pixel_format : str, optional
Optional: Pixel format for the output video file. If is not specified
- 'rgb24' will be used as the default format unless ``with_mask`` is set
- as ``True``, then 'rgba' will be used.
+ ``"rgb24"`` will be used as the default format unless ``with_mask`` is
+ set as ``True``, then ``"rgba"`` will be used.
+
+ logfile : int, optional
+ File descriptor for logging output. If not defined, ``subprocess.PIPE``
+ will be used. Defined using another value, the log level of the ffmpeg
+ command will be "info", otherwise "error".
+
+ threads : int, optional
+ Number of threads used to write the output with ffmpeg.
+ ffmpeg_params : list, optional
+ Additional parameters passed to ffmpeg command.
"""
def __init__(
@@ -90,7 +95,7 @@ class FFMPEG_VideoWriter:
self.filename = filename
self.codec = codec
self.ext = self.filename.split(".")[-1]
- if not pixel_format:
+ if not pixel_format: # pragma: no cover
pixel_format = "rgba" if with_mask else "rgb24"
# order is important
@@ -268,7 +273,26 @@ def ffmpeg_write_video(
def ffmpeg_write_image(filename, image, logfile=False, pixel_format=None):
- """Writes an image (HxWx3 or HxWx4 numpy array) to a file, using ffmpeg."""
+ """Writes an image (HxWx3 or HxWx4 numpy array) to a file, using ffmpeg.
+
+ Parameters
+ ----------
+
+ filename : str
+ Path to the output file.
+
+ image : np.ndarray
+ Numpy array with the image data.
+
+ logfile : bool, optional
+ Writes the ffmpeg output inside a logging file (``True``) or not
+ (``False``).
+
+ pixel_format : str, optional
+ Pixel format for ffmpeg. If not defined, it will be discovered checking
+ if the image data contains an alpha channel (``"rgba"``) or not
+ (``"rgb24"``).
+ """
if image.dtype != "uint8":
image = image.astype("uint8")
if not pixel_format:
@@ -298,7 +322,7 @@ def ffmpeg_write_image(filename, image, logfile=False, pixel_format=None):
)
proc = sp.Popen(cmd, **popen_params)
- out, err = proc.communicate(image.tostring())
+ out, err = proc.communicate(image.tobytes())
if proc.returncode:
error = (
diff --git a/tests/test_ffmpeg_writer.py b/tests/test_ffmpeg_writer.py
new file mode 100644
index 00000000..9be228e9
--- /dev/null
+++ b/tests/test_ffmpeg_writer.py
@@ -0,0 +1,173 @@
+"""FFmpeg writer tests of moviepy."""
+
+import multiprocessing
+import os
+
+import pytest
+from PIL import Image
+
+from moviepy.video.io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video
+from moviepy.video.io.VideoFileClip import VideoFileClip
+from moviepy.video.tools.drawing import color_gradient
+from moviepy.video.VideoClip import BitmapClip
+
+from tests.test_helper import TMP_DIR
+
+
+ "with_mask",
+ (False, True),
+ ids=("with_mask=False", "with_mask=True"),
+)
+ "write_logfile",
+ (False, True),
+ ids=("write_logfile=False", "write_logfile=True"),
+)
+ ("codec", "is_valid_codec", "ext"),
+ (
+ pytest.param(
+ "libcrazyfoobar", False, ".mp4", id="codec=libcrazyfoobar-ext=.mp4"
+ ),
+ pytest.param(None, True, ".mp4", id="codec=default-ext=.mp4"),
+ pytest.param("libtheora", False, ".avi", id="codec=libtheora-ext=.mp4"),
+ ),
+)
+ "bitrate",
+ (None, "5000k"),
+ ids=("bitrate=None", "bitrate=5000k"),
+)
+ "threads",
+ (None, multiprocessing.cpu_count()),
+ ids=("threads=None", "threads=multiprocessing.cpu_count()"),
+)
+def test_ffmpeg_write_video(
+ codec,
+ is_valid_codec,
+ ext,
+ write_logfile,
+ with_mask,
+ bitrate,
+ threads,
+):
+ filename = os.path.join(TMP_DIR, f"moviepy_ffmpeg_write_video{ext}")
+ if os.path.isfile(filename):
+ os.remove(filename)
+
+ logfile_name = filename + ".log"
+ if os.path.isfile(logfile_name):
+ os.remove(logfile_name)
+
+ clip = BitmapClip([["R"], ["G"], ["B"]], fps=10).with_duration(0.3)
+ if with_mask:
+ clip = clip.with_mask(
+ BitmapClip([["W"], ["O"], ["O"]], fps=10, is_mask=True).with_duration(0.3)
+ )
+
+ kwargs = dict(
+ logger=None,
+ write_logfile=write_logfile,
+ with_mask=with_mask,
+ )
+ if codec is not None:
+ kwargs["codec"] = codec
+ if bitrate is not None:
+ kwargs["bitrate"] = bitrate
+ if threads is not None:
+ kwargs["threads"] = threads
+
+ ffmpeg_write_video(clip, filename, 10, **kwargs)
+
+ if is_valid_codec:
+ assert os.path.isfile(filename)
+
+ final_clip = VideoFileClip(filename)
+
+ r, g, b = final_clip.get_frame(0)[0][0]
+ assert r == 254
+ assert g == 0
+ assert b == 0
+
+ r, g, b = final_clip.get_frame(0.1)[0][0]
+ assert r == (0 if not with_mask else 1)
+ assert g == (255 if not with_mask else 1)
+ assert b == 1
+
+ r, g, b = final_clip.get_frame(0.2)[0][0]
+ assert r == 0
+ assert g == 0
+ assert b == (255 if not with_mask else 0)
+
+ if write_logfile:
+ assert os.path.isfile(logfile_name)
+
+
+ ("size", "logfile", "pixel_format", "expected_result"),
+ (
+ pytest.param(
+ (5, 1),
+ False,
+ None,
+ [[(0, 255, 0), (51, 204, 0), (102, 153, 0), (153, 101, 0), (204, 50, 0)]],
+ id="size=(5, 1)",
+ ),
+ pytest.param(
+ (2, 1), False, None, [[(0, 255, 0), (51, 204, 0)]], id="size=(2, 1)"
+ ),
+ pytest.param(
+ (2, 1), True, None, [[(0, 255, 0), (51, 204, 0)]], id="logfile=True"
+ ),
+ pytest.param(
+ (2, 1),
+ False,
+ "invalid",
+ (OSError, "MoviePy error: FFMPEG encountered the following error"),
+ id="pixel_format=invalid-OSError",
+ ),
+ ),
+)
+def test_ffmpeg_write_image(size, logfile, pixel_format, expected_result):
+ filename = os.path.join(TMP_DIR, "moviepy_ffmpeg_write_image.png")
+ if os.path.isfile(filename):
+ os.remove(filename)
+
+ image_array = color_gradient(
+ size,
+ (0, 0),
+ p2=(5, 0),
+ color_1=(255, 0, 0),
+ color_2=(0, 255, 0),
+ )
+
+ if hasattr(expected_result[0], "__traceback__"):
+ with pytest.raises(expected_result[0]) as exc:
+ ffmpeg_write_image(
+ filename,
+ image_array,
+ logfile=logfile,
+ pixel_format=pixel_format,
+ )
+ assert expected_result[1] in str(exc.value)
+ return
+ else:
+ ffmpeg_write_image(
+ filename,
+ image_array,
+ logfile=logfile,
+ pixel_format=pixel_format,
+ )
+
+ assert os.path.isfile(filename)
+
+ if logfile:
+ assert os.path.isfile(filename + ".log")
+ os.remove(filename + ".log")
+
+ im = Image.open(filename, mode="r")
+ for i in range(im.width):
+ for j in range(im.height):
+ assert im.getpixel((i, j)) == expected_result[j][i]