Skip to content

Video editing with Python

Migrate preview to ffplay instead of pygame, making pygame now useless. Also add doc to some functions.

osaajani4bf4c3bea86a
diff --git a/moviepy/Clip.py b/moviepy/Clip.py
index c2907830..afbb7dd0 100644
--- a/moviepy/Clip.py
+++ b/moviepy/Clip.py
@@ -78,7 +78,6 @@ class Clip:
self.memoized_frame = frame
return frame
else:
- # print(t)
return self.make_frame(t)
def transform(self, func, apply_to=None, keep_duration=True):
diff --git a/moviepy/audio/AudioClip.py b/moviepy/audio/AudioClip.py
index 5811088b..d779873a 100644
--- a/moviepy/audio/AudioClip.py
+++ b/moviepy/audio/AudioClip.py
@@ -206,6 +206,12 @@ class AudioClip(Clip):
nbytes
Sample width (set to 2 for 16-bit sound, 4 for 32-bit sound)
+ buffersize
+ The sound is not generated all at once, but rather made by bunches
+ of frames (chunks). ``buffersize`` is the size of such a chunk.
+ Try varying it if you meet audio problems (but you shouldn't
+ have to). Default to 2000
+
codec
Which audio codec should be used. If None provided, the codec is
determined based on the extension of the filename. Choose
diff --git a/moviepy/audio/io/ffmpeg_audiopreviewer.py b/moviepy/audio/io/ffmpeg_audiopreviewer.py
new file mode 100644
index 00000000..cce62060
--- /dev/null
+++ b/moviepy/audio/io/ffmpeg_audiopreviewer.py
@@ -0,0 +1,168 @@
+"""MoviePy audio writing with ffmpeg."""
+
+import subprocess as sp
+
+import proglog
+
+from moviepy.config import FFMPEG_BINARY, FFPLAY_BINARY
+from moviepy.decorators import requires_duration
+from moviepy.tools import cross_platform_popen_params
+
+
+class FFMPEG_AudioPreviewer:
+ """
+ A class to preview an AudioClip.
+
+ Parameters
+ ----------
+
+ fps_input
+ Frames per second of the input audio (given by the AUdioClip being
+ written down).
+
+ nbytes:
+ Number of bytes to encode the sound: 1 for 8bit sound, 2 for
+ 16bit, 4 for 32bit sound. Default is 2 bytes, it's fine.
+
+ nchannels:
+ Number of audio channels in the clip. Default to 2 channels.
+
+ """
+
+ def __init__(
+ self,
+ fps_input,
+ nbytes=2,
+ nchannels=2,
+ ):
+
+ # order is important
+ cmd = [
+ FFPLAY_BINARY,
+ "-autoexit", # If you dont precise, ffplay dont stop at end
+ "-nodisp", # If you dont precise a window is
+ "-f",
+ "s%dle" % (8 * nbytes),
+ "-ar",
+ "%d" % fps_input,
+ "-ac",
+ "%d" % nchannels,
+ "-i",
+ "-",
+ ]
+
+ popen_params = cross_platform_popen_params(
+ {"stdout": sp.DEVNULL, "stderr": sp.STDOUT, "stdin": sp.PIPE}
+ )
+
+ self.proc = sp.Popen(cmd, **popen_params)
+
+ def write_frames(self, frames_array):
+ """ Send a raw audio frame (a chunck of audio) to ffplay to be played"""
+ try:
+ self.proc.stdin.write(frames_array.tobytes())
+ except IOError as err:
+ _, ffplay_error = self.proc.communicate()
+ if ffplay_error is not None:
+ ffplay_error = ffplay_error.decode()
+ else:
+ # The error was redirected to a logfile with `write_logfile=True`,
+ # so read the error from that file instead
+ self.logfile.seek(0)
+ ffplay_error = self.logfile.read()
+
+ error = (
+ f"{err}\n\nMoviePy error: FFPLAY encountered the following error while "
+ f":\n\n {ffplay_error}"
+ )
+
+ raise IOError(error)
+
+ def close(self):
+ """Closes the writer, terminating the subprocess if is still alive."""
+ if hasattr(self, "proc") and self.proc:
+ self.proc.stdin.close()
+ self.proc.stdin = None
+ if self.proc.stderr is not None:
+ self.proc.stderr.close()
+ self.proc.stderr = None
+ # If this causes deadlocks, consider terminating instead.
+ self.proc.wait()
+ self.proc = None
+
+ def __del__(self):
+ # If the garbage collector comes, make sure the subprocess is terminated.
+ self.close()
+
+ # Support the Context Manager protocol, to ensure that resources are cleaned up.
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+
+
+@requires_duration
+def ffmpeg_audiopreview(
+ clip,
+ fps=None,
+ buffersize=2000,
+ nbytes=2,
+ audio_flag=None,
+ video_flag=None
+):
+ """
+ A function that wraps the FFMPEG_AudioPreviewer to preview an AudioClip
+
+ Parameters
+ ----------
+
+ fps
+ Frame rate of the sound. 44100 gives top quality, but may cause
+ problems if your computer is not fast enough and your clip is
+ complicated. If the sound jumps during the preview, lower it
+ (11025 is still fine, 5000 is tolerable).
+
+ buffersize
+ The sound is not generated all at once, but rather made by bunches
+ of frames (chunks). ``buffersize`` is the size of such a chunk.
+ Try varying it if you meet audio problems (but you shouldn't
+ have to).
+
+ nbytes:
+ Number of bytes to encode the sound: 1 for 8bit sound, 2 for
+ 16bit, 4 for 32bit sound. 2 bytes is fine.
+
+ audio_flag, video_flag:
+ Instances of class threading events that are used to synchronize
+ video and audio during ``VideoClip.preview()``.
+ """
+ if not fps:
+ if not clip.fps:
+ fps = 44100
+ else:
+ fps = clip.fps
+
+ with FFMPEG_AudioPreviewer(
+ fps,
+ nbytes,
+ clip.nchannels
+ ) as previewer:
+
+
+ first_frame = True
+ for chunk in clip.iter_chunks(
+ chunksize=buffersize, quantize=True, nbytes=nbytes, fps=fps
+ ):
+ # On first frame, wait for video
+ if first_frame :
+ first_frame = False
+
+ if audio_flag is not None:
+ audio_flag.set() # Say to video that audio is ready
+
+ if video_flag is not None:
+ video_flag.wait() # Wait for video to be ready
+
+ previewer.write_frames(chunk)
\ No newline at end of file
diff --git a/moviepy/audio/io/ffmpeg_audiowriter.py b/moviepy/audio/io/ffmpeg_audiowriter.py
index 60c2de50..db8c808d 100644
--- a/moviepy/audio/io/ffmpeg_audiowriter.py
+++ b/moviepy/audio/io/ffmpeg_audiowriter.py
@@ -91,7 +91,7 @@ class FFMPEG_AudioWriter:
self.proc = sp.Popen(cmd, **popen_params)
def write_frames(self, frames_array):
- """TODO: add documentation"""
+ """Send the audio frame (a chunck of ``AudioClip``) to ffmpeg for writting"""
try:
self.proc.stdin.write(frames_array.tobytes())
except IOError as err:
diff --git a/moviepy/audio/io/preview.py b/moviepy/audio/io/preview.py
deleted file mode 100644
index 662cf43c..00000000
--- a/moviepy/audio/io/preview.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""Audio preview functions for MoviePy editor."""
-
-import time
-
-import numpy as np
-import pygame as pg
-
-from moviepy.decorators import requires_duration
-
-
-pg.init()
-pg.display.set_caption("MoviePy")
-
-
-@requires_duration
-def preview(
- clip, fps=22050, buffersize=4000, nbytes=2, audio_flag=None, video_flag=None
-):
- """
- Plays the sound clip with pygame.
-
- Parameters
- ----------
-
- fps
- Frame rate of the sound. 44100 gives top quality, but may cause
- problems if your computer is not fast enough and your clip is
- complicated. If the sound jumps during the preview, lower it
- (11025 is still fine, 5000 is tolerable).
-
- buffersize
- The sound is not generated all at once, but rather made by bunches
- of frames (chunks). ``buffersize`` is the size of such a chunk.
- Try varying it if you meet audio problems (but you shouldn't
- have to).
-
- nbytes:
- Number of bytes to encode the sound: 1 for 8bit sound, 2 for
- 16bit, 4 for 32bit sound. 2 bytes is fine.
-
- audio_flag, video_flag:
- Instances of class threading events that are used to synchronize
- video and audio during ``VideoClip.preview()``.
-
- """
- pg.mixer.quit()
-
- pg.mixer.init(fps, -8 * nbytes, clip.nchannels, 1024)
- totalsize = int(fps * clip.duration)
- pospos = np.array(list(range(0, totalsize, buffersize)) + [totalsize])
- timings = (1.0 / fps) * np.arange(pospos[0], pospos[1])
- sndarray = clip.to_soundarray(timings, nbytes=nbytes, quantize=True)
- chunk = pg.sndarray.make_sound(sndarray)
-
- if (audio_flag is not None) and (video_flag is not None):
- audio_flag.set()
- video_flag.wait()
-
- channel = chunk.play()
- for i in range(1, len(pospos) - 1):
- timings = (1.0 / fps) * np.arange(pospos[i], pospos[i + 1])
- sndarray = clip.to_soundarray(timings, nbytes=nbytes, quantize=True)
- chunk = pg.sndarray.make_sound(sndarray)
- while channel.get_queue():
- time.sleep(0.003)
- if video_flag is not None:
- if not video_flag.is_set():
- channel.stop()
- del channel
- return
- channel.queue(chunk)
diff --git a/moviepy/audio/io/readers.py b/moviepy/audio/io/readers.py
index 4f60efb4..309469e3 100644
--- a/moviepy/audio/io/readers.py
+++ b/moviepy/audio/io/readers.py
@@ -122,13 +122,34 @@ class FFMPEG_AudioReader:
self.pos = np.round(self.fps * start_time)
def skip_chunk(self, chunksize):
- """TODO: add documentation"""
+ """
+ This method skips a chunk of audio data by reading and discarding the specified number of frames from the audio stream.
+ The audio stream is read from the `proc` stdout. After skipping the chunk, the `pos` attribute is updated accordingly.
+
+ Parameters
+ -----------
+
+ chunksize (int): The number of audio frames to skip.
+
+ """
_ = self.proc.stdout.read(self.nchannels * chunksize * self.nbytes)
self.proc.stdout.flush()
self.pos = self.pos + chunksize
def read_chunk(self, chunksize):
- """TODO: add documentation"""
+ """
+ Reads a chunk of audio data from the audio stream.
+
+ This method reads a chunk of audio data from the audio stream. The specified number of frames, given by `chunksize`,
+ is read from the `proc` stdout. The audio data is returned as a NumPy array, where each row corresponds to a frame and
+ each column corresponds to a channel. If there is not enough audio left to read, the remaining portion is padded with
+ zeros, ensuring that the returned array has the desired length. The `pos` attribute is updated accordingly.
+
+ Parameters:
+ ------------
+ chunksize (float): The desired number of audio frames to read.
+
+ """
# chunksize is not being autoconverted from float to int
chunksize = int(round(chunksize))
s = self.proc.stdout.read(self.nchannels * chunksize * self.nbytes)
@@ -166,66 +187,74 @@ class FFMPEG_AudioReader:
# last case standing: pos = current pos
self.pos = pos
- def get_frame(self, tt):
- """TODO: add documentation"""
- 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)
-
- # Check that the requested time is in the valid range
- if not in_time.any():
- raise IOError(
- "Error in file %s, " % (self.filename)
- + "Accessing time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])
- + "with clip duration=%f seconds, " % 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)):
- self.buffer_around(fr_min)
- elif not (0 <= (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
- result[in_time] = self.buffer[indices]
- return result
-
- except IndexError as error:
- warnings.warn(
- "Error in file %s, " % (self.filename)
- + "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),
- UserWarning,
- )
-
- # repeat the last frame instead
- indices[indices >= len(self.buffer)] = len(self.buffer) - 1
- result[in_time] = self.buffer[indices]
- return result
+ def get_frame(self, tt):
+ """Retrieves the audio frame(s) corresponding to the given timestamp(s).
+
+ Parameters
+ -----------
+
+ tt (float or numpy.ndarray): The timestamp(s) at which to retrieve the audio frame(s).
+ If `tt` is a single float value, the frame corresponding to that timestamp is returned.
+ If `tt` is a NumPy array of timestamps, an array of frames corresponding to each timestamp is returned.
+ """
+ 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)
+
+ # Check that the requested time is in the valid range
+ if not in_time.any():
+ raise IOError(
+ "Error in file %s, " % (self.filename)
+ + "Accessing time t=%.02f-%.02f seconds, " % (tt[0], tt[-1])
+ + "with clip duration=%f seconds, " % 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)):
+ self.buffer_around(fr_min)
+ elif not (0 <= (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
+ result[in_time] = self.buffer[indices]
+ return result
+
+ except IndexError as error:
+ warnings.warn(
+ "Error in file %s, " % (self.filename)
+ + "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),
+ UserWarning,
+ )
+
+ # repeat the last frame instead
+ indices[indices >= len(self.buffer)] = len(self.buffer) - 1
+ result[in_time] = self.buffer[indices]
+ return result
- else:
- ind = int(self.fps * tt)
- if ind < 0 or ind > self.n_frames: # out of time: return 0
- return np.zeros(self.nchannels)
+ else:
+ ind = int(self.fps * tt)
+ if ind < 0 or ind > self.n_frames: # 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)
+ 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]
+ # read the frame in the buffer
+ return self.buffer[ind - self.buffer_startframe]
def buffer_around(self, frame_number):
"""
diff --git a/moviepy/config.py b/moviepy/config.py
index 251a80f3..d93b3b5e 100644
--- a/moviepy/config.py
+++ b/moviepy/config.py
@@ -19,12 +19,13 @@ except ImportError:
DOTENV = None
FFMPEG_BINARY = os.getenv("FFMPEG_BINARY", "ffmpeg-imageio")
+FFPLAY_BINARY = os.getenv("FFPLAY_BINARY", "auto-detect")
IS_POSIX_OS = os.name == "posix"
def try_cmd(cmd):
- """TODO: add documentation"""
+ """Verify if the OS support command invocation as expected by moviepy"""
try:
popen_params = cross_platform_popen_params(
{"stdout": sp.PIPE, "stderr": sp.PIPE, "stdin": sp.DEVNULL}
@@ -55,6 +56,22 @@ else:
raise IOError(
f"{err} - The path specified for the ffmpeg binary might be wrong"
)
+
+
+if FFPLAY_BINARY == "auto-detect":
+ if try_cmd(["ffplay"])[0]:
+ FFPLAY_BINARY = "ffplay"
+ elif not IS_POSIX_OS and try_cmd(["ffplay.exe"])[0]:
+ FFPLAY_BINARY = "ffplay.exe"
+ else: # pragma: no cover
+ FFPLAY_BINARY = "unset"
+else:
+ success, err = try_cmd([FFPLAY_BINARY])
+ if not success:
+ raise IOError(
+ f"{err} - The path specified for the ffmpeg binary might be wrong"
+ )
+
def check():
"""Check if moviepy has found the binaries for FFmpeg."""
@@ -63,6 +80,11 @@ def check():
else: # pragma: no cover
print(f"MoviePy: can't find or access ffmpeg in '{FFMPEG_BINARY}'.")
+ if try_cmd([FFPLAY_BINARY])[0]:
+ print(f"MoviePy: ffmpeg successfully found in '{FFPLAY_BINARY}'.")
+ else: # pragma: no cover
+ print(f"MoviePy: can't find or access ffmpeg in '{FFPLAY_BINARY}'.")
+
if DOTENV:
print(f"\n.env file content at {DOTENV}:\n")
print(Path(DOTENV).read_text())
diff --git a/moviepy/editor.py b/moviepy/editor.py
index 92b5fd78..adf0547a 100644
--- a/moviepy/editor.py
+++ b/moviepy/editor.py
@@ -17,6 +17,7 @@ from moviepy import *
from moviepy.video.io.html_tools import ipython_display
+
try:
from moviepy.video.io.sliders import sliders
except ImportError:
@@ -40,7 +41,7 @@ os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
# Add methods preview and show (only if pygame installed)
try:
- from moviepy.video.io.preview import preview, show
+ from moviepy.video.io.preview import show, preview
except ImportError:
def preview(self, *args, **kwargs):
@@ -56,7 +57,7 @@ VideoClip.preview = preview
VideoClip.show = show
try:
- from moviepy.audio.io.preview import preview
+ from moviepy.audio.io.ffmpeg_audiopreviewer import ffmpeg_audiopreview
except ImportError:
def preview(self, *args, **kwargs):
@@ -64,8 +65,8 @@ except ImportError:
raise ImportError("clip.preview requires Pygame installed")
-AudioClip.preview = preview
+AudioClip.preview = ffmpeg_audiopreview
__all__ = moviepy.__all__ + ["ipython_display", "sliders"]
-del preview, show
+del show, preview, ffmpeg_audiopreview
diff --git a/moviepy/video/VideoClip.py b/moviepy/video/VideoClip.py
index 02a0c06c..4af8051f 100644
--- a/moviepy/video/VideoClip.py
+++ b/moviepy/video/VideoClip.py
@@ -560,7 +560,23 @@ class VideoClip(Clip):
# C O M P O S I T I N G
def fill_array(self, pre_array, shape=(0, 0)):
- """TODO: needs documentation."""
+ """Fills an array to match the specified shape.
+
+ If the `pre_array` is smaller than the desired shape, the missing rows or columns are added with ones to the bottom or right,
+ respectively, until the shape matches. If the `pre_array` is larger than the desired shape, the excess rows or columns are cropped
+ from the bottom or right, respectively, until the shape matches.
+
+ The resulting array with the filled shape is returned.
+
+ Parameters
+ ------------
+ pre_array (numpy.ndarray)
+ The original array to be filled.
+
+ shape (tuple)
+ The desired shape of the resulting array.
+
+ """
pre_shape = pre_array.shape
dx = shape[0] - pre_shape[0]
dy = shape[1] - pre_shape[1]
@@ -964,7 +980,6 @@ class UpdatedVideoClip(VideoClip):
self.world = world
def make_frame(t):
- print(t)
while self.world.clip_t < t:
world.update()
return world.to_frame()
diff --git a/moviepy/video/io/ffmpeg_previewer.py b/moviepy/video/io/ffmpeg_previewer.py
new file mode 100644
index 00000000..ad8dfe56
--- /dev/null
+++ b/moviepy/video/io/ffmpeg_previewer.py
@@ -0,0 +1,155 @@
+"""
+On the long term this will implement several methods to make videos
+out of VideoClips
+"""
+
+import subprocess as sp
+
+import numpy as np
+from proglog import proglog
+
+from moviepy.config import FFMPEG_BINARY, FFPLAY_BINARY
+from moviepy.tools import cross_platform_popen_params
+
+
+class FFMPEG_VideoPreviewer:
+ """A class for FFMPEG-based (ffplay) video preview.
+
+ Parameters
+ ----------
+
+ size : tuple or list
+ Size of the output video in pixels (width, height).
+
+ fps : int
+ Frames per second in the output video file.
+
+ pixel_format : str
+ Pixel format for the output video file, ``rgb24`` for normal video, ``rgba``
+ if video with mask.
+ """
+
+ def __init__(
+ self,
+ size,
+ fps,
+ pixel_format,
+ ):
+ # order is important
+ cmd = [
+ FFPLAY_BINARY,
+ "-autoexit", # If you dont precise, ffplay dont stop at end
+ "-f",
+ "rawvideo",
+ "-pixel_format",
+ pixel_format,
+ "-video_size",
+ "%dx%d" % (size[0], size[1]),
+ "-framerate",
+ "%.02f" % fps,
+ "-",
+ ]
+
+ popen_params = cross_platform_popen_params(
+ {"stdout": sp.DEVNULL, "stderr": sp.STDOUT, "stdin": sp.PIPE}
+ )
+
+ self.proc = sp.Popen(cmd, **popen_params)
+
+ def show_frame(self, img_array):
+ """Writes one frame in the file."""
+ try:
+ self.proc.stdin.write(img_array.tobytes())
+ except IOError as err:
+ _, ffplay_error = self.proc.communicate()
+ if ffplay_error is not None:
+ ffplay_error = ffplay_error.decode()
+
+ error = (
+ f"{err}\n\nMoviePy error: FFPALY encountered the following error while "
+ f"previewing clip :\n\n {ffplay_error}"
+ )
+
+ raise IOError(error)
+
+ def close(self):
+ """Closes the writer, terminating the subprocess if is still alive."""
+ if self.proc:
+ self.proc.stdin.close()
+ if self.proc.stderr is not None:
+ self.proc.stderr.close()
+ self.proc.wait()
+
+ self.proc = None
+
+ # Support the Context Manager protocol, to ensure that resources are cleaned up.
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+
+
+def ffmpeg_preview_video(
+ clip,
+ fps,
+ pixel_format=None,
+ audio_flag=None,
+ video_flag=None
+):
+ """Preview the clip using ffplay. See VideoClip.preview for details
+ on the parameters.
+
+ Parameters
+ ----------
+
+ clip : VideoClip
+ The clip to preview
+
+ fps : int
+ Number of frames per seconds in the displayed video.
+
+ pixel_format : str, optional
+ Pixel format for the output video file, ``rgb24`` for normal video, ``rgba``
+ if video with mask.
+
+ audio_flag : Thread.Event, optional
+ A thread event that video will wait for. If not provided we ignore audio
+
+ video_flag : Thread.Event, optional
+ A thread event that video will set after first frame has been shown. If not
+ provided, we simply ignore
+ """
+ if not pixel_format:
+ pixel_format = "rgba" if clip.mask is not None else "rgb24"
+
+
+ with FFMPEG_VideoPreviewer(
+ clip.size,
+ fps,
+ pixel_format
+ ) as previewer:
+ first_frame = True
+ for t, frame in clip.iter_frames(
+ with_times=True, fps=fps, dtype="uint8"
+ ):
+ if clip.mask is not None:
+ mask = 255 * clip.mask.get_frame(t)
+ if mask.dtype != "uint8":
+ mask = mask.astype("uint8")
+ frame = np.dstack([frame, mask])
+
+ previewer.show_frame(frame)
+
+ # After first frame is shown, if we have audio/video flag, set video ready and wait for audio
+ if first_frame :
+ first_frame = False
+
+ if video_flag :
+ video_flag.set() # say to the audio: video is ready
+
+ if audio_flag :
+ audio_flag.wait() # wait for the audio to be ready
+
+
diff --git a/moviepy/video/io/preview.py b/moviepy/video/io/preview.py
index c936726f..f0b3b99f 100644
--- a/moviepy/video/io/preview.py
+++ b/moviepy/video/io/preview.py
@@ -2,9 +2,8 @@
import threading
import time
-
import numpy as np
-import pygame as pg
+from PIL import Image
from moviepy.decorators import (
convert_masks_to_RGB,
@@ -13,23 +12,12 @@ from moviepy.decorators import (
)
from moviepy.video.compositing.CompositeVideoClip import CompositeVideoClip
-
-pg.init()
-pg.display.set_caption("MoviePy")
-
-
-def imdisplay(imarray, screen=None):
- """Splashes the given image array on the given pygame screen."""
- a = pg.surfarray.make_surface(imarray.swapaxes(0, 1))
- if screen is None:
- screen = pg.display.set_mode(imarray.shape[:2][::-1])
- screen.blit(a, (0, 0))
- pg.display.flip()
+from moviepy.video.io.ffmpeg_previewer import ffmpeg_preview_video
@convert_masks_to_RGB
@convert_parameter_to_seconds(["t"])
-def show(clip, t=0, with_mask=True, interactive=False):
+def show(clip, t=0, with_mask=True):
"""
Splashes the frame of clip corresponding to time ``t``.
@@ -43,10 +31,6 @@ def show(clip, t=0, with_mask=True, interactive=False):
``False`` if the clip has a mask but you want to see the clip without
the mask.
- interactive : bool, optional
- Displays the image freezed and you can clip in each pixel to see the
- pixel number and its color.
-
Examples
--------
@@ -59,22 +43,9 @@ def show(clip, t=0, with_mask=True, interactive=False):
clip = CompositeVideoClip([clip.with_position((0, 0))])
img = clip.get_frame(t)
- imdisplay(img)
-
- if interactive:
- result = []
- while True:
- for event in pg.event.get():
- if event.type == pg.KEYDOWN:
- if event.key == pg.K_ESCAPE:
- print("Keyboard interrupt")
- return result
- elif event.type == pg.MOUSEBUTTONDOWN:
- x, y = pg.mouse.get_pos()
- rgb = img[y, x]
- result.append({"position": (x, y), "color": rgb})
- print("position, color : ", "%s, %s" % (str((x, y)), str(rgb)))
- time.sleep(0.03)
+ pil_img = Image.fromarray(img)
+
+ pil_img.show()
@requires_duration
@@ -85,8 +56,7 @@ def preview(
audio=True,
audio_fps=22050,
audio_buffersize=3000,
- audio_nbytes=2,
- fullscreen=False,
+ audio_nbytes=2
):
"""
Displays the clip in a window, at the given frames per second (of movie)
@@ -98,7 +68,7 @@ def preview(
----------
fps : int, optional
- Number of frames per seconds in the displayed video.
+ Number of frames per seconds in the displayed video. Default to ``15``.
audio : bool, optional
``True`` (default) if you want the clip's audio be played during
@@ -113,9 +83,6 @@ def preview(
audio_nbytes : int, optional
The number of bytes used generating the audio sound.
- fullscreen : bool, optional
- ``True`` if you want the preview to be displayed fullscreen.
-
Examples
--------
@@ -124,20 +91,15 @@ def preview(
>>> clip = VideoFileClip("media/chaplin.mp4")
>>> clip.preview(fps=10, audio=False)
"""
- if fullscreen:
- flags = pg.FULLSCREEN
- else:
- flags = 0
-
- # compute and splash the first image
- screen = pg.display.set_mode(clip.size, flags)
audio = audio and (clip.audio is not None)
+ audio_flag = None
+ video_flag = None
if audio:
# the sound will be played in parallel. We are not
# parralellizing it on different CPUs because it seems that
- # pygame and openCV already use several cpus it seems.
+ # ffplay use several cpus.
# two synchro-flags to tell whether audio and video are ready
video_flag = threading.Event()
@@ -149,39 +111,5 @@ def preview(
)
audiothread.start()
- img = clip.get_frame(0)
- imdisplay(img, screen)
- if audio: # synchronize with audio
- video_flag.set() # say to the audio: video is ready
- audio_flag.wait() # wait for the audio to be ready
-
- result = []
-
- t0 = time.time()
- for t in np.arange(1.0 / fps, clip.duration - 0.001, 1.0 / fps):
- img = clip.get_frame(t)
-
- for event in pg.event.get():
- if event.type == pg.QUIT or (
- event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE
- ):
- if audio:
- video_flag.clear()
- print("Interrupt")
- pg.quit()
- return result
-
- elif event.type == pg.MOUSEBUTTONDOWN:
- x, y = pg.mouse.get_pos()
- rgb = img[y, x]
- result.append({"time": t, "position": (x, y), "color": rgb})
- print(
- "time, position, color : ",
- "%.03f, %s, %s" % (t, str((x, y)), str(rgb)),
- )
-
- t1 = time.time()
- time.sleep(max(0, t - (t1 - t0)))
- imdisplay(img, screen)
-
- pg.quit()
+ # passthrough to ffmpeg, passing flag for ffmpeg to set
+ ffmpeg_preview_video(clip=clip, fps=fps, audio_flag=audio_flag, video_flag=video_flag)