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
🌐
Cloudinary
cloudinary.com › home › 3 ways to compress video in python
3 Ways to Compress Video in Python | Cloudinary
April 12, 2026 - It supports a variety of codecs and formats and is extremely efficient for compressing video files. In Python, you can interact with FFmpeg using the subprocess library, which provides a Pythonic interface to FFmpeg’s command-line functionality.
🌐
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
Discussions

How to compress video to target size by Python? - Stack Overflow
I am uploading text and videos to a site by Python program. This site says they only receive video files of up to 50 MB in size. Otherwise, they will reject the video and other associated informati... More on stackoverflow.com
🌐 stackoverflow.com
Fast and efficient media compression codecs
Compression is a compromise between : speed ratio memory Pick 2 of them, but you cannot have all of them. For video the best compression ratio is AV1 + opus, but it is so slow to compute ! H.265 is certainly the most optimized compression algorithm. You could try to use hardware accelerated compression, with video cards (Radeon or Nvidia). For images, avif and jpeg-xl. Jpeg-xl can recompress jpeg without lossing data from the jpeg (the displayed result will be exactly the same). More on reddit.com
🌐 r/compression
6
2
June 23, 2023
Does anyone knows a Python module to convert a video format
Iirc, the ffmpeg python libraries are just wrappers over the ffmpeg executable. ffmpeg-python claims the best filter support. More on reddit.com
🌐 r/pythontips
5
6
September 13, 2024
Analyzing Python Compression Libraries: zlib, LZ4, Brotli, and Zstandard
You need to compare levels to make this useful. Brotli defaults to the maximum level (11) which is why its taking so long -- if you turn it down to 6 you'll get a ~1.17s compression time with a ~57% ratio. Zstandard defaults to 3 on a scale of 22. If you turn it up to 22 you'll get a >100 second compression time and a ~60% ratio. If you go 6 for Brotli and 11 for Zstandard you'll get roughly the same speed (for compression) and ratio. Point is, level matters a lot. There's other factors like streaming performance and window size that you need to account for but bare minimum you need to do like-to-like comparisons on level. More on reddit.com
🌐 r/Python
15
23
April 30, 2024
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.

🌐
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 - Compress MP4 files in Python with only 3 lines of code github: https://github.com/CantCode023/aspose_compressor I’ve been searching for a Python video compression package for quite a while now but …
🌐
PyPI
pypi.org › project › CaaS
CaaS · PyPI
A Python library for Compression as a Service. CaaS can compress images, audio, video, text files
      » pip install CaaS
    
Published: May 06, 2020
Version: 1.5
Find elsewhere
🌐
GitHub
gist.github.com › ESWZY › a420a308d3118f21274a0bc3a6feb1ff
An example Python code for compressing video file to target size. · GitHub
As an idea, the ffmpeg library in Python just calls the ffmpeg binary, you can use this library as an alternative (just rename this library as ffmpeg): https://github.com/althonos/ffpb · https://github.com/althonos/ffpb/blob/da41f96433bfc1...
🌐
PyPI
pypi.org › project › video-compressor
video-compressor · PyPI
Download URL: video_compressor-0.0.6-py2.py3-none-any.whl
      » pip install video-compressor
    
Published: Oct 26, 2020
Version: 0.0.6
🌐
Readthedocs
ricecooker.readthedocs.io › en › latest › video_compression.html
Video compression tools — ricecooker 0.1.dev246+g0e94e9391 documentation
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 chef.py ... --compress. Under the hood, the ffmpeg video conversion program will be called to compress video files before uploading them to Kolibri ...
🌐
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
🌐
GitHub
github.com › topics › video-compression
video-compression · GitHub Topics · GitHub
Tool for automating common video key-frame extraction, video compression and Image Auto-crop/Image-resize tasks · python video image-processing artificial-intelligence image-cropping crops image-resizing vision-framework video-compression frame-extraction
🌐
CodeSpeedy
codespeedy.com › home › compress video using moviepy in python
Compress video using moviepy in Python - CodeSpeedy
October 31, 2022 - In this post, we are going to learn how to compress a video using moviepy in Python. Moviepy is a Python video editing module that allows users to perform basic video editing to a given video.
🌐
PyCon US
us.pycon.org › 2019 › schedule › presentation › 138
Presentation: Framework For Lossless Data Compression Using Python | PyCon 2019 in Cleveland, Ohio
We also make use of the fabulous ffmpy library. ffmpy is a Python library that provides access to the ffmpeg command line utility. ffmpeg is a command-line application that can perform several different kinds of transformations on video files, ...
🌐
Orange
opensource.orange.com › en › langages › python › video-compression-decompression-en
Video compression/decompression software based on PyTorch – Orange Open Source
It is implemented in python using the PyTorch framework. The neural networks are pre-trained and allow video encoding at rates around 1 Mbit/s. It is the reflection of 2 publications presented at international conferences: Conditional Coding for Flexible Learned Video Compression (ICLR 2021) [1][2]
🌐
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 - #productivity #tutorial #python #batch · I am always sharing clips and videos with my friends and often times the file size is ridiculously large to send over most social media (Discord, Twitter, Telegram, etc). To get around these massive file sizes, I use ffmpeg to compress the video. FFMPEG is a super powerful tool for all your media processing. It has a ton of libraries for handling different tasks involving visual and audio media.
🌐
Ijecs
ijecs.in › index.php › ijecs › article › download › 4296 › 3901 pdf
www.ijecs.in
March 3, 2019 - We also make use of the fabulous ffmpy library. ffmpy is a Python library that provides · access to the ffmpeg command line utility. ffmpeg is a command-line application that can perform several · different kinds of transformations on video files, including video compression, which is the ...
🌐
Kaggle
kaggle.com › questions-and-answers › 565587
Video compression Open sourse Library | Kaggle
Could anyone kindly recommend the most effective video compression library that dramatically reduces file sizes
🌐
Reddit
reddit.com › r/compression › fast and efficient media compression codecs
r/compression on Reddit: Fast and efficient media compression codecs
June 23, 2023 -

Hello everyone!

I'm in search of the most efficient open-source compression algorithm for compressing videos and images.

I have a large collection of 1TB of images and videos that I need to upload to Google Drive. Before uploading, I want to compress them to save space.

Currently, I have written a Python script that recursively compresses files. It utilizes FFmpeg with H.265 for videos and MozJPEG for images.

In terms of space efficiency and quality preservation, the script works great. I achieve a compression rate of 60%-80% with no noticeable loss in visual quality.

However, when it comes to speed, it's quite slow. It takes more than 10 minutes to compress every 1GB of data.

Therefore, I am seeking alternative algorithms or codecs that can offer faster compression while delivering similar benefits in terms of space efficiency and quality preservation.