Implementing an animated preview generator
Generating animated previews with ffmpeg
The basic command for animated preview generation looks like this:
/opt/bin/ffmpeg \
-y \
-i "yourvideo.mp4" \
-ss 00:00:00.100 \
-filter:v scale=trunc(oh*a/2)*2:480,fps=20 \
-c:v libx264 \
-preset ultrafast \
-crf 28 \
-t 5 \
-an \
"preview.mp4"
An overview of the commands used here:
/opt/bin/ffmpeg | Path to the ffmpeg executable. |
-y | Overwrite the output file if it exists. |
-i "yourvideo.mp4" | The input file to generate a thumbnail from. |
-ss 00:00:00.100 | Seek to 100 milliseconds into the video, i.e. start creating the animated preview from this point. |
-filter:v scale=trunc(oh*a/2)*2:480,fps=20 | Scale the output video resolution to 640x480, without stretching, and set the FPS to 20, which will remove some frames. |
-c:v libx264 | Use the x264 encoder to encode the animated preview. |
-preset ultrafast | Use the ultrafast x264 preset, sacrificing quality and compression efficiency for fast encoding. |
-crf 28 | The CRF for x264 to use. 28 is fairly high (i.e. low quality) as for this purpose we don't need particularly good quality. |
-t 5 | Only use five seconds of the input video, starting from the marker specified in the earlier -ss command. |
-an | Remove the audio track. If you want the audio to be preserved in the animated preview, use "-c:a copy" instead, to copy the existing audio without re-encoding. |
"preview.mp4" | The output file for the animated preview. |
As with thumbnail images, you can choose any point of the video to start from, and any length of time to use, just make sure the start point and length don't go beyond the actual duration of the video.
Why not use WebP for this?
The libwebp encoder (Google's official encoder for the WebP format) is horrendously slow, and equivalent x264-encoded mp4s tend to have better filesizes and quality from my experiments.
If you want the animated preview to behave like a GIF on a webpage, disable the video controls and set it to autoplay with the muted and loop attributes enabled.