How to compress a video file using FFmpeg?

Learn how to compress video files effectively using FFmpeg. This guide will teach you about different techniques and bitrate adjustments for compressing video files for storage and sharing.

FFmpeg Compress Video
How to compress a video file using FFmpeg?

FFmpeg, a versatile open-source multimedia framework, offers a plethora of options for optimizing your videos. Let's dive in and go through the essential steps of compressing your videos using FFmpeg.

How to compress a video file using FFmpeg?

FFmpeg is a powerful, open-source command-line tool that helps in processing and compressing video files by adjusting codecs, resolution, bitrate, and other video attributes. Below, we’ll cover several techniques for compressing videos using FFmpeg.

1. Changing Video Codec

The first and most common way to compress a video file is by changing the codec, which refers to the algorithm that compresses and decompresses video data. Codecs like H.264 (for MP4) and H.265 offer great compression with minimal quality loss.

Example command to compress video using the H.264 codec:

ffmpeg -i sample_input.mov -c:v libx264 -pix_fmt yuv420p compressed_output.mp4

Here:

  • -i sample_input.mov: This specifies the input video file.
  • -c:v libx264: Sets the video codec to H.264 for compression.
  • -pix_fmt yuv420p: Changes the pixel format to one compatible with H.264.
  • compressed_output.mp4: This is the compressed output video file in MP4 format.

For greater compression, you can use the H.265 codec, though it may require extra software to be played.

It is worth noting you could use other codecs and file formats (containers) to compress the video. For example, you could use the H.265 codec as an MP4 file, or you could use the VP9 codec as a WebM file. H.265 offers smaller file sizes but may not be compatible with all devices. VP9 provides good quality but might result in slower encoding and a slightly larger file.

Command for compressing with H.265:

ffmpeg -i sample_input.mov -c:v libx265 -pix_fmt yuv420p compressed_output_h265.mp4

Alternatively, for WebM format, use the VP9 codec:

ffmpeg -i sample_input.mov -c:v libvpx-vp9 -pix_fmt yuv420p compressed_output_vp9.webm

2. Reducing Video Resolution (Downscaling)

Another effective method of compressing a video is reducing its resolution. Downscaling the resolution is a practical solution if your video will be primarily viewed on mobile devices or smaller screens.

Command to reduce the resolution to 1280x720:

ffmpeg -i sample_input.mov -c:v libx264 -pix_fmt yuv420p -vf scale=1280:720 smaller_output.mp4

-vf scale=1280:720 applies a scaling filter to change the resolution to 1280x720 pixels.

If you want to preserve the original aspect ratio but only change one dimension (e.g., the height), use:

ffmpeg -i sample_input.mov -c:v libx264 -pix_fmt yuv420p -vf scale=-1:720 output_720p.mp4

3. Modifying the Video Bitrate

Lowering the bitrate reduces video size but may also impact the quality. With the bitrate, you can control how much data is used per second of the video.

ffmpeg -i sample_input.mov -c:v libx264 -pix_fmt yuv420p -b:v 1000k -vf scale=-1:720 reduced_bitrate.mp4

-b:v 1000k: This sets the video bitrate to 1000 Kbps

4. Using Constant Rate Factor (CRF) for Compression

The Constant Rate Factor (CRF) is an easy way to control the quality versus size balance during video compression. A CRF value between 0 (highest quality) and 51 (lowest quality) helps control how much the video is compressed.

ffmpeg -i sample_input.mov -c:v libx264 -pix_fmt yuv420p -crf 28 crf_compressed_output.mp4

Here, 

  • -crf 28 indicates the CRF value for compression. Lower values result in higher quality and larger files, and vice-versa.

Below is a table of recommended CRF values for different levels of quality:

Quality Level CRF Value
High Quality 18-20
Medium Quality 21-23
Lower Quality 24-28

There are other options in FFmpeg to fine-tune your video compression process to optimize the balance between encoding speed, file size, and quality.

ffmpeg -i sample_input.mov -c:v libx264 -pix_fmt yuv420p -crf 28 -preset faster -tune zerolatency -c:a aac fine_tuned_output.mp4

Here,

  • -preset faster: Determines the encoding speed. Available presets include ultrafast, fast, medium, slow, and slower. Faster presets result in quicker compression at the expense of efficiency, while slower presets improve compression but take more time.
  • -tune zerolatency: This tuning option optimizes for scenarios where low-latency is required, such as live streaming.
  • -c:a aac: Compresses the audio stream using the AAC codec to further reduce file size.

Other video compression techniques with FFmpeg

Apart from the common methods like modifying codecs, resolution, and bitrates, FFmpeg also offers additional techniques to reduce video file sizes, such as: Frame Rate Reduction and Audio Compression.

Reducing the Frame Rate

The frame rate determines how many frames are displayed per second in a video (measured in frames per second, or fps). A higher frame rate provides smoother playback but leads to larger file sizes. By reducing the frame rate, you can compress the video while still maintaining acceptable visual quality, particularly for videos that don’t require very high frame rates (e.g., non-action footage or instructional videos).

Command to reduce frame rate to 20 fps:

ffmpeg -i video_sample.mov -c:v libx264 -pix_fmt yuv420p -vf scale=-1:720 -r 20 output_reduced_fps.mp4

When applied alone, reducing the frame rate from 30 fps to 20 fps can lower the file size slightly. You can experiment with different frame rates (e.g., 15 fps or lower) based on your video content and use case

ffmpeg -i video_sample.mov -c:v libx264 -pix_fmt yuv420p -r 20 output_simple_fps.mp4

Audio Compression

Another way is by reducing the audio bitrate; lowering the audio bitrate can compress the video further while retaining reasonable sound quality. Here's how:

ffmpeg -i video_sample.mov -c:v libx264 -pix_fmt yuv420p -b:v 900k -b:a 96k -vf scale=-1:720 output_compressed_audio.mp4

If your video has an audio track, this can significantly reduce the overall file size. Make sure you experiment with different audio bitrates (e.g., 128 Kbps or lower) to see how much compression is satisfactory to you.

How to compress video to a specific size using FFmpeg?

If you want your video to be compressed to an exact file size, you can use two-pass encoding in FFmpeg. This method lets FFmpeg analyze the video in the first pass and adjust the bitrate in the second pass. Here's a step-by-step guide to ffmpeg compress video to specific size: 

Step 1: First, you need to calculate the video’s required bitrate based on the length of the video and the target file size:

Bitrate (kBit/s) = (Target Size in MiB * 8388.608) / Video Duration in Seconds

For instance, if you want a 15-minute (900 seconds) video to be 300 MiB, you would calculate the bitrate like this:

(300 MiB * 8388.608) / 900 seconds ≈ 2796 kBit/s (total bitrate)

Next, subtract the audio bitrate (e.g., 128 kBit/s) from the total bitrate to get the video bitrate:

2796 kBit/s - 128 kBit/s (audio bitrate) = 2668 kBit/s (video bitrate)

Now you're ready for the two-pass encoding process.

Step 2: The first pass analyzes the video and generates a log file without producing an actual output file. Here’s the command to run:

ffmpeg -y -i myvideo.mov -c:v libx264 -b:v 2668k -pass 1 -an -f null /dev/null

Here, 

  • -y: Overwrites existing files without prompting.
  • -i myvideo.mov: Specifies your input video.
  • -c:v libx264: Sets the H.264 codec for video compression.
  • -b:v 2668k: Assigns the calculated video bitrate.
  • -pass 1: Indicates this is the first pass.
  • -an: Disables audio for this pass (audio will be added in the second pass).
  • -f null /dev/null: Sends the output to a null file (it won’t produce an actual file, just a log).

Step 3: Now, you will run the second pass to encode the video based on the analysis from the first pass.

ffmpeg -i myvideo.mov -c:v libx264 -b:v 2668k -pass 2 -c:a aac -b:a 128k final_video.mp4

Here,

  • -pass 2: Executes the second pass.
  • -c:a aac: Uses the AAC codec for audio.
  • -b:a 128k: Sets the audio bitrate to 128 kBit/s.
  • final_video.mp4: The name of the output video file.

Step 4: You can fine-tune the encoding process for quality and speed by adding more parameters like: -preset medium, -tune film, -profile:v high: Ensures compatibility with a variety of devices while optimizing compression.

How to Reduce Video Size using FFmpeg in Python?

FFmpeg is a potent tool for video compression; you can easily use it with Python for automating the task of reducing video size. 

Here’s how you can reduce the size of a video file using FFmpeg in Python:

Step 1: The Python package ffmpeg-python is a wrapper for FFmpeg, so you still need to install FFmpeg on your computer for it to work. Be sure to add FFmpeg to your system's PATH so that it can be accessed from the command line.

Step 2: Now, let’s create a simple Python script to compress a video by reducing its bitrate. Here’s the code:

import subprocess
# FFmpeg command to compress the video
command = 'ffmpeg -i input_video.mov -b:v 900k output_video.mp4'
# Run the command using subprocess
process = subprocess.run(command, shell=True)
# Print the result to verify success
print(process)

Step 3: If you get the error "FileNotFoundError: [WinError 2] The system cannot find the file specified", this means FFmpeg is not installed or is not set up correctly on your system.

Step 4: Once your script is ready and FFmpeg is installed, run the Python script:

python compress_video_script.py

This will compress the video using the settings you provided, for instance reduce the bitrate to lower the file size.

You also reduce the resolution of the video using FFmpeg in Python:

import subprocess
# FFmpeg command to reduce video resolution and size
command = 'ffmpeg -i input_video.mov -vf scale=1280:-1 -b:v 800k resized_video.mp4'
# Run the command
process = subprocess.run(command, shell=True)
# Output the result
print(process)

Closing Remarks

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. If you manage online videos and need optimal compression without hassle, Gumlet offers per-title encoding and advanced compression technologies. It is a great option for automatically adjusting video quality.without the need for manual FFmpeg adjustments.

FAQs

How to compress a GIF file using FFmpeg?

If you need to make a GIF file smaller, FFmpeg offers a straightforward way to do it by adjusting the frame rate and resizing the dimensions. Here’s how you can use FFmpeg to compress your GIF:

ffmpeg -i original.gif -filter_complex "fps=8,scale=-1:300" smaller.gif

After running this command, the smaller.gif file will be much lighter—in this example, it’s reduced from 120MB to just 8MB. While the animation might not be as fluid as the original, it’s still viewable and far more manageable.

How do I scale down a video to 720p in FFmpeg?

To resize a video to 720p while preserving the aspect ratio with FFmpeg, you can use the scale filter. This way the video won’t get stretched or look odd. Here’s a quick example on how to resize your video to a width of 720 pixels:

ffmpeg -i sample.mp4 -vf "scale=720:-1" resized_video.mp4

The height is set to -2, which means FFmpeg will automatically calculate the height to keep the aspect ratio intact and ensure that it is divisible by 2.

How do I reduce the resolution of a MP4 video in FFmpeg?

You can adjust both the width and height to reduce the resolution using FFmpeg. Here’s an example of how to resize a video to 50% of its original dimensions:

ffmpeg -i myvideo.mp4 -vf "scale=iw/2:ih/2" smaller_video.mp4

-vf "scale=iw/2:ih/2" tells FFmpeg to set the video’s width and height to half of their original sizes. The iw and ih represent the input video's width and height, respectively.

How to increase the speed of FFmpeg compression?

To make FFmpeg compress videos more quickly, you can adjust several settings to prioritize speed. Here’s an example:

ffmpeg -y -i input.mp4 -s 1280x720 -r 10 -c:v libx264 -b:v 800k -b:a 192k -ac 2 -ar 44100 -preset ultrafast output.mp4

Here,

  • -s 1280x720 sets the output resolution to 720p.
  • -r 10 sets the frame rate to 10 frames per second, which can help speed up processing.
  • -c:v libx264 uses the H.264 codec for video encoding.
  • -b:v 800k sets the video bitrate to 800 kbps.
  • -b:a 192k sets the audio bitrate to 192 kbps.
  • -ac 2 configures audio to use 2 channels.
  • -ar 44100 sets the audio sample rate to 44.1 kHz.
  • -preset ultrafast optimizes the encoding process for speed.

How to compress video without losing quality in FFmpeg?

To compress a video while maintaining its quality, you can convert it to the H.265 codec with FFmpeg. This codec is known for its efficient compression, often reducing file sizes by 2 to 8 times without a significant loss in quality. Here’s how you can do it:

ffmpeg -i input.mp4 -c:v libx265 -crf 28 -preset medium output.mp4
Images or Videos Loading Slow?

We compress them so your users don't need to wait.