Compress video files by Python and FFmpeg

Tools

FFmpeg is a powerful tool for video editing. And there is a great Python binding named ffmpeg-python (API Reference) for this. Firstly, pip install ffmpeg-python and install FFmpeg.

Steps

Probe the configuration of video by function ffmpeg.probe() to get duration, audio & video bit rate and so on. And calculate the bit rate of the target file based on what we have. Then, construct commands by ffmpeg.input() and ffmpeg.output(). Finally, run it.

Codes

Following is the example code. Change the compression algo for your situation if you want. For easy follow-up, I hided the code of boundary condition. The code I am using is in GitHub Gist. Any bug report is welcomed!

import os, ffmpeg
def compress_video(video_full_path, output_file_name, target_size):
    # Reference: https://en.wikipedia.org/wiki/Bit_rate#Encoding_bit_rate
    min_audio_bitrate = 32000
    max_audio_bitrate = 256000

    probe = ffmpeg.probe(video_full_path)
    # Video duration, in s.
    duration = float(probe['format']['duration'])
    # Audio bitrate, in bps.
    audio_bitrate = float(next((s for s in probe['streams'] if s['codec_type'] == 'audio'), None)['bit_rate'])
    # Target total bitrate, in bps.
    target_total_bitrate = (target_size * 1024 * 8) / (1.073741824 * duration)

    # Target audio bitrate, in bps
    if 10 * audio_bitrate > target_total_bitrate:
        audio_bitrate = target_total_bitrate / 10
        if audio_bitrate < min_audio_bitrate < target_total_bitrate:
            audio_bitrate = min_audio_bitrate
        elif audio_bitrate > max_audio_bitrate:
            audio_bitrate = max_audio_bitrate
    # Target video bitrate, in bps.
    video_bitrate = target_total_bitrate - audio_bitrate

    i = ffmpeg.input(video_full_path)
    ffmpeg.output(i, os.devnull,
                  **{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 1, 'f': 'mp4'}
                  ).overwrite_output().run()
    ffmpeg.output(i, output_file_name,
                  **{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 2, 'c:a': 'aac', 'b:a': audio_bitrate}
                  ).overwrite_output().run()

# Compress input.mp4 to 50MB and save as output.mp4
compress_video('input.mp4', 'output.mp4', 50 * 1000)

Notes

  1. Don't waste your time! Judge the file size before compressing.

  2. You can disable two-pass function by only keeping second ffmpeg.output() without parameter 'pass': 2.

  3. If video bit rate < 1000, it will throw exception Bitrate is extremely low.

  4. The biggest min file size I recommend is:

# Best min size, in kB.
best_min_size = (32000 + 100000) * (1.073741824 * duration) / (8 * 1024)
  1. If you specify a extremely small target file size, the size of generated file maybe exceed it. For most time, this will not happen.
Answer from 武状元 Woa on Stack Overflow
Top answer
1 of 4
23

Compress video files by Python and FFmpeg

Tools

FFmpeg is a powerful tool for video editing. And there is a great Python binding named ffmpeg-python (API Reference) for this. Firstly, pip install ffmpeg-python and install FFmpeg.

Steps

Probe the configuration of video by function ffmpeg.probe() to get duration, audio & video bit rate and so on. And calculate the bit rate of the target file based on what we have. Then, construct commands by ffmpeg.input() and ffmpeg.output(). Finally, run it.

Codes

Following is the example code. Change the compression algo for your situation if you want. For easy follow-up, I hided the code of boundary condition. The code I am using is in GitHub Gist. Any bug report is welcomed!

import os, ffmpeg
def compress_video(video_full_path, output_file_name, target_size):
    # Reference: https://en.wikipedia.org/wiki/Bit_rate#Encoding_bit_rate
    min_audio_bitrate = 32000
    max_audio_bitrate = 256000

    probe = ffmpeg.probe(video_full_path)
    # Video duration, in s.
    duration = float(probe['format']['duration'])
    # Audio bitrate, in bps.
    audio_bitrate = float(next((s for s in probe['streams'] if s['codec_type'] == 'audio'), None)['bit_rate'])
    # Target total bitrate, in bps.
    target_total_bitrate = (target_size * 1024 * 8) / (1.073741824 * duration)

    # Target audio bitrate, in bps
    if 10 * audio_bitrate > target_total_bitrate:
        audio_bitrate = target_total_bitrate / 10
        if audio_bitrate < min_audio_bitrate < target_total_bitrate:
            audio_bitrate = min_audio_bitrate
        elif audio_bitrate > max_audio_bitrate:
            audio_bitrate = max_audio_bitrate
    # Target video bitrate, in bps.
    video_bitrate = target_total_bitrate - audio_bitrate

    i = ffmpeg.input(video_full_path)
    ffmpeg.output(i, os.devnull,
                  **{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 1, 'f': 'mp4'}
                  ).overwrite_output().run()
    ffmpeg.output(i, output_file_name,
                  **{'c:v': 'libx264', 'b:v': video_bitrate, 'pass': 2, 'c:a': 'aac', 'b:a': audio_bitrate}
                  ).overwrite_output().run()

# Compress input.mp4 to 50MB and save as output.mp4
compress_video('input.mp4', 'output.mp4', 50 * 1000)

Notes

  1. Don't waste your time! Judge the file size before compressing.

  2. You can disable two-pass function by only keeping second ffmpeg.output() without parameter 'pass': 2.

  3. If video bit rate < 1000, it will throw exception Bitrate is extremely low.

  4. The biggest min file size I recommend is:

# Best min size, in kB.
best_min_size = (32000 + 100000) * (1.073741824 * duration) / (8 * 1024)
  1. If you specify a extremely small target file size, the size of generated file maybe exceed it. For most time, this will not happen.
2 of 4
1

I have used MoviePy in the past with good results. Another option (not the safest) might be to run FFMpeg as an external process to compress or resize the media file.

🌐
GitHub
gist.github.com › ESWZY › a420a308d3118f21274a0bc3a6feb1ff
An example Python code for compressing video file to target size. · GitHub
I mean in django I will save files in another place and in pure python in another place. from typing import Any from typing import NoReturn import ffmpeg import os def resize_video( video_absolute_path: str, output_file_absolute_path: str, size_upper_bound: int, two_pass: bool=True,) -> str: """ Compress video file to max-supported size.
🌐
DEV Community
dev.to › m4cs › compressing-videos-easily-on-windows-w-ffmpeg-and-registry-files-5fin
Compressing Videos Easily on Windows w/ FFMPEG and Registry Files - DEV Community
November 2, 2020 - 5: video_file is a Path object with the args passed joined as a string · 6: run([...]) is where we call the ffmpeg executable from Python and run our command to compress.
🌐
Medium
medium.com › @cantcode023 › compress-mp4-files-in-python-with-only-3-lines-of-code-4b01f6d274c7
Compress MP4 files in Python with only 3 lines of code | by Putera Danish Danial | Medium
February 26, 2023 - import discord # pip install discord.py from discord.ext import commands import asyncio import aiofiles # pip install aiofiles import requests # pip install requests from aspose_compressor import AsposeCompressor # pip install aspose-compressor client= commands.Bot(command_prefix='!', self_bot=True) loop = asyncio.get_event_loop() # wrap aspose compressor in an asynchronous function async def aspose_compress(file_path: str): ac = AsposeCompressor() file = await loop.run_in_executor(None, ac.compress_video, file_path) await loop.run_in_executor(None, file.save, "./compressed.mp4") @client.comma
🌐
Cloudinary
cloudinary.com › home › 3 ways to compress video in python
3 Ways to Compress Video in Python | Cloudinary
April 12, 2026 - Leverage GPU acceleration with FFmpeg If you’re compressing multiple or high-resolution videos, use hardware acceleration (e.g., NVENC for NVIDIA GPUs). Add flags like -hwaccel cuda or use -c:v h264_nvenc to massively speed up processing. Integrate perceptual quality metrics in your workflow Instead of only relying on bitrate, use SSIM or VMAF to evaluate visual quality after compression. These metrics help balance perceived quality against file size more effectively. Auto-adjust resolution using Python and FFprobe Dynamically query video metadata with ffprobe and downscale based on screen-size targets (e.g., mobile vs.
🌐
Gumlet
gumlet.com › learn › ffmpeg-compress-video
How to compress a video file using FFmpeg? - Gumlet
October 9, 2024 - Using FFmpeg in Python is a great way to reduce video sizes by adjusting bitrate, resolution, or frame rate. Be sure to experiment with various options like CRF, bitrate control, and scaling to find a satisfactory balance between quality and size.
🌐
Cloudinary
cloudinary.com › home › how to compress video size automatically with one line of code
How to Compress Video Size Automatically With One Line of Code
February 9, 2025 - This technique involves applying compression transformation to the videos during upload before storage. Cloudinary makes the process a walk in the park with just one line of code in Ruby, Python, or PHP:
Find elsewhere
🌐
CodeSpeedy
codespeedy.com › home › compress video using moviepy in python
Compress video using moviepy in Python - CodeSpeedy
October 31, 2022 - # Importing the module from moviepy.editor import * # uploading the video we want to edit video = VideoFileClip("coding.mp4") # getting width and height of video 1 width_of_video1 = video.w height_of_video1 = video.h print("Width and Height of original video : ", end = " ") print(str(width_of_video1) + " x ", str(height_of_video1)) print("#################################") # compressing video_resized = video.resize(0.2) # getting width and height of video 2 which is resized width_of_video2 = video_resized.w height_of_video2 = video_resized.h print("Width and Height of resized video : ", end = " ") print(str(width_of_video2) + " x ", str(width_of_video2)) print("###################################") # displaying final clip video_resized.ipython_display()
🌐
YouTube
youtube.com › coffee and python
Compress all videos in folder using python and ffmpeg [Beginner-friendly code] - YouTube
I am showing you how you can use python and ffmpeg to compress an unlimited number of videos in a specified folder. The program works great on Windows, Mac a...
Published: February 27, 2023
Views: 1K
🌐
YouTube
youtube.com › novaspirit tech
Code with me | FFMPEG compressing video | python - YouTube
Coding a much needed task to help save storage space in my NAS. ffmpeg compression video. ○○○ LINKS ○○○ ○○○ SHOP ○○○ Novaspirit Shop ► https://teespring.com/...
Published: November 21, 2019
Views: 7K
🌐
How to use OpenCV
opencvhelp.org › tutorials › advanced › video-compression
Video Compression in OpenCV
pip install opencv-python opencv-python-headless numpy · We’ll start by loading the input video file using OpenCV’s VideoCapture class: import cv2 input_file = 'path/to/input_video.mp4' cap = cv2.VideoCapture(input_file) if not cap.isOpened(): print("Error: Could not open the input video file.") exit() Next, we’ll set up the output video file using OpenCV’s VideoWriter class. We’ll choose the desired compression codec, frame size, and frame rate:
🌐
PyPI
pypi.org › project › CaaS
CaaS · PyPI
It uses Semantic Perceptual Compression algorithm to compress the video files.
      » pip install CaaS
    
Published: May 06, 2020
Version: 1.5
🌐
WinXDVD
winxdvd.com › resize-video › compress-video-with-ffmpeg.htm
FFmpeg Guide - How to Use FFmpeg to Compress Large Video Size
December 26, 2025 - Related: How to Compress Video Media File Size in PowerPoint, Adobe Tutorial: How to Compress Video in Adobe Media Encoder · FFmpeg-python is only a Python wrapper for FFmpeg. You still need to install FFmpeg on Windows or macOS computer. Then make the following script for reducing (MP4/MKV/MOV/WebM, etc.) video size in Python.
🌐
PyPI
pypi.org › project › video-compress
video-compress
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
GitHub
github.com › topics › compress-videos
compress-videos · GitHub Topics · GitHub
2 weeks ago - A sample demo showing how to build ... compress-videos ... The Video&Photo Compressor is a tool designed to reduce the file size of videos and photos while maintaining as much of the original quality as possible....
🌐
Readthedocs
ricecooker.readthedocs.io › en › latest › video_compression.html
Video compression tools — ricecooker 0.1.dev246+g0e94e9391 documentation
Consider also the overall size of the channel—how much storage space will be required for the entire collection of videos? Let’s now look at compression tools that you can use to ensure a good video experience for all Kolibri users, regardless of their device. The ricecooker library can handle the video compression for you if you specify the --compress command line argument to the chef script, e.g. python ...
🌐
DEV Community
dev.to › matetechnologie › building-a-smart-video-compressor-in-python-step-by-step-4f23
Building a Smart Video Compressor in Python (Step-by-Step) - DEV Community
February 21, 2026 - pass1_cmd = [ FFMPEG_PATH, "-y", "-i", self.input_file, "-c:v", self.codec, "-preset", "fast", "-b:v", f"{video_kbps}k", "-pass", "1", "-an", "-f", "null", "-" ] 2-pass encoding gives much more accurate file sizes.
🌐
GitHub
github.com › topics › video-compression
video-compression · GitHub Topics · GitHub
python video image-processing artificial-intelligence image-cropping crops image-resizing vision-framework video-compression frame-extraction ... Compress Videos for Free. Forever. Say goodbye to bulky files! Crush video sizes by 90% with no quality loss, even offline.