ffmpeg-python
The `ffmpeg` Python package (often referred to as `ffmpeg-python`) provides a lightweight, fluent Python wrapper for the `ffmpeg` command-line tool. It enables programmatic construction of `ffmpeg` commands, management of audio/video streams, application of filters, and format conversions. It currently stands at version 1.4, with its release cadence tied to upstream `ffmpeg` tool features and community contributions.
Warnings
- gotcha The Python `ffmpeg` package is merely a wrapper. The actual `ffmpeg` command-line executable must be installed separately on your system (e.g., via `apt`, `brew`, `choco`, or by downloading binaries) and be available in your system's PATH for the Python library to function.
- gotcha Operations involving the `ffmpeg` CLI tool can fail for various reasons (e.g., invalid input, missing codecs, file permissions). Always wrap `ffmpeg.run()` calls in a `try-except` block to catch `ffmpeg.Error` and inspect `e.stderr` for detailed diagnostic information.
- gotcha By default, `ffmpeg` processes files on disk. For handling raw byte data in memory (e.g., from NumPy arrays, OpenCV), you must explicitly use `pipe_input=True` and/or `pipe_output=True` in your input/output nodes, and pass `capture_stdout=True`, `capture_stderr=True` (or `stdout=subprocess.PIPE` directly) to `ffmpeg.run()` to manage data streams.
- gotcha The `ffmpeg.run()` function is blocking, meaning your Python script will pause until the `ffmpeg` process completes. For long-running video processing tasks in applications that need to remain responsive, consider executing `ffmpeg.run_async()` for non-blocking execution or offloading the operation to a separate thread or background process.
Install
-
pip install ffmpeg
Imports
- ffmpeg
import ffmpeg
Quickstart
import ffmpeg
import os
# This quickstart demonstrates compiling an ffmpeg command.
# To actually run it, you would need 'input.mp4' to exist
# and the ffmpeg CLI tool to be installed and in your PATH.
# For full execution, replace 'input.mp4' with an actual file
# and remove the '.compile()' to use '.run()'.
# Example: Generate an ffmpeg command to re-encode a video
# without actually running it, useful for inspection.
command_list = (
ffmpeg.input('input.mp4')
.output('output_resized.mp4', vf='scale=1280:-1')
.compile()
)
print(f"Generated ffmpeg command: {' '.join(command_list)}")
# Example: Probe a (potentially non-existent) file to get its metadata
# For this to run successfully, 'input.mp4' would need to exist
# and the ffmpeg CLI tool must be installed.
# try:
# probe_info = ffmpeg.probe('input.mp4')
# print("Probe information:")
# print(probe_info)
# except ffmpeg.Error as e:
# print(f"Error probing file: {e.stderr.decode()}")