In today's web-centric world, optimizing video content for fast loading times is crucial. Large video files can hinder website performance, affecting user experience and search engine rankings. Fortunately, FFmpeg—a powerful open-source multimedia framework—provides tools to compress videos without significant loss of quality, enhancing web performance and providing a better experience for your users.

Understanding video codecs and formats

Before diving into compression techniques, it's important to understand video codecs and container formats. A codec is a program that encodes and decodes digital video data. Common video codecs include H.264, H.265 (HEVC), VP9, and AV1. A container format (like MP4, MKV, or WebM) holds the video, audio, and metadata in a single file.

For web videos, the H.264 codec within an MP4 container is widely supported and offers a good balance between quality and file size. Newer codecs like H.265 and AV1 provide better compression but may have limited browser support.

Installing FFmpeg on your system

FFmpeg is a free, open-source tool for handling multimedia files. You can install it on various operating systems:

macOS

Install FFmpeg using Homebrew:

brew install ffmpeg

Linux

For Debian/Ubuntu-based systems:

sudo apt update
sudo apt install ffmpeg

For Fedora:

sudo dnf install ffmpeg

Windows

Download the latest FFmpeg build from the official website. Extract the files and add the bin folder to your system's PATH environment variable.

Alternatively, you can use Chocolatey to install FFmpeg:

choco install ffmpeg

Basic video compression with FFmpeg

Reducing video file size

To reduce video file size using FFmpeg while maintaining quality, you can re-encode the video with a lower bitrate or use a more efficient codec.

Here's a basic command to compress a video using the H.264 codec:

ffmpeg -i input.mp4 -c:v libx264 -crf 23 output.mp4
  • -i input.mp4: Specifies the input file.
  • -c:v libx264: Uses the H.264 codec for video encoding.
  • -crf 23: Sets the Constant Rate Factor, controlling quality (lower values mean higher quality). The CRF scale ranges from 0 (lossless) to 51 (worst quality). A value between 18–28 is common; 23 is the default.
  • output.mp4: The output file.

Optimizing for web playback

To ensure your video is optimized for web playback, include the -preset and -movflags options:

ffmpeg -i input.mp4 -c:v libx264 -crf 23 -preset slow -movflags +faststart output.mp4
  • -preset slow: Determines the encoding speed versus compression efficiency. Slower presets yield better compression but take longer to encode. Options include ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow.
  • -movflags +faststart: Moves metadata to the beginning of the file to enable progressive streaming, which is beneficial for web playback.

Advanced compression techniques with FFmpeg

Two-pass encoding

When targeting a specific file size or bitrate, two-pass encoding allows FFmpeg to analyze the video first to optimize bitrate allocation, improving overall quality.

First pass:

ffmpeg -y -i input.mp4 -c:v libx264 -b:v 1000k -pass 1 -an -f null /dev/null

Second pass:

ffmpeg -i input.mp4 -c:v libx264 -b:v 1000k -pass 2 -c:a aac -b:a 128k output.mp4
  • -b:v 1000k: Sets the video bitrate to 1000 kbps.
  • -pass 1 and -pass 2: Indicates the pass number.
  • -an: Disables audio during the first pass.
  • -f null /dev/null: Discards the output of the first pass.
  • -c:a aac -b:a 128k: Sets the audio codec to AAC with a bitrate of 128 kbps.

Using more efficient codecs

Consider using codecs like H.265 (HEVC) or VP9 for better compression efficiency. They can produce smaller files at the same quality compared to H.264 but may have compatibility limitations.

H.265 Example:

ffmpeg -i input.mp4 -c:v libx265 -crf 28 output_hevc.mp4
  • -c:v libx265: Uses the H.265 encoder.
  • -crf 28: Sets the CRF for H.265 (the scale differs from H.264; higher values mean lower quality).

VP9 Example:

ffmpeg -i input.mp4 -c:v libvpx-vp9 -b:v 0 -crf 30 output_vp9.webm
  • -c:v libvpx-vp9: Uses the VP9 encoder.
  • -b:v 0: Enables constant quality mode.
  • -crf 30: Sets the CRF for VP9 encoding.

Note: Ensure that your target audience's browsers and devices support these codecs.

Comparing quality and file size

After compression, it's important to evaluate the quality of the output video against the original.

Using ffplay

You can preview the video using FFplay:

ffplay output.mp4

Checking file size

Use the ls command to compare file sizes:

ls -lh input.mp4 output.mp4

Automating batch video compression

If you have multiple videos to compress, automate the process using a simple shell script.

Bash script example

#!/bin/bash

input_dir="/path/to/videos"
output_dir="/path/to/output"

mkdir -p "$output_dir"

for file in "$input_dir"/*.mp4; do
  filename=$(basename "$file")
  ffmpeg -i "$file" -c:v libx264 -crf 23 "$output_dir/${filename%.*}_compressed.mp4"
done
  • Replace /path/to/videos with the directory containing your videos.
  • The script loops through each .mp4 file and compresses it.
  • mkdir -p "$output_dir" ensures the output directory exists.

Windows batch script example

Create a compress.bat file:

@echo off
set input_dir=C:\path\to\videos
set output_dir=C:\path\to\output

if not exist "%output_dir%" (
  mkdir "%output_dir%"
)

for %%a in ("%input_dir%\*.mp4") do (
  ffmpeg -i "%%a" -c:v libx264 -crf 23 "%output_dir%\%%~na_compressed.mp4"
)
  • Adjust the paths accordingly.
  • The script compresses all .mp4 files in the specified directory.

Conclusion and best practices

By leveraging FFmpeg's powerful command-line capabilities, you can significantly reduce video file sizes for better web optimization. Remember to balance compression settings to maintain acceptable video quality.

Best practices

  • Use Appropriate Codecs: Choose codecs based on your audience's device and browser support.
  • Experiment with CRF Values: Test different CRF settings to find the optimal balance between quality and file size.
  • Consider Browser Compatibility: Newer codecs may not be supported on all platforms.
  • Utilize Batch Processing: Automate compression for multiple files to save time.

For an automated solution that handles video encoding and optimization at scale, consider using Transloadit's video encoding service, which leverages FFmpeg under the hood to streamline your media processing needs.