### Install ffmpeg-python from source Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Shows how to install ffmpeg-python by cloning the source repository and then performing a local pip installation. This is useful for development or when needing to work with the latest unreleased changes. ```bash git clone git@github.com:kkroening/ffmpeg-python.git pip install -e ./ffmpeg-python ``` -------------------------------- ### Run and capture ffmpeg output example Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html This example demonstrates how to run an ffmpeg command and capture its standard output and error streams using `run_async`. The output is piped and then read using `communicate()`, returning the captured data. ```python process = ( ffmpeg .input(in_filename) .output('pipe:', format='rawvideo', pix_fmt='rgb24') .run_async(pipe_stdout=True, pipe_stderr=True) ) out, err = process.communicate() ``` -------------------------------- ### Check FFmpeg installation Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Demonstrates how to verify if FFmpeg is installed and accessible in your system's PATH. Running the 'ffmpeg' command should display its version information, confirming a successful installation. ```bash $ ffmpeg ffmpeg version 4.2.4-1ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-10ubuntu2) ``` -------------------------------- ### Get Video Info using ffprobe with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Retrieves detailed information about a video file using ffprobe via the ffmpeg-python library. It parses the probe data to extract video stream details like width and height. Requires ffmpeg and ffprobe to be installed and accessible. ```python probe = ffmpeg.probe(args.in_filename) video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None) width = int(video_stream['width']) height = int(video_stream['height']) ``` -------------------------------- ### Mono to Stereo Audio with Video Overlay using ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Combines two mono audio streams into a stereo stream with specified offsets and overlays it onto a video stream. This example uses 'atrim' and 'asetpts' for audio manipulation and 'join' for stereo creation, then merges with video, outputting to 'output-video.mp4'. ```python audio_left = (ffmpeg.input('audio-left.wav').filter('atrim', start=5).filter('asetpts', 'PTS-STARTPTS')) audio_right = (ffmpeg.input('audio-right.wav').filter('atrim', start=10).filter('asetpts', 'PTS-STARTPTS')) input_video = ffmpeg.input('input-video.mp4') (ffmpeg.filter((audio_left, audio_right), 'join', inputs=2, channel_layout='stereo').output(input_video.video, 'output-video.mp4', shortest=None, vcodec='copy').overwrite_output().run()) ``` -------------------------------- ### Run ffmpeg with piped input example Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html This example shows how to run an ffmpeg command that accepts piped input. The `run_async` function is used with `pipe_stdin=True`, allowing raw video data to be sent to ffmpeg's stdin via `process.communicate(input=input_data)`. ```python process = ( ffmpeg .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height)) .output(out_filename, pix_fmt='yuv420p') .overwrite_output() .run_async(pipe_stdin=True) ) process.communicate(input=input_data) ``` -------------------------------- ### Audio/Video Pipeline Construction with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Demonstrates building a complex audio-video processing pipeline by concatenating and filtering multiple input streams. This example shows how to flip video, reverse audio, apply hue and phaser filters, join streams, adjust volume, and output a final file. It uses ffmpeg.concat for stream merging. ```python in1 = ffmpeg.input('in1.mp4') in2 = ffmpeg.input('in2.mp4') v1 = in1.video.hflip() a1 = in1.audio v2 = in2.video.filter('reverse').filter('hue', s=0) a2 = in2.audio.filter('areverse').filter('aphaser') joined = ffmpeg.concat(v1, a1, v2, a2, v=1, a=1).node v3 = joined[0] a3 = joined[1].filter('volume', 0.8) out = ffmpeg.output(v3, a3, 'out.mp4') out.run() ``` -------------------------------- ### Generate Video Thumbnail with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Creates a thumbnail image from a specific point in a video file using ffmpeg-python. The example specifies the input file, a timestamp, scaling, and the output file. It's useful for previewing video content. ```python (ffmpeg.input(in_filename, ss=time).filter('scale', width, -1).output(out_filename, vframes=1).run()) ``` -------------------------------- ### Install ffmpeg-python using pip Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Provides the command to install the ffmpeg-python library using pip. This is the standard method for adding the library to your Python environment. ```bash pip install ffmpeg-python ``` -------------------------------- ### Assemble Video with Filtering using ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Assembles a video from image frames while applying multiple filters. This example demonstrates 'deflicker' and 'scale' filters, along with advanced output options like CRF, preset, and pixel format. It also includes a .view() call for debugging the filter graph. ```python (ffmpeg.input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25).filter('deflicker', mode='pm', size=10).filter('scale', size='hd1080', force_original_aspect_ratio='increase').output('movie.mp4', crf=20, preset='slower', movflags='faststart', pix_fmt='yuv420p').view(filename='filter_graph').run()) ``` -------------------------------- ### Asynchronous ffmpeg stream processing example Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html This example demonstrates processing video frames in real-time using `run_async`. It reads frames from an input file, processes them using numpy, and writes the modified frames to an output file, showcasing pipe-based communication between ffmpeg processes. ```python process1 = ( ffmpeg .input(in_filename) .output('pipe:', format='rawvideo', pix_fmt='rgb24') .run_async(pipe_stdout=True) ) process2 = ( ffmpeg .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height)) .output(out_filename, pix_fmt='yuv420p') .overwrite_output() .run_async(pipe_stdin=True) ) while True: in_bytes = process1.stdout.read(width * height * 3) if not in_bytes: break in_frame = ( np .frombuffer(in_bytes, np.uint8) .reshape([height, width, 3]) ) out_frame = in_frame * 0.3 process2.stdin.write( frame .astype(np.uint8) .tobytes() ) process2.stdin.close() process1.wait() process2.wait() ``` -------------------------------- ### FaceTime Webcam Capture with ffmpeg-python (OS X) Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md This example captures video directly from the FaceTime camera on OS X using ffmpeg-python. It specifies the 'avfoundation' input format, a desired framerate, and outputs to a file named 'out.mp4' with yuv420p pixel format. The capture is limited to 100 frames. Dependencies include ffmpeg-python and the ffmpeg backend. ```python ( ffmpeg .input('FaceTime', format='avfoundation', pix_fmt='uyvy422', framerate=30) .output('out.mp4', pix_fmt='yuv420p', vframes=100) .run() ) ``` -------------------------------- ### Assemble Video from Sequence of Frames with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Creates a video file from a sequence of image frames (e.g., JPEGs) located in a directory. It supports glob patterns for selecting frames and allows setting framerate. Basic output is to 'movie.mp4'. ```python (ffmpeg.input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25).output('movie.mp4').run()) ``` -------------------------------- ### Import Libraries for ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/ffmpeg-numpy.ipynb Imports necessary libraries for video processing and visualization, including ffmpeg, matplotlib, ipywidgets, and numpy. These libraries are essential for the subsequent operations. ```python from ipywidgets import interact from matplotlib import pyplot as plt import ffmpeg import ipywidgets as widgets import numpy as np ``` -------------------------------- ### Running ffmpeg-python Tests Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md This snippet provides the bash commands necessary to clone the ffmpeg-python repository, set up a virtual environment, install development dependencies, and execute the test suite using pytest. It covers both macOS/Linux and Windows activation commands for the virtual environment. ```bash git clone git@github.com:kkroening/ffmpeg-python.git cd ffmpeg-python virtualenv venv . venv/bin/activate # (OS X / Linux) virtualenv venv . venv/bin/activate # (Windows) pip install -e .[dev] pytest ``` -------------------------------- ### Create Timelapse Video from Photos (Python) Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to generate a 4K timelapse video from a directory of JPG images. It sets a high framerate and uses the libx265 codec for efficient compression. This is suitable for creating high-resolution timelapse videos. ```python import ffmpeg (ffmpeg.input('timelapse/*.jpg', pattern_type='glob', framerate=60) .filter('scale', 3840, 2160) .output('timelapse_4k.mp4', vcodec='libx265', crf=18, preset='slow') .run()) ``` -------------------------------- ### Stream from RTSP Server to TCP Socket with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md This example reads a video stream from an RTSP server and forwards it over a TCP socket. It uses ffmpeg-python to capture from the RTSP URL and output in H.264 format to stdout, which is then read in chunks and sent over a TCP socket. The loop breaks if a socket error occurs. Dependencies include ffmpeg-python, socket, and potentially a pre-established tcp_socket object. ```python packet_size = 4096 process = ( ffmpeg .input('rtsp://%s:8554/default') .output('-', format='h264') .run_async(pipe_stdout=True) ) while process.poll() is None: packet = process.stdout.read(packet_size) try: tcp_socket.send(packet) except socket.error: process.stdout.close() process.wait() break ``` -------------------------------- ### Python: Video Filters and Transformations with FFmpeg Source: https://context7.com/kkroening/ffmpeg-python/llms.txt Shows how to apply various video filters and transformations using ffmpeg-python. Examples include horizontal and vertical flipping, scaling video to specific dimensions, and preserving aspect ratio during scaling. ```python import ffmpeg # Horizontal and vertical flip ( ffmpeg .input('input.mp4') .hflip() .output('flipped_h.mp4') .run() ) ( ``` -------------------------------- ### Probe Video Information with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/ffmpeg-numpy.ipynb Extracts detailed information about a video file, such as width, height, and number of frames, using ffmpeg.probe. This information is crucial for subsequent frame manipulation and display. ```python probe = ffmpeg.probe('in.mp4') video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video') width = int(video_info['width']) height = int(video_info['height']) num_frames = int(video_info['nb_frames']) ``` -------------------------------- ### Build Video Processing Graph with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/ffmpeg-numpy.ipynb Constructs a video processing graph that can optionally apply an overlay (with horizontal flip) and draw a colored box on the video. This function returns an ffmpeg stream object representing the processing pipeline. ```python def build_graph( enable_overlay, flip_overlay, enable_box, box_x, box_y, thickness, color): stream = ffmpeg.input('in.mp4') if enable_overlay: overlay = ffmpeg.input('overlay.png') if flip_overlay: overlay = overlay.hflip() stream = stream.overlay(overlay) if enable_box: stream = stream.drawbox( box_x, box_y, 120, 120, color=color, t=thickness) return stream.output('out.mp4') ``` -------------------------------- ### Async Execution with Process Control using ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt Runs an FFmpeg process asynchronously, allowing the Python script to continue executing while FFmpeg operates in the background. This example demonstrates setting up an asynchronous output process and capturing stderr. ```python import subprocess process = ( ffmpeg .input('input.mp4') .output('output.mp4', vcodec='libx264') .overwrite_output() .run_async(pipe_stderr=True) ) # The process runs in the background. You can interact with it further if needed. # For example, to wait for completion: # process.wait() ``` -------------------------------- ### Adjust Hue and Saturation with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to modify the hue and saturation of a video using the .hue() method. The parameters for hue can be dynamic based on time. The adjusted video is saved as 'hue_adjusted.mp4'. ```python ( ffmpeg .input('input.mp4') .hue(h='sin(2*PI*t)*180', s=1.5) .output('hue_adjusted.mp4') .run() ) ``` -------------------------------- ### Batch Video Format Conversion with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example demonstrates converting a single input video file ('source.mp4') into multiple output formats (WebM, MP4, AVI) with specified video codecs. It utilizes a dictionary to map extensions to codecs and then merges the outputs into a single operation. ```python import ffmpeg formats = {'webm': 'libvpx', 'mp4': 'libx264', 'avi': 'mpeg4'} input_file = ffmpeg.input('source.mp4') outputs = [] for ext, codec in formats.items(): output = ffmpeg.output(input_file, f'output.{ext}', vcodec=codec) outputs.append(output) fmpeg.merge_outputs(*outputs).run() ``` -------------------------------- ### Stream Local Video to HTTP Server with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md This snippet streams a local video file ('input.mp4') to an HTTP server. It uses the 'copy' codec to avoid re-encoding, enabling HTTP listening and specifying the FLV format. The '-re' global argument simulates a live stream. The output is directed to a specified server URL. A separate ffplay command is provided to receive the stream. ```python video_format = "flv" server_url = "http://127.0.0.1:8080" process = ( ffmpeg .input("input.mp4") .output( server_url, codec = "copy", # use same codecs of the original video listen=1, # enables HTTP server f=video_format) .global_args("-re") # argument to act as a live stream .run() ) ``` -------------------------------- ### Inspect FFmpeg Command Arguments Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to retrieve the FFmpeg command-line arguments generated by ffmpeg-python without executing them. The `get_args()` method returns a list of arguments, while `compile()` provides the full command including the executable. This is invaluable for debugging and understanding the exact FFmpeg commands being constructed. ```python import ffmpeg # Get command-line arguments stream = ( ffmpeg .input('input.mp4') .filter('scale', 1920, 1080) .output('output.mp4', vcodec='libx264') ) args = stream.get_args() print("FFmpeg arguments:", args) # Get full command including executable cmd = stream.compile() print("Full command:", ' '.join(cmd)) ``` -------------------------------- ### Select Specific Stream by Index with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to select specific streams from a multi-stream media file (e.g., MKV) by their index using dictionary-like access (e.g., 'v:0', 'a:1'). It demonstrates selecting video, audio, and subtitle streams. ```python input_file = ffmpeg.input('multi_stream.mkv') video_stream_0 = input_file['v:0'] # First video stream audio_stream_1 = input_file['a:1'] # Second audio stream subtitle = input_file['s:0'] # First subtitle stream ``` -------------------------------- ### Read Single Video Frame as JPEG with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Extracts a specific frame from a video file and encodes it as a JPEG image, outputting it through a pipe. This is useful for frame-by-frame analysis or previewing. Requires ffmpeg. ```python out, _ = (ffmpeg.input(in_filename).filter('select', 'gte(n,{})'.format(frame_num)).output('pipe:', vframes=1, format='image2', vcodec='mjpeg').run(capture_stdout=True)) ``` -------------------------------- ### Apply Audio Effects with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to apply audio effects like 'aphaser' and 'areverse' to an audio file using chained .filter() calls. The processed audio is saved as 'effects.wav'. ```python ( ffmpeg .input('audio.wav') .filter('aphaser') # Phaser effect .filter('areverse') # Reverse audio .output('effects.wav') .run() ) ``` -------------------------------- ### Display Frame and Graph Visualization Interactively Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/ffmpeg-numpy.ipynb An interactive function that allows users to control various parameters like frame selection, overlay enabling/disabling, box drawing, and box properties. It displays the processed video frame alongside a visualization of the processing graph. ```python from io import BytesIO from PIL import Image def extract_frame(stream, frame_num): while isinstance(stream, ffmpeg.nodes.OutputStream): stream = stream.node.incoming_edges[0].upstream_node.stream() out, _ = ( stream .filter_('select', 'gte(n,{})'.format(frame_num)) .output('pipe:', format='rawvideo', pix_fmt='rgb24', vframes=1) .run(capture_stdout=True, capture_stderr=True) ) return np.frombuffer(out, np.uint8).reshape([height, width, 3]) def png_to_np(png_bytes): buffer = BytesIO(png_bytes) pil_image = Image.open(buffer) return np.array(pil_image) def build_graph( enable_overlay, flip_overlay, enable_box, box_x, box_y, thickness, color): stream = ffmpeg.input('in.mp4') if enable_overlay: overlay = ffmpeg.input('overlay.png') if flip_overlay: overlay = overlay.hflip() stream = stream.overlay(overlay) if enable_box: stream = stream.drawbox( box_x, box_y, 120, 120, color=color, t=thickness) return stream.output('out.mp4') def show_image(ax, stream, frame_num): try: image = extract_frame(stream, frame_num) ax.imshow(image) ax.axis('off') except ffmpeg.Error as e: print(e.stderr.decode()) def show_graph(ax, stream, detail): data = ffmpeg.view(stream, detail=detail, pipe=True) image = png_to_np(data) ax.imshow(image, aspect='equal', interpolation='hanning') ax.set_xlim(0, 1100) ax.axis('off') @interact( frame_num=(0, num_frames), box_x=(0, 200), box_y=(0, 200), thickness=(1, 40), color=['red', 'green', 'magenta', 'blue'], ) def f( enable_overlay=True, enable_box=True, flip_overlay=True, graph_detail=False, frame_num=0, box_x=50, box_y=50, thickness=5, color='red'): stream = build_graph( enable_overlay, flip_overlay, enable_box, box_x, box_y, thickness, color ) fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(15,4)) plt.tight_layout() show_image(ax0, stream, frame_num) show_graph(ax1, stream, graph_detail) ``` -------------------------------- ### Visualize FFmpeg Filter Graphs Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to visualize FFmpeg filter graphs generated by `ffmpeg-python`. The `view()` method can save the graph as a PNG file using Graphviz, optionally including detailed filter parameters. It can also return the graph data as bytes without saving a file, facilitating programmatic access to the visualization. ```python import ffmpeg stream = ( ffmpeg .input('input.mp4') .hflip() .filter('scale', 1920, 1080) .drawtext(text='Hello', x=10, y=10) .output('output.mp4') ) # Generate graph visualization as PNG stream.view(filename='filter_graph') # View with detailed filter parameters stream.view(filename='detailed_graph', detail=True) # Get graph as bytes without saving file graph_bytes = stream.view(pipe=True) ``` -------------------------------- ### Convert Sound to Raw PCM Audio with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Converts an audio file to raw PCM signed 16-bit little-endian audio format, outputting it to stdout. This is useful for transcribing audio or feeding it into other processing tools. Requires ffmpeg. ```python out, _ = (ffmpeg.input(in_filename, **input_kwargs).output('-', format='s16le', acodec='pcm_s16le', ac=1, ar='16k').overwrite_output().run(capture_stdout=True)) ``` -------------------------------- ### Trim Audio by Time with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to trim an audio file to a specific time range using the .filter('atrim', ...). It also resets audio timestamps with .filter('asetpts', 'PTS-STARTPTS'). The output is 'trimmed.wav'. ```python ( ffmpeg .input('audio.wav') .filter('atrim', start=5, end=30) .filter('asetpts', 'PTS-STARTPTS') .output('trimmed.wav') .run() ) ``` -------------------------------- ### Draw Colored Box on Video with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example demonstrates drawing a colored rectangle on a video using the .drawbox() method. You can specify the position, dimensions, color, and thickness of the box. The output video is named 'with_box.mp4'. ```python ( ffmpeg .input('input.mp4') .drawbox(x=50, y=50, width=200, height=100, color='red', thickness=3) .output('with_box.mp4') .run() ) ``` -------------------------------- ### Utilize Multi-Output Filters in ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Demonstrates the use of `filter_multi_output` for filters that generate multiple output streams, like 'split'. It also shows how to use the shorthand `.split()` method and how to process these multiple outputs, for example, by concatenating them in different ways. ```python split = ( ffmpeg .input('in.mp4') .filter_multi_output('split') # or `.split()` ) ( ffmpeg .concat(split[0], split[1].reverse()) .output('out.mp4') .run() ) ``` -------------------------------- ### Replace Audio Track with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to replace the audio track of a video file with a new audio file. It selects the video stream from the original video and the audio stream from a new audio file, then remuxes them into a new output file with specified codecs. ```python video_only = ffmpeg.input('video.mp4').video new_audio = ffmpeg.input('audio.mp3').audio ( ffmpeg .output(video_only, new_audio, 'output.mp4', vcodec='copy', acodec='aac') .run() ) ``` -------------------------------- ### Apply Custom Filter Graph with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example demonstrates applying a sequence of custom filters to a video stream using the .filter() method. It shows chaining 'crop' and 'fps' filters. The processed video is saved as 'custom_filtered.mp4'. ```python ( ffmpeg .input('input.mp4') .filter('crop', 'in_w-2*10', 'in_h-2*20') .filter('fps', fps=30, round='up') .output('custom_filtered.mp4') .run() ) ``` -------------------------------- ### Tensorflow Deep Dream Video Streaming with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md This snippet decodes an input video, processes each frame using a Tensorflow 'deep dream' model, and then encodes the processed frames into an output video. It utilizes two asynchronous ffmpeg processes for input and output, communicating via pipes. Dependencies include ffmpeg-python and numpy. Input is a video file, and output is a video file. This method is suitable for real-time AI-driven video effects. ```python process1 = ( ffmpeg .input(in_filename) .output('pipe:', format='rawvideo', pix_fmt='rgb24', vframes=8) .run_async(pipe_stdout=True) ) process2 = ( ffmpeg .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height)) .output(out_filename, pix_fmt='yuv420p') .overwrite_output() .run_async(pipe_stdin=True) ) while True: in_bytes = process1.stdout.read(width * height * 3) if not in_bytes: break in_frame = ( np .frombuffer(in_bytes, np.uint8) .reshape([height, width, 3]) ) # See examples/tensorflow_stream.py: out_frame = deep_dream.process_frame(in_frame) process2.stdin.write( out_frame .astype(np.uint8) .tobytes() ) process2.stdin.close() process1.wait() process2.wait() ``` -------------------------------- ### Batch Transcode Video Files Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example provides a Python script for batch transcoding multiple video files. It iterates through MP4 files in an input directory, processes each file using FFmpeg with specified codecs and quality settings (`libx264`, `crf=23`, `preset='medium'`), and saves the output to a designated directory. Error handling is included to report failures for individual files. ```python import ffmpeg import os from pathlib import Path from concurrent.futures import ThreadPoolExecutor, as_completed input_dir = Path('input_videos') output_dir = Path('output_videos') output_dir.mkdir(exist_ok=True) for video_file in input_dir.glob('*.mp4'): output_file = output_dir / video_file.name try: ( ffmpeg .input(str(video_file)) .output(str(output_file), vcodec='libx264', crf=23, preset='medium') .overwrite_output() .run(capture_stdout=True, capture_stderr=True) ) print(f"✓ Processed {video_file.name}") except ffmpeg.Error as e: print(f"✗ Failed {video_file.name}: {e.stderr.decode()}") ``` -------------------------------- ### Stream Input from Memory with FFmpeg Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example demonstrates how to stream input data directly from memory to FFmpeg. It reads the content of a local file into a byte string and then pipes this data to an FFmpeg process configured to read from stdin. This is useful for scenarios where the input video is generated or manipulated in memory before being processed by FFmpeg. ```python import ffmpeg input_data = open('video.mp4', 'rb').read() process = ( ffmpeg .input('pipe:', format='mp4') .output('output.mp4') .overwrite_output() .run_async(pipe_stdin=True, pipe_stderr=True) ) process.stdin.write(input_data) process.stdin.close() process.wait() ``` -------------------------------- ### Display Video Frames Interactively with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/ffmpeg-numpy.ipynb Reads raw video data from 'in.mp4', processes it into a NumPy array, and displays individual frames interactively using matplotlib and ipywidgets. Allows selection of specific frames via a slider. ```python out, err = ( ffmpeg .input('in.mp4') .output('pipe:', format='rawvideo', pix_fmt='rgb24') .run(capture_stdout=True) ) video = ( np .frombuffer(out, np.uint8) .reshape([-1, height, width, 3]) ) @interact(frame=(0, num_frames)) def show_frame(frame=0): plt.imshow(video[frame,:,:,:]) ``` -------------------------------- ### Convert Audio to Raw PCM with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example converts an audio file (MP3) to raw PCM signed 16-bit little-endian format, with specific channel count and sample rate, capturing the output to stdout. This is useful for further processing with other libraries. ```python out, err = ( ffmpeg .input('audio.mp3') .output('-', format='s16le', acodec='pcm_s16le', ac=1, ar='16k') .run(capture_stdout=True) ) ``` -------------------------------- ### Convert PNG Bytes to NumPy Array Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/ffmpeg-numpy.ipynb Provides a utility function to convert PNG image data from bytes into a NumPy array using Pillow (PIL). This is useful for processing image overlays or generated graphics. ```python from io import BytesIO from PIL import Image def png_to_np(png_bytes): buffer = BytesIO(png_bytes) pil_image = Image.open(buffer) return np.array(pil_image) ``` -------------------------------- ### Split Video Stream with Custom Count using ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to use .filter_multi_output('split', N) to split a video stream into a specified number (N) of output streams. Each resulting stream can then be independently processed before being output. ```python split3 = input_stream.video.filter_multi_output('split', 3) out1 = split3[0].hflip() out2 = split3[1].vflip() out3 = split3[2].filter('scale', 640, 480) ``` -------------------------------- ### Complex Filter Graph with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Illustrates how to create a complex FFmpeg filter graph using ffmpeg-python. This example chains multiple operations like trimming, concatenating, overlaying, and drawing a box, showcasing the library's ability to handle intricate signal processing pipelines in a readable Python format. ```python import ffmpeg in_file = ffmpeg.input('input.mp4') overlay_file = ffmpeg.input('overlay.png') ( ffmpeg .concat( in_file.trim(start_frame=10, end_frame=20), in_file.trim(start_frame=30, end_frame=40), ) .overlay(overlay_file.hflip()) .drawbox(50, 50, 120, 120, color='red', thickness=5) .output('out.mp4') .run() ) ``` -------------------------------- ### Python: Basic Input/Output Operations with FFmpeg Source: https://context7.com/kkroening/ffmpeg-python/llms.txt Demonstrates fundamental file input and output operations using ffmpeg-python. It covers basic file conversion, specifying encoding parameters, handling multiple outputs, and piping data to/from FFmpeg processes. ```python import ffmpeg # Basic input/output stream = ffmpeg.input('input.mp4') output = ffmpeg.output(stream, 'output.mp4') ffmpeg.run(output) # Input with time offset and format specification stream = ffmpeg.input('video.mp4', ss=30.5, t=10, format='mp4') ffmpeg.output(stream, 'clip.mp4').run() # Output with encoding parameters ( ffmpeg .input('input.mp4') .output('output.mp4', vcodec='libx264', acodec='aac', video_bitrate='5M', audio_bitrate='192k', **{'qscale:v': 3}) .overwrite_output() .run() ) # Multiple outputs from single input input_stream = ffmpeg.input('input.mp4') output1 = ffmpeg.output(input_stream, 'out1.mp4', vcodec='h264') output2 = ffmpeg.output(input_stream, 'out2.webm', vcodec='vp8') ffmpeg.merge_outputs(output1, output2).run() # Pipe input from stdin process = ( ffmpeg .input('pipe:', format='rawvideo', pix_fmt='rgb24', s='1920x1080') .output('output.mp4', pix_fmt='yuv420p') .run_async(pipe_stdin=True) ) process.stdin.write(raw_video_bytes) process.stdin.close() process.wait() # Capture output to stdout out, err = ( ffmpeg .input('input.mp4') .output('pipe:', format='rawvideo', pix_fmt='rgb24') .run(capture_stdout=True, capture_stderr=True) ) ``` -------------------------------- ### Process Video Frames with NumPy and ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt Iterates through video frames converted to NumPy arrays and applies image processing operations. This example darkens each frame by multiplying pixel values. ```python # Convert entire video to NumPy array first (see previous snippet) # ... video = np.frombuffer(out, np.uint8).reshape([-1, height, width, 3]) for i, frame in enumerate(video): # Apply image processing processed = frame * 0.8 # Darken # Save or further process ``` -------------------------------- ### Define FFmpeg Output with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html Illustrates how to define an output file for FFmpeg processing with ffmpeg-python. The 'output' function takes one or more streams and a filename. Keyword arguments are passed to FFmpeg, with specific handling for parameters like video bitrate ('video_bitrate'), audio bitrate ('audio_bitrate'), and format ('format'). Writing to standard output is supported using 'pipe:'. ```python import ffmpeg input_stream = ffmpeg.input('in.mp4') # Single stream output with bitrate and formatoutput_stream = ffmpeg.output(input_stream, 'out.mp4', video_bitrate=1000, audio_bitrate=200, format='mp4') # Multiple streams to the same output output_multi = ffmpeg.output(input_stream.audio, input_stream.video, 'out_multi.mp4') # Output to stdout output_pipe = ffmpeg.output(input_stream, 'pipe:') ``` -------------------------------- ### Create Video from Image Sequences with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This snippet demonstrates how to create videos from sequences of images using ffmpeg-python. It covers creating a video from a glob pattern of JPG images with a specified framerate and creating a video from a numbered PNG sequence with codec and pixel format options. ```python import ffmpeg # Create video from image sequence with glob pattern ( ffmpeg .input('/path/to/images/*.jpg', pattern_type='glob', framerate=25) .output('movie.mp4') .run() ) # With numbered sequence ( ffmpeg .input('/path/to/frames/frame_%04d.png', framerate=30) .output('video.mp4', vcodec='libx264', pix_fmt='yuv420p') .run() ) ``` -------------------------------- ### Convert Entire Video to NumPy Array with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt Converts an entire video file into a NumPy array for further processing. It first probes the video to get dimensions and then uses rawvideo output with a specified pixel format. ```python probe = ffmpeg.probe('video.mp4') video_info = next(s for s in probe['streams'] if s['codec_type'] == 'video') width = int(video_info['width']) height = int(video_info['height']) out, err = ( ffmpeg .input('video.mp4') .output('pipe:', format='rawvideo', pix_fmt='rgb24') .run(capture_stdout=True) ) video = np.frombuffer(out, np.uint8).reshape([-1, height, width, 3]) print(f"Video shape: {video.shape}") ``` -------------------------------- ### Convert Video to NumPy Array with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/README.md Converts a video file into a NumPy array for further processing. This snippet reads the video frames as raw RGB data through a pipe and reshapes them into a multi-dimensional array. It requires numpy and ffmpeg. ```python out, _ = (ffmpeg.input('in.mp4').output('pipe:', format='rawvideo', pix_fmt='rgb24').run(capture_stdout=True)) video = (np.frombuffer(out, np.uint8).reshape([-1, height, width, 3])) ``` -------------------------------- ### Define FFmpeg Input with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html Shows how to specify an input file for FFmpeg processing using the ffmpeg-python library. The 'input' function takes a filename and accepts keyword arguments that are passed directly to FFmpeg's options (e.g., duration 't', format 'f', audio codec 'acodec'). Reading from standard input is supported using 'pipe:'. ```python import ffmpeg # Example with specific options input_file = ffmpeg.input('input.mp4', t=20, f='mp4', acodec='pcm') # Example reading from stdin input_pipe = ffmpeg.input('pipe:') ``` -------------------------------- ### ffmpeg.get_args() Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html Builds command-line arguments for FFmpeg based on a stream specification. ```APIDOC ## GET /ffmpeg/get_args ### Description Builds command-line arguments to be passed to ffmpeg. ### Method GET ### Endpoint /ffmpeg/get_args ### Parameters #### Query Parameters - **stream_spec** (any) - Required - The stream specification for FFmpeg. - **overwrite_output** (boolean) - Optional - Whether to overwrite output files if they exist. Defaults to False. ``` -------------------------------- ### Run ffmpeg command with run Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html The `run` function executes the ffmpeg command with the generated arguments. It can optionally capture stdout and stderr, and takes an input string for stdin. It returns a tuple of captured stdout and stderr. ```python ffmpeg.run(stream_spec, cmd='ffmpeg', capture_stdout=False, capture_stderr=False, input=None, quiet=False, overwrite_output=False) ``` -------------------------------- ### Complex Concatenation with Processing using ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt Performs a complex concatenation of video segments with additional processing like overlaying an image and drawing a box. This example demonstrates trimming specific parts of input files and applying filters. ```python in_file = ffmpeg.input('input.mp4') overlay_file = ffmpeg.input('overlay.png') ( ffmpeg .concat( in_file.trim(start_frame=10, end_frame=20), in_file.trim(start_frame=30, end_frame=40), ) .overlay(overlay_file.hflip()) .drawbox(50, 50, 120, 120, color='red', thickness=5) .output('out.mp4') .run() ) ``` -------------------------------- ### Separate Audio and Video Streams with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This snippet demonstrates how to access and process individual audio and video streams from a single input file. It shows selecting the video and audio streams, applying a video filter (.hflip(), .filter('scale', ...)), and then outputting the processed video alongside the original audio. ```python input_file = ffmpeg.input('input.mp4') video = input_file.video # or input_file['v'] audio = input_file.audio # or input_file['a'] # Process video only, keep audio unchanged processed_video = video.hflip().filter('scale', 1280, 720) ( ffmpeg .output(processed_video, audio, 'output.mp4') .run() ) ``` -------------------------------- ### Extract Specific Video Frame with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/examples/ffmpeg-numpy.ipynb Defines a function to extract a specific frame from a video stream using ffmpeg's select filter. It takes a stream and frame number as input and returns the frame as a NumPy array. ```python from io import BytesIO from PIL import Image def extract_frame(stream, frame_num): while isinstance(stream, ffmpeg.nodes.OutputStream): stream = stream.node.incoming_edges[0].upstream_node.stream() out, _ = ( stream .filter_('select', 'gte(n,{})'.format(frame_num)) .output('pipe:', format='rawvideo', pix_fmt='rgb24', vframes=1) .run(capture_stdout=True, capture_stderr=True) ) return np.frombuffer(out, np.uint8).reshape([height, width, 3]) ``` -------------------------------- ### Create Video from Image Sequence with Filters (Python) Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This snippet demonstrates how to create a video from a sequence of JPEG images using glob pattern matching. It applies 'deflicker' and 'scale' filters, crops the video, and outputs it to an MP4 file with specified encoding parameters. This is useful for batch processing image sequences into videos. ```python import ffmpeg (ffmpeg.input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25) .filter('deflicker', mode='pm', size=10) .filter('scale', size='hd1080', force_original_aspect_ratio='increase') .filter('crop', 1920, 1080) .output('movie.mp4', crf=20, preset='slower', movflags='faststart', pix_fmt='yuv420p') .run()) ``` -------------------------------- ### Trim Video by Frame or Time with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This example shows how to trim a video either by frame number or by time duration using the .trim() method. It's essential to use .setpts('PTS-STARTPTS') to reset timestamps after trimming. The output is saved as 'trimmed.mp4'. ```python ( ffmpeg .input('input.mp4') .trim(start_frame=10, end_frame=250) .setpts('PTS-STARTPTS') # Reset timestamps .output('trimmed.mp4') .run() ) ``` -------------------------------- ### Use String Expressions for ffmpeg Filters Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Explains how to incorporate string expressions, which are interpreted by ffmpeg, into filter parameters. This allows for dynamic filter adjustments using ffmpeg's special variable names, as shown with the 'crop' filter example. ```python ( ffmpeg .input('in.mp4') .filter('crop', 'in_w-2*10', 'in_h-2*20') .input('out.mp4') ) ``` -------------------------------- ### ffmpeg.run() Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html Invokes FFmpeg with the given stream specification and arguments, capturing output if requested. ```APIDOC ## POST /ffmpeg/run ### Description Invokes ffmpeg for the supplied node graph. This function builds the command line arguments and executes them. ### Method POST ### Endpoint /ffmpeg/run ### Parameters #### Query Parameters - **stream_spec** (any) - Required - The stream specification for FFmpeg. - **cmd** (string) - Optional - The ffmpeg command to use. Defaults to 'ffmpeg'. - **capture_stdout** (boolean) - Optional - If True, capture stdout. Defaults to False. - **capture_stderr** (boolean) - Optional - If True, capture stderr. Defaults to False. - **quiet** (boolean) - Optional - Shorthand for setting `capture_stdout` and `capture_stderr`. Defaults to False. - **input** (string) - Optional - Text to be sent to stdin. Defaults to None. - **overwrite_output** (boolean) - Optional - Whether to overwrite output files if they exist. Defaults to False. #### Request Body *Note: Request body is not explicitly defined but keyword arguments passed to `get_args()` can be included.* ### Response #### Success Response (200) - **out** (string) - Captured stdout data if `capture_stdout` is True. - **err** (string) - Captured stderr data if `capture_stderr` is True. #### Response Example ```json { "out": "stdout data", "err": "stderr data" } ``` ``` -------------------------------- ### Build ffmpeg command-line arguments with get_args Source: https://github.com/kkroening/ffmpeg-python/blob/master/doc/html/index.html The `get_args` function constructs the command-line arguments for ffmpeg based on a stream specification. It is useful for debugging or when manual invocation of ffmpeg is required. It takes a stream specification and an optional `overwrite_output` boolean as input. ```python ffmpeg.get_args(stream_spec, overwrite_output=False) ``` -------------------------------- ### Handle Multiple Inputs for Filters in ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Shows how to use filters that require multiple input streams, such as the 'overlay' filter, by passing the input streams as a list to the `ffmpeg.filter` function. This enables complex operations involving several media files. ```python main = ffmpeg.input('main.mp4') logo = ffmpeg.input('logo.png') ( ffmpeg .filter([main, logo], 'overlay', 10, 10) .output('out.mp4') .run() ) ``` -------------------------------- ### Flip Video Horizontally with ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Demonstrates how to flip a video horizontally using the ffmpeg-python library. This involves importing the library, defining input and output streams, applying the hflip filter, and running the process. It shows both a step-by-step approach and a fluent interface style. ```python import ffmpeg stream = ffmpeg.input('input.mp4') stream = ffmpeg.hflip(stream) stream = ffmpeg.output(stream, 'output.mp4') ffmpeg.run(stream) ``` ```python import ffmpeg ( ffmpeg .input('input.mp4') .hflip() .output('output.mp4') .run() ) ``` -------------------------------- ### Complex Audio/Video Pipeline with ffmpeg-python Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This advanced snippet demonstrates a complex pipeline involving multiple inputs, stream manipulation (flipping, reversing, hue adjustment, volume control), concatenation using ffmpeg.concat(), and outputting a new file. It shows how to build intricate filter graphs. ```python in1 = ffmpeg.input('in1.mp4') in2 = ffmpeg.input('in2.mp4') v1 = in1.video.hflip() a1 = in1.audio v2 = in2.video.filter('reverse').filter('hue', s=0) a2 = in2.audio.filter('areverse').filter('aphaser') joined = ffmpeg.concat(v1, a1, v2, a2, v=1, a=1).node v3 = joined[0] # Video output a3 = joined[1].filter('volume', 0.8) # Audio output with volume adjustment ffmpeg.output(v3, a3, 'out.mp4').run() ``` -------------------------------- ### Compile and Dry Run FFmpeg Commands Source: https://context7.com/kkroening/ffmpeg-python/llms.txt This snippet demonstrates how to compile FFmpeg commands using `ffmpeg-python` and perform a dry run. `compile()` generates the command list, and it can be combined with `subprocess` to simulate execution without actually processing video. This is useful for verifying command syntax and parameters before a potentially lengthy operation. ```python import ffmpeg import subprocess stream = ( ffmpeg .input('input.mp4') .filter('scale', 1920, 1080) .output('output.mp4', vcodec='libx264') ) # Compile without running cmd = stream.compile(cmd='ffmpeg', overwrite_output=True) print(' '.join(cmd)) # Dry run - just show command args = stream.get_args() print("Would execute:", ['ffmpeg'] + args) ``` -------------------------------- ### Specify Special Option Names in ffmpeg-python Source: https://github.com/kkroening/ffmpeg-python/blob/master/README.md Illustrates how to handle special option names, such as '-qscale:v' or '-b:v', when configuring output streams in ffmpeg-python. This is done by passing these options as a dictionary to the output function, ensuring correct interpretation by ffmpeg. ```python ( ffmpeg .input('in.mp4') .output('out.mp4', **{'qscale:v': 3}) .run() ) ```