Skip to content

Instantly share code, notes, and snippets.

@basperheim
Created February 24, 2024 09:02
Show Gist options
  • Save basperheim/182b4d5c1ef175d390dd2b2da4867f9b to your computer and use it in GitHub Desktop.
Save basperheim/182b4d5c1ef175d390dd2b2da4867f9b to your computer and use it in GitHub Desktop.
Use Python & FFmpeg to reduce video sizes
import os
import subprocess
DRY_RUN = False
# Function to find all video files in the current directory
def find_video_files():
video_files = []
for file in os.listdir('.'):
if file.endswith('.mkv') or file.endswith('.mp4'):
video_files.append(file)
return video_files
# Function to execute FFmpeg command on each video file
def process_files(video_files):
for input_file in video_files:
file_extension = input_file.split(".")[-1]
if '.reduced.' in input_file:
print("\n\x1b[33mSkipping:", input_file, "\x1b[37m")
continue
else:
print("\n\x1b[32mEncoding:", input_file, "\x1b[37m")
output_file = os.path.splitext(input_file)[0] + '.reduced.' + file_extension
ffmpeg_command = [
'ffmpeg',
'-y',
'-hide_banner',
'-i', input_file,
'-vf', 'scale=854:-2', # Scale down to a width of 854 pixels, keeping the aspect ratio
'-c:v', 'libx264',
'-preset', 'slow',
'-crf', '28', # Increase the CRF value for smaller file size
'-c:a', 'copy',
'-c:s', 'copy',
# '-threads', '2',
output_file
]
if not DRY_RUN:
# Execute FFmpeg command as a subprocess
subprocess.run(ffmpeg_command)
else:
print(ffmpeg_command)
# Find all video files in the current directory
video_files = find_video_files()
if video_files:
# Process each video file
process_files(video_files)
print("Conversion completed successfully.")
else:
print("No video files found in the current directory.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment