FFmpeg VideoToolbox H.264 Hardware Encoding on macOS

Using hardware acceleration for video encoding on macOS can drastically reduce render times and lower CPU usage. This article provides a straightforward guide on how to leverage Apple’s native hardware acceleration API, VideoToolbox, within the FFmpeg command-line tool to perform fast, efficient H.264 video encoding.

Prerequisites

To use VideoToolbox, you must be running macOS and have FFmpeg installed. The easiest way to install FFmpeg with all necessary codecs enabled on macOS is via Homebrew.

Run the following command in your Terminal:

brew install ffmpeg

To verify that your FFmpeg installation supports VideoToolbox, run:

ffmpeg -encoders | grep videotoolbox

You should see h264_videotoolbox listed in the output.

Basic Encoding Command

To encode a video using the VideoToolbox H.264 hardware accelerator, replace the default CPU encoder (libx264) with h264_videotoolbox using the -c:v flag.

Here is the basic command structure:

ffmpeg -i input.mp4 -c:v h264_videotoolbox output.mp4

Controlling Quality and Bitrate

Unlike software encoders that rely heavily on Constant Rate Factor (CRF), hardware encoders like VideoToolbox are optimized for bitrate-targeted encoding.

To control the output size and quality, set a specific video bitrate using the -b:v flag. For example, to set the bitrate to 5 Mbps (5 Megabits per second):

ffmpeg -i input.mp4 -c:v h264_videotoolbox -b:v 5M output.mp4

2. Setting a Constant Quality

If you prefer a variable bitrate based on quality, you can use the -q:v flag. VideoToolbox accepts a scale, typically from 1 to 100, where higher numbers yield better quality but larger files:

ffmpeg -i input.mp4 -c:v h264_videotoolbox -q:v 65 output.mp4

Optimizing for Compatibility

To ensure your output video plays seamlessly on all devices (including older iPads, iPhones, and web browsers), it is best practice to force a widely compatible pixel format and H.264 profile.

Add the following flags to your command: * -pix_fmt yuv420p: Ensures 8-bit YUV 4:2:0 chroma subsampling. * -profile:v high: Uses the High H.264 profile for a better compression-to-quality ratio.

Complete Optimized Example:

ffmpeg -i input.mkv -c:v h264_videotoolbox -b:v 8M -pix_fmt yuv420p -profile:v high -c:a aac -b:a 192k output.mp4

In this optimized command: * -c:v h264_videotoolbox enables Mac hardware-accelerated video encoding. * -b:v 8M sets the video bitrate to 8 Mbps. * -pix_fmt yuv420p ensures maximum player compatibility. * -c:a aac -b:a 192k encodes the audio to standard AAC format at 192 kbps.