A 2-pass encoding (or two-pass encoding) is a video compression technique that processes your video twice to achieve better quality for a given file size.
Here's how it works:
First Pass: The encoder analyzes the entire video without actually creating a final output file. It collects data about scene complexity, motion, and other characteristics throughout the video. During this phase, it's just gathering information and creating statistical data about the video.
Second Pass: The encoder uses the analysis data from the first pass to make smarter decisions about how to allocate bits. It can assign more bits to complex scenes that need them and fewer bits to simpler scenes, resulting in more consistent quality throughout.
The benefits of 2-pass encoding include:
- More efficient use of the target bitrate
- More consistent quality across the entire video
- Better handling of complex scenes
- Better overall quality-to-size ratio
The downside is that encoding takes approximately twice as long as single-pass encoding. However, for final distribution versions of videos (especially when file size constraints are important), the quality improvement is often worth the extra processing time.
Let's take as example:
ffmpeg -i input.mp4 -c:v libx264 -preset medium -b:v 1500k -pass 1 -an -f mp4 /dev/null && \
ffmpeg -i input.mp4 -c:v libx264 -preset medium -b:v 1500k -pass 2 -c:a aac -b:a 128k -movflags +faststart output.mp4
This command performs a 2-pass encoding of a video file for optimal quality-to-size ratio. The first command runs the first pass of the encoding process, while the second command runs the second pass and creates the final output file.
First pass:
-i input.mp4Specifies the input video file-c:v libx264Uses H.264 video codec-preset mediumBalances encoding speed and compression efficiency-b:v 1500kSets target video bitrate to 1500 kbps-pass 1Indicates this is the first pass (analysis phase)-anDisables audio processing (not needed for first pass)-f mp4Forces MP4 format output/dev/nullDiscards the actual output (only statistics are needed)
Second pass:
- Uses the same input and video settings
-pass 2Indicates this is the second pass (encoding with knowledge from first pass)-c:a aacEncodes audio using AAC codec-b:a 128kSets audio bitrate to 128 kbps-movflags +faststartOptimizes for web streaming
The && operator ensures the second command only runs if the first succeeds. This method
produces better quality at the same file size compared to single-pass encoding.