Yes, absolutely! While there isn't one single, definitive "Python package" that does only video downscaling with GPU support built from scratch, you can achieve this effectively by leveraging existing powerful tools through Python.
The most common and efficient way to do this, especially leveraging your GPU, is by using Python to control FFmpeg. FFmpeg is the gold standard command-line tool for multimedia processing and has excellent support for GPU hardware acceleration (like NVIDIA NVENC/NVDEC).
Here are the main approaches:
Using subprocess to call FFmpeg (Recommended for Performance & GPU)
This is generally the most performant and reliable method as it directly uses FFmpeg's highly optimized code, including its GPU acceleration features.
Prerequisites:
Install FFmpeg on your system. Make sure the build you install supports GPU acceleration (e.g., NVENC for NVIDIA). Many pre-built binaries include this. You can download from the official FFmpeg website or install via package managers (like apt, brew, conda).
Ensure your NVIDIA drivers and CUDA toolkit (if needed by FFmpeg) are installed correctly.
Python Code:
python
import subprocess
import shlex # For safely splitting command strings
def downscale_video_gpu(input_file, output_file, output_resolution='1920x1080'):
"""
Downscales a video using FFmpeg with GPU acceleration (NVENC/CUDA).
Args:
input_file (str): Path to the input video file.
output_file (str): Path for the output video file.
output_resolution (str): Target resolution (e.g., '1920x1080', '1280x720').
"""
# Try to use hardware decoding if available (faster)
# '-hwaccel cuda' or '-hwaccel nvdec' might be needed depending on FFmpeg version/build
# '-hwaccel_output_format cuda' ensures frames stay on GPU for subsequent ops
# NVENC encoder is typically specified as 'h264_nvenc' or 'hevc_nvenc'
# Use 'h264_nvenc' for H.264 output
# Adjust preset for quality/speed trade-off ('slow', 'medium', 'fast', 'hq', 'bd')
# '-cq' or '-qp' can be used for constant quality mode, or '-b:v' for bitrate.
command = [
'ffmpeg',
'-i', input_file, # Input file
'-vf', f'scale={output_resolution}', # Video filter: resize
'-c:v', 'h264_nvenc', # Use NVIDIA's H.264 encoder
'-preset', 'medium', # Encoder preset (quality/speed)
'-cq', '23', # Constant Quality (adjust as needed, lower = better quality)
# Alternatively, use bitrate: '-b:v', '5000k', # Target bitrate e.g., 5 Mbps
'-c:a', 'aac', # Copy audio stream or re-encode (e.g., 'aac')
'-b:a', '128k', # Audio bitrate
'-y', # Overwrite output file if it exists
output_file
]
# Optional: Add hardware decoding if supported and beneficial
# command.insert(1, '-hwaccel_output_format')
# command.insert(2, 'cuda')
# command.insert(1, '-hwaccel')
# command.insert(2, 'cuda') # or 'nvdec' if your FFmpeg version uses that
print(f"Running FFmpeg command: {' '.join(shlex.quote(str(c)) for c in command)}")
try:
# Use run instead of Popen for simpler waiting and error checking
result = subprocess.run(command, check=True, capture_output=True, text=True)
print("FFmpeg stdout:", result.stdout)
print("FFmpeg stderr:", result.stderr)
print(f"Video successfully downscaled to {output_resolution} and saved as {output_file}")
except subprocess.CalledProcessError as e:
print(f"FFmpeg command failed with error code {e.returncode}")
print("FFmpeg stdout:", e.stdout)
print("FFmpeg stderr:", e.stderr)
except FileNotFoundError:
print("Error: ffmpeg command not found. Make sure FFmpeg is installed and in your PATH.")
# --- Example Usage ---
input_video = 'input_4k.mp4'
output_video = 'output_1080p.mp4'
# Create a dummy input file if needed for testing (requires numpy and opencv-python)
# import cv2
# import numpy as np
# fourcc = cv2.VideoWriter_fourcc(*'mp4v')
# out = cv2.VideoWriter(input_video, fourcc, 30.0, (3840, 2160))
# for _ in range(100): # ~3 seconds of video
# frame = np.random.randint(0, 256, (2160, 3840, 3), dtype=np.uint8)
# out.write(frame)
# out.release()
# print(f"Created dummy file: {input_video}")
downscale_video_gpu(input_video, output_video, '1920x1080')
Using MoviePy
MoviePy is a higher-level library that uses FFmpeg as its backend by default. It provides a more Pythonic interface. GPU acceleration can be used if FFmpeg is configured correctly, but it's less explicit than calling FFmpeg directly via subprocess.
Prerequisites:
pip install moviepy
FFmpeg installed (MoviePy often bundles a version or uses your system's).
Python Code:
python
from moviepy.editor import VideoFileClip
def downscale_moviepy(input_file, output_file, target_resolution=(1920, 1080)):
"""
Downscales a video using MoviePy. Relies on FFmpeg backend.
Args:
input_file (str): Path to the input video file.
output_file (str): Path for the output video file.
target_resolution (tuple): Target resolution (width, height).
"""
try:
print(f"Loading video file: {input_file}")
clip = VideoFileClip(input_file)
print(f"Resizing video to {target_resolution}")
# Use 'method="lanczos"' for high-quality resizing, though it might be slower.
# Moviepy's underlying call to ffmpeg might utilize GPU if available and configured.
resized_clip = clip.resize(target_resolution, method='lanczos')
print(f"Writing resized video to: {output_file}")
# Use appropriate codecs and parameters. 'libx264' is common software encoder.
# For hardware encoding, you might need to pass specific ffmpeg_params,
# but it's often simpler to use the subprocess method for explicit GPU control.
resized_clip.write_videofile(
output_file,
codec='libx264', # Software encoder (can specify others like 'libx265')
audio_codec='aac', # Audio codec
temp_audiofile='temp-audio.m4a', # Temporary file for audio processing
remove_temp=True,
# preset='medium', # FFMPEG preset (ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow)
# bitrate='5M' # Optional: Specify target bitrate like '5000k' or '5M'
threads=4 # Adjust based on your CPU cores
)
print(f"Video successfully downscaled to {target_resolution} and saved as {output_file}")
except Exception as e:
print(f"An error occurred: {e}")
finally:
if 'clip' in locals() and clip:
clip.close()
if 'resized_clip' in locals() and resized_clip:
resized_clip.close()
# --- Example Usage ---
# input_video = 'input_4k.mp4'
# output_video = 'output_1080p_moviepy.mp4'
# downscale_moviepy(input_video, output_video, target_resolution=(1920, 1080))
Using OpenCV (cv2) with CUDA
OpenCV can utilize GPU acceleration for certain operations, including resizing, if you have a CUDA-enabled build (opencv-contrib-python often includes CUDA modules, or you might need a specific build). However, managing the video encoding part efficiently on the GPU often brings you back to needing FFmpeg anyway. You'd typically read frames using OpenCV, resize them on the GPU (if possible), and then potentially use FFmpeg (via subprocess) to encode the processed frames.
Prerequisites:
pip install opencv-python or pip install opencv-contrib-python
CUDA Toolkit and cuDNN installed
Build OpenCV with CUDA support (often complex to set up manually, check package availability).
Conceptual Code (Focus on Resizing Frame):
python
Recommendation:
For straightforward downscaling leveraging your GPU for both decoding and encoding (which is usually the bottleneck), the subprocess approach calling FFmpeg is the most direct, efficient, and recommended method. It gives you explicit control over FFmpeg's powerful features. MoviePy is a good alternative if you prefer a higher-level API, but be aware that fine-grained GPU control might be less straightforward. OpenCV is best if you need to do complex frame-by-frame analysis before or during the resizing, but for simple downscaling, FFmpeg is usually superior.
User
If the video is recording by phone, do I need to do anything else?
Assistant
Okay, that's a great clarifying question! Videos recorded by phones often have a few characteristics that might require slight adjustments to the FFmpeg command, although the core process remains the same.
Here are the main things to consider and potential adjustments:
Variable Frame Rate (VFR): This is the most common issue with phone videos. Phones often adjust the frame rate dynamically to save power or adapt to scene complexity. This can cause problems with audio sync, editing, or playback in certain applications.
Solution: Force a Constant Frame Rate (CFR) during conversion. You can do this by adding the fps video filter. Choose a common target like 30 or 60 fps.
Rotation Metadata: Phones record orientation data (which way is "up"). FFmpeg usually reads this metadata and applies the correct rotation automatically during processing. However, sometimes it might miss it, or you might want to ensure it's handled correctly before scaling.
Solution: FFmpeg usually handles this implicitly. If you find your output video is sideways despite the input being correct, you can explicitly add a transpose filter before or after the scale filter. Common values are transpose=0 (90 degrees counter-clockwise), transpose=1 (90 degrees clockwise), transpose=2 (vertical flip), transpose=3 (horizontal flip). transpose=auto attempts to use metadata. It's often best to test first and only add transpose if needed.
Codecs: Phones commonly use H.264 (AVC) or H.265 (HEVC) for video and AAC for audio. FFmpeg handles these well. If your phone records in HEVC (often results in smaller file sizes), you might want to use the HEVC encoder on the output side too, if your GPU supports it (hevc_nvenc).
Solution: The h264_nvenc encoder in the previous example is a safe bet. If you want HEVC output (potentially smaller files for the same quality), you can try hevc_nvenc. Ensure your FFmpeg build supports it.
Audio: AAC is widely compatible. Re-encoding it (-c:a aac) is usually fine. If you want to preserve the original audio exactly (faster, no quality loss), you can try -c:a copy, but ensure the output container (like MP4) supports the original audio codec.
User
How about color, do we need to take care of this if the video is recording by phone?
Assistant
That's an excellent question! While FFmpeg and GPU acceleration primarily focus on resolution, codecs, and frame rates, color can be a factor, especially with phone footage. Here's what to consider:
Color Range (Full vs. Limited/MPEG):
The Issue: This is the most common color-related nuance with phone videos. Phones often record video using Full Color Range (where black is 0 and white is 255 in digital values, often referred to as "PC" or "Pascal C"). However, many video standards and players expect Limited Color Range (where black is 16 and white is 235, often referred to as "TV" or "MPEG" range).
What Happens: If your input video is Full range and FFmpeg processes it assuming Limited (or vice-versa), you can get washed-out colors (if input was Full, output assumed Limited) or crushed blacks/whites (if input was Limited, output assumed Full).
FFmpeg Handling: FFmpeg is usually pretty good at guessing the input range based on metadata or common formats. For the output, it often defaults to what the container format expects (e.g., Limited for MP4).
Solution: If you notice the washed-out or crushed look after conversion, you might need to explicitly tell FFmpeg about the color range. You can use the scale filter with in_range and out_range options.
If your input is Full and you want Limited output (common):
Or, using the format filter can sometimes be more robust:
ffmpeg
-vf "scale=1920x1080,fps=30" -pix_fmt yuv420p -color_range tv
(Note: -color_range tv implies limited range output). You might need to experiment. Often, just letting FFmpeg handle it works fine, but keep this in mind if the output looks off.
HDR (High Dynamic Range) vs. SDR (Standard Dynamic Range):
The Issue: Some modern phones can record video in HDR formats (like Dolby Vision, HDR10+). These videos contain much more information about brightness and color than standard SDR videos. Downscaling an HDR video to SDR requires tone mapping – compressing the dynamic range to fit within the SDR limitations. This is a complex process.
User
Ok, write a complete script for me, to convert these two videos:
20250614_170859_1080p.mp4
20250614_161955_1080p.mp4
Assistant
Okay, here is a complete Python script that uses subprocess to call FFmpeg for converting your video files. It incorporates the best practices discussed, including GPU acceleration, CFR enforcement, and sensible default settings.
Before Running:
Install FFmpeg: Make sure you have FFmpeg installed on your system and that the ffmpeg command is accessible from your terminal (i.e., it's in your system's PATH). You can download it from ffmpeg.org. Ensure your FFmpeg build includes support for your GPU's hardware encoder (like NVENC for NVIDIA).
Install Python: You need Python 3 installed.
GPU Drivers: Ensure your NVIDIA drivers are installed and up-to-date if you're using h264_nvenc or hevc_nvenc.
Place Videos: Put this script in the same directory as your video files, or update the INPUT_VIDEOS list with the correct paths to your videos.
Note: While MoviePy uses FFmpeg, explicitly forcing GPU encoding within MoviePy's write_videofile arguments can be tricky and might require custom ffmpeg_params. The subprocess method gives you direct control.
import cv2
import numpy as np
import time
def downscale_opencv_gpu(input_file, output_file, output_resolution=(1920, 1080)):
"""
Downscales video using OpenCV, attempting GPU resizing.
Note: Efficient GPU *encoding* often still requires external tools like FFmpeg.
This example focuses on the resizing part. Writing the output efficiently
might require careful handling or using FFmpeg backend.
"""
try:
# --- Check for CUDA availability ---
if not cv2.cuda.getCudaEnabledDeviceCount() > 0:
print("Warning: CUDA not available or OpenCV not built with CUDA support. Falling back to CPU.")
use_gpu = False
else:
# Select the device (optional, defaults to 0)
# cv2.cuda.Device(0).select()
use_gpu = True
print("CUDA is available. Using GPU.")
# --- Video Capture and Writer Setup ---
cap = cv2.VideoCapture(input_file)
if not cap.isOpened():
print(f"Error: Could not open video file: {input_file}")
return
# Get video properties
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"Input: {frame_width}x{frame_height} @ {fps:.2f} FPS")
# --- Output Setup ---
# Using standard VideoWriter (CPU-bound encoding by default)
# For GPU encoding, you'd typically pipe frames to FFmpeg subprocess
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Or use a codec suitable for your FFmpeg build
out = cv2.VideoWriter(output_file, fourcc, fps, output_resolution)
frame_count = 0
start_time = time.time()
while True:
ret, frame = cap.read()
if not ret:
break # End of video
frame_count += 1
if frame_count % 30 == 0: # Print progress every 30 frames
print(f"Processing frame {frame_count}/{total_frames}...")
# --- Resizing ---
if use_gpu:
# Upload frame to GPU memory
frame_gpu = cv2.cuda_GpuMat()
frame_gpu.upload(frame)
# Resize on GPU
resized_frame_gpu = cv2.cuda.resize(frame_gpu, output_resolution, fx=0, fy=0, interpolation=cv2.INTER_LINEAR)
# Download back to CPU memory
resized_frame = resized_frame_gpu.download()
else:
# Resize on CPU
resized_frame = cv2.resize(frame, output_resolution, interpolation=cv2.INTER_LINEAR)
# Write the resized frame (encoding happens here, likely on CPU)
out.write(resized_frame)
end_time = time.time()
print(f"\nProcessing finished.")
print(f"Total frames processed: {frame_count}")
print(f"Elapsed time: {end_time - start_time:.2f} seconds")
cap.release()
out.release()
cv2.destroyAllWindows() # Close any OpenCV windows if opened
except Exception as e:
print(f"An error occurred: {e}")
if 'cap' in locals() and cap.isOpened():
cap.release()
if 'out' in locals() and out.isOpened():
out.release()
cv2.destroyAllWindows()
# --- Example Usage ---
# input_video = 'input_4k.mp4'
# output_video = 'output_1080p_opencv.mp4'
# downscale_opencv_gpu(input_video, output_video, output_resolution=(1920, 1080))
Metadata: Phone videos often contain GPS data, timestamps, etc. Processing with FFmpeg might strip some of this metadata unless you specifically tell it to preserve it (which can add complexity). For simple downscaling, losing GPS data is usually acceptable.
Revised FFmpeg Command incorporating VFR fix:
Let's assume you want to target 30 FPS CFR output. We'll add the fps filter to the video filter chain (-vf).
python
import subprocess
import shlex
def downscale_video_gpu_phone(input_file, output_file, output_resolution='1920x1080', output_fps=30):
"""
Downscales a video (potentially from a phone) using FFmpeg with GPU acceleration,
forcing Constant Frame Rate (CFR).
Args:
input_file (str): Path to the input video file.
output_file (str): Path for the output video file.
output_resolution (str): Target resolution (e.g., '1920x1080').
output_fps (int): Target constant frame rate (e.g., 30 or 60).
"""
# Construct the video filter chain: scale AND force FPS
# Note: Putting fps filter after scale is generally fine.
vf_filter = f"scale={output_resolution},fps=fps={output_fps}"
# Potential addition if rotation is wrong: add ',transpose=1' (or 0, 2, 3) to vf_filter
# Example: vf_filter = f"scale={output_resolution},fps=fps={output_fps},transpose=1"
# Encoder choice: h264_nvenc is common. Use hevc_nvenc for HEVC output if supported.
video_codec = 'h264_nvenc'
# video_codec = 'hevc_nvenc' # Uncomment to try HEVC encoding
command = [
'ffmpeg',
'-i', input_file, # Input file
# '-map 0' # Optional: Ensure all streams (video, audio, subtitles) are mapped
# '-vsync', 'cfr', # Alternative/additional way to suggest CFR (less explicit than fps filter)
'-vf', vf_filter, # Video filters: scale AND force FPS
'-c:v', video_codec, # Use GPU-accelerated encoder
'-preset', 'medium', # Encoder preset (quality/speed trade-off)
'-cq', '23', # Constant Quality (adjust as needed, lower=better quality)
# '-b:v', '5000k', # Alternatively, set target bitrate (e.g., 5 Mbps)
'-c:a', 'aac', # Re-encode audio to AAC (compatible)
'-b:a', '128k', # Audio bitrate
# '-metadata:s:v:0', 'rotation=0', # Optional: Reset rotation metadata if causing issues BEFORE scaling
'-y', # Overwrite output file if it exists
output_file
]
# Add hardware decoding flags if needed and supported (can sometimes speed up)
# command.insert(1, '-hwaccel_output_format')
# command.insert(2, 'cuda')
# command.insert(1, '-hwaccel')
# command.insert(2, 'cuda') # or 'nvdec' depending on FFmpeg version/build
print(f"Running FFmpeg command: {' '.join(shlex.quote(str(c)) for c in command)}")
try:
result = subprocess.run(command, check=True, capture_output=True, text=True)
print("FFmpeg stdout:", result.stdout)
print("FFmpeg stderr:", result.stderr) # FFmpeg often prints info/warnings to stderr
print(f"Video successfully downscaled and saved as {output_file}")
except subprocess.CalledProcessError as e:
print(f"FFmpeg command failed with error code {e.returncode}")
print("FFmpeg stdout:", e.stdout)
print("FFmpeg stderr:", e.stderr)
except FileNotFoundError:
print("Error: ffmpeg command not found. Make sure FFmpeg is installed and in your PATH.")
# --- Example Usage ---
input_video = 'my_phone_video_4k.mp4'
output_video = 'my_phone_video_1080p_30fps.mp4'
# Make sure input_video exists before running!
# Example: Create a dummy file if needed for testing
# import cv2
# import numpy as np
# fourcc = cv2.VideoWriter_fourcc(*'mp4v')
# out = cv2.VideoWriter(input_video, fourcc, 60.0, (3840, 2160)) # Example 4K @ 60fps VFR source
# for i in range(150):
# frame = np.random.randint(0, 256, (2160, 3840, 3), dtype=np.uint8)
# out.write(frame)
# out.release()
# print(f"Created dummy file: {input_video}")
downscale_video_gpu_phone(input_video, output_video, output_resolution='1920x1080', output_fps=30)
Key Changes & Considerations:
-vf "scale=...,fps=fps=30": This is the crucial addition to handle potential VFR from the phone. Replace 30 with 60 or your desired target FPS.
Check Output: Always play back the output file to confirm the resolution, frame rate, and audio sync are correct.
HEVC Encoder: If your phone records in H.265/HEVC, consider using -c:v hevc_nvenc for the output encoder for potentially better compression efficiency, but ensure your FFmpeg build and GPU driver support it.
Transpose Filter: Only add ,transpose=1 (or another value) to the -vf string if the output video is incorrectly rotated.
In summary, the core FFmpeg command is robust, but adding the fps filter is often necessary for reliable results with phone-recorded footage due to VFR.
FFmpeg Handling: FFmpeg can do tone mapping, but it's not typically done automatically by a simple scale filter. You'd need specific filters like zscale or alcupscale, often requiring the libplacebo library and careful parameter tuning.
Solution: If your phone records in HDR, you need to explicitly decide if you want to:
Convert to SDR: This is the most common scenario if you're downscaling for general playback. You'll need specific FFmpeg filters for tone mapping.
Keep as HDR (but lower resolution): Less common, as the primary benefit of HDR is detail across a wide brightness range.
Recommendation: If you suspect your video is HDR, first verify it. If it is, you'll need a more advanced FFmpeg command specifically for HDR-to-SDR conversion during downscaling. For most users, phone videos are SDR by default.
Color Space and Primaries:
The Issue: Videos are recorded within specific color spaces (e.g., Rec.709, sRGB, BT.2020) which define the range of colors that can be represented. Phones typically record in common SDR spaces like Rec.709 or sRGB.
FFmpeg Handling: FFmpeg generally interprets these standard color spaces correctly. The scale filter can sometimes perform color space conversion if needed (e.g., if the input metadata incorrectly claims BT.2020 when it's actually Rec.709).
Solution: Usually, you don't need to worry about this for standard SDR phone footage. FFmpeg's automatic color management is typically sufficient. If you were converting between very different color spaces (e.g., Log footage to Rec.709, or wide-gamut HDR to Rec.709), you'd use filters like colorspace.
Baked-in Color Adjustments (White Balance, Saturation, etc.):
The Issue: The phone's camera processing applies white balance, saturation, contrast, etc., during recording. These adjustments are "baked into" the video file.
FFmpeg Handling: FFmpeg preserves these baked-in colors during the downscaling process. It doesn't inherently alter the white balance or saturation unless you specifically apply color correction filters (like curves, eq, lut3d).
Solution: No action is needed here unless you want to change the colors further. The downscaling itself won't add or remove color casts.
In Summary:
For most standard SDR phone videos: You likely don't need to do anything extra regarding color. FFmpeg handles common color spaces and ranges reasonably well by default.
If output looks washed out or blacks/whites are crushed: Investigate Color Range issues. Try adding in_range=full:out_range=limited to your scale filter, or experiment with -color_range tv.
If your phone records HDR: This requires a more specialized FFmpeg workflow involving tone mapping filters to convert to SDR. If this is your situation, let me know, and we can explore specific filters.
Always test a short clip first to check for any unexpected color shifts!
# -*- coding: utf-8 -*-
"""
Python script to batch convert video files using FFmpeg with GPU acceleration.
This script takes a list of input video files and converts them to a specified
resolution and frame rate, utilizing GPU hardware encoding (e.g., NVIDIA NVENC)
for faster processing. It also enforces a Constant Frame Rate (CFR) to avoid
potential playback issues common with Variable Frame Rate (VFR) footage from phones.
Prerequisites:
1. **FFmpeg:** Must be installed on your system and accessible via the command line (in your PATH).
Download from: https://ffmpeg.org/download.html
Ensure your FFmpeg build includes support for your GPU's hardware encoder (e.g., NVENC for NVIDIA).
2. **NVIDIA GPU:** Required for `h264_nvenc` or `hevc_nvenc` codecs.
3. **NVIDIA Drivers:** Up-to-date drivers must be installed.
4. **Python:** Version 3.6 or higher recommended.
How to Use:
1. Save this script as a Python file (e.g., `convert_videos.py`).
2. Place the script in the same directory as your video files, or provide full paths to the videos.
3. Modify the `INPUT_VIDEOS`, `TARGET_RESOLUTION`, `TARGET_FPS`, `VIDEO_ENCODER`, etc., variables
in the script below according to your needs.
4. Run the script from your terminal: `python convert_videos.py`
"""
import subprocess
import shlex
import os
import sys # For exiting gracefully
# --- Configuration Section ---
# List of input video files to process.
# Replace these with the actual names/paths of your video files.
INPUT_VIDEOS = [
'20250614_170859_1080p.mp4',
'20250614_161955_1080p.mp4',
# Add more video file paths here if needed:
# 'path/to/your/other_video_4k.mov',
# 'another_clip.mkv',
]
# --- Conversion Parameters ---
# Target video resolution (e.g., '1920x1080' for Full HD, '1280x720' for HD)
TARGET_RESOLUTION = '1920x1080'
# Target Constant Frame Rate (CFR). Helps prevent sync issues common with phone footage.
# Common values are 30 or 60. Choose based on your source video's typical frame rate.
TARGET_FPS = 30
# Video Encoder: Use GPU-accelerated encoders if available.
# Common options for NVIDIA GPUs: 'h264_nvenc' (for H.264/AVC) or 'hevc_nvenc' (for H.265/HEVC).
# If your GPU/FFmpeg doesn't support these, you might need to fall back to software encoders like 'libx264'.
VIDEO_ENCODER = 'h264_nvenc'
# Quality Setting (Constant Rate Factor - CRF)
# Lower values mean higher quality and larger file sizes. Higher values mean lower quality and smaller files.
# Typical range for h264_nvenc might be ~18-28. Adjust as needed.
CRF_QUALITY = 23
# Audio Encoder and Bitrate
# 'aac' is widely compatible. Use 'copy' to avoid re-encoding audio if the output container supports the original codec.
AUDIO_ENCODER = 'aac'
AUDIO_BITRATE = '128k' # e.g., '128k', '192k', '256k'
# --- FFmpeg Command Construction ---
def build_ffmpeg_command(input_file, output_file, output_resolution, output_fps, video_codec, crf, audio_codec, audio_bitrate):
"""Constructs the FFmpeg command list for a single video conversion."""
# Video Filter chain: resize the video and enforce constant frame rate.
# Example filter: "scale=1920x1080,fps=fps=30"
vf_filter = f"scale={output_resolution},fps=fps={output_fps}"
# --- Optional Flags (Uncomment and adjust if needed) ---
# 1. Hardware Acceleration Flags: Explicitly tell FFmpeg to use CUDA.
# May not be needed if FFmpeg automatically detects it, but can sometimes help.
# hwaccel_flags = ['-hwaccel', 'cuda', '-hwaccel_output_format', 'cuda']
# 2. Color Range Adjustment: Use if output colors appear washed out or crushed.
# 'tv' implies limited range (16-235), 'full' implies full range (0-255).
# Phone footage is often recorded in 'full' range. MP4 usually expects 'limited'.
# color_range_flags = ['-color_range', 'tv'] # Or use 'full'
# Alternatively, you could add to vf_filter: vf_filter += ",scale=in_range=full:out_range=limited"
# --- Base FFmpeg Command ---
command = [
'ffmpeg',
'-i', input_file, # Specify the input file
# '-map 0', # Optional: Map all streams (video, audio, subtitles, etc.) from input 0
]
# --- Add Optional Flags ---
# command.extend(hwaccel_flags) # Uncomment to enable explicit HW acceleration flags
# command.extend(color_range_flags) # Uncomment to enable explicit color range flags
# --- Add Video Filters ---
command.extend(['-vf', vf_filter])
# --- Video Encoding Settings ---
command.extend(['-c:v', video_codec]) # Set the video codec
command.extend(['-preset', 'medium']) # Encoder preset (balance speed/quality). Options: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow
command.extend(['-cq', str(crf)]) # Set the Constant Quality factor
# --- Audio Encoding Settings ---
command.extend(['-c:a', audio_codec]) # Set the audio codec
if audio_codec != 'copy':
command.extend(['-b:a', audio_bitrate]) # Set audio bitrate if re-encoding
# --- Output Settings ---
command.extend(['-y', output_file]) # Overwrite output file without asking, specify output file path
return command
# --- Main Execution Logic ---
def main():
"""Main function to process the list of videos."""
print("*" * 70)
print("Starting Video Conversion Script")
print("*" * 70)
print(f"Target Resolution: {TARGET_RESOLUTION}")
print(f"Target FPS: {TARGET_FPS} (CFR)")
print(f"Video Encoder: {VIDEO_ENCODER}")
print(f"Quality (CRF): {CRF_QUALITY}")
print(f"Audio Encoder: {AUDIO_ENCODER} @ {AUDIO_BITRATE}")
print("-" * 70)
# Check if FFmpeg is available before starting the loop
try:
print("Checking for FFmpeg installation...")
# Run 'ffmpeg -version' to see if the command exists and works
subprocess.run(['ffmpeg', '-version'], check=True, capture_output=True, text=True, encoding='utf-8')
print("FFmpeg found and accessible.")
except FileNotFoundError:
print("\nERROR: 'ffmpeg' command not found.")
print("Please ensure FFmpeg is installed and its executable is in your system's PATH.")
print("Download FFmpeg from: https://ffmpeg.org/download.html")
sys.exit(1) # Exit script if FFmpeg is not found
except Exception as e:
print(f"\nAn error occurred while checking FFmpeg: {e}")
sys.exit(1)
print("-" * 70)
success_count = 0
skipped_count = 0
# Process each video file in the list
for input_file in INPUT_VIDEOS:
# Check if the input file exists and is actually a file
if not os.path.isfile(input_file):
print(f"WARNING: Input file '{input_file}' not found or is not a regular file. Skipping.")
skipped_count += 1
continue
# Generate a meaningful output filename based on the input name and conversion settings
base, ext = os.path.splitext(input_file)
# Append conversion details to the filename to avoid overwriting originals unintentionally
output_file = f"{base}_converted_{TARGET_RESOLUTION}_fps{TARGET_FPS}{ext}"
# Build the FFmpeg command for this specific file
ffmpeg_command = build_ffmpeg_command(
input_file=input_file,
output_file=output_file,
output_resolution=TARGET_RESOLUTION,
output_fps=TARGET_FPS,
video_codec=VIDEO_ENCODER,
crf=CRF_QUALITY,
audio_codec=AUDIO_ENCODER,
audio_bitrate=AUDIO_BITRATE
)
# Print command details for transparency and debugging
print(f"\nProcessing: '{input_file}'")
print(f"Outputting to: '{output_file}'")
# Use shlex.quote for safe printing of commands with spaces or special characters
print(f"Command: {' '.join(shlex.quote(str(c)) for c in ffmpeg_command)}")
# Execute the FFmpeg command
try:
# subprocess.run() is generally preferred for running commands and waiting for completion.
# capture_output=True captures stdout/stderr. text=True decodes them as strings.
result = subprocess.run(ffmpeg_command, check=True, capture_output=True, text=True, encoding='utf-8')
# FFmpeg often prints progress and informational messages to stderr, even on success.
# Print stdout only if it contains meaningful output, stderr regardless.
if result.stdout:
print("FFmpeg stdout:\n", result.stdout)
print("FFmpeg stderr:\n", result.stderr) # Contains progress info
print(f"Successfully converted '{input_file}'")
success_count += 1
except subprocess.CalledProcessError as e:
# Handle errors during FFmpeg execution
print(f"\nERROR: FFmpeg command failed for '{input_file}' with exit code {e.returncode}")
print("--- FFmpeg stdout ---")
print(e.stdout)
print("--- FFmpeg stderr ---")
print(e.stderr)
print("-" * 20)
# Optional: Uncomment the next line to stop the script on the first error
# sys.exit(1)
except Exception as e:
# Handle any other unexpected errors during the process
print(f"\nAn unexpected error occurred while processing '{input_file}': {e}")
# Optional: Uncomment the next line to stop the script on the first error
# sys.exit(1)
print("-" * 70) # Separator line between processing logs for different files
# --- Summary ---
print("\n" + "*" * 70)
print("Video Conversion Process Summary")
print("*" * 70)
print(f"Total files specified in list: {len(INPUT_VIDEOS)}")
print(f"Successfully converted: {success_count}")
print(f"Skipped (file not found): {skipped_count}")
print(f"Failed conversions: {len(INPUT_VIDEOS) - success_count - skipped_count}")
print("*" * 70)
# --- Script Entry Point ---
# Ensures the main() function runs only when the script is executed directly
if __name__ == "__main__":
main()
How to Use:
Save: Save the code above into a file named convert_videos.py.
Configure:
Modify the INPUT_VIDEOS list to include the exact filenames of your videos. If they are not in the same directory as the script, provide the full paths (e.g., /Users/yourname/Videos/my_video.mp4).
Adjust TARGET_RESOLUTION, TARGET_FPS, VIDEO_ENCODER, CRF_QUALITY, etc., if needed. h264_nvenc is a good default for NVIDIA GPUs.
Run: Open your terminal or command prompt, navigate to the directory where you saved the script, and run it using:
bash
python convert_videos.py
The script will process each video file, printing progress and any errors encountered. The converted files will be saved in the same directory with _converted_1920x1080_fps30 appended to their original filenames.