Compress Video From Your Terminal With FFmpeg

You know what it's like. We all have plenty of storage space these days but we all also have video files in our archives that are just taking up too much space. There's just no need to have a bunch of 20‑minute MP4s or MKVs taking up 5 to 10 gigs each.

There's plenty of software that will do compression for you and there are plenty of online services too. With both of those options, however, there's likely to be some expense—particularly if you have a lot of large files to process.

However, there is another option, one that can give you a lot more control and flexibility, and that is to compress your files yourself using a free, open source, command line programme called FFmpeg.

Installation (For Mac – You Can Adapt For Your Operating System Easily)

Install Homebrew (if not already installed)


/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
      

Install FFmpeg via Homebrew


brew install ffmpeg
      

Verify the installation


ffmpeg -version
      

Running A Compression Programme

To compress a single video (mp4) you need to CD to the folder containing the video:


cd /path/to/video
      

...and then run the command:


ffmpeg -i input_video.mp4 -vcodec libx264 -crf 23 -preset slow -movflags +faststart output_video.mp4
      

This will create a new, compressed file with the prefix “compressed”. Your old file will still be there when processing is completed.

Compressing Multiple Video Files in a Folder

To compress multiple videos, all you have to do is create a loop. For example:


for file in *.mp4; do
  ffmpeg -i "$file" -vcodec libx264 -crf 26 -preset slow -movflags +faststart "compressed_${file}"
done
      

Working With Different Video File Types

If you want to compress MKV files rather than MP4s, simply change the file type in the command. FFmpeg works with lots of file types. For example, to compress all MKVs in a folder:


for file in *.mkv; do
  ffmpeg -i "$file" -vcodec libx264 -crf 26 -preset slow -movflags +faststart "compressed_${file}"
done
      

How to Set Compression Levels

-crf 26 refers to the compression level. A value of 22 means there is no perceptible loss in quality; a value of 30 might cause a slight but noticeable loss.

-preset slow refers to the speed of the operation. A higher speed setting may not affect the quality of compression but can result in larger file sizes.

-movflags +faststart pushes the video meta to the beginning of the file so that playback can start before compression is complete.

Explore Further

While I have only covered compression here, FFmpeg is a powerful and versatile tool that can perform a wide range of tasks across most video formats. I fully recommend you have a look at what it can do at ffmpeg.org.