Sometimes, I would need to generate GIFs from videos of certain file size limits, convert from one video format to another. While there are lots of online conversion tools available, they don’t provide privacy for the data and usually they don’t have too many options. FFmpeg, which is open source and has been used in all those online conversion tools, has become my companion.
In this blog post, I am going to introduce some basic usages of FFmpeg for video processing and conversion.
Ubuntu 18.04 LTS
$ sudo apt-get update $ sudo apt-get install ffmpeg
Pixabay provides a lot of royalty-free images and videos. Let’s get a 4K squirrel video from Pixabay.
$ wget https://pixabay.com/videos/download/video-948_source.mp4 $ ls -lh video-948_source.mp4 -rw-r--r-- 1 leimao leimao 52M Feb 3 2017 video-948_source.mp4
This 10-second 4K MP4-format video takes 52MB.
Convert Video to GIF
We use the default settings to convert with multithreads to accelerate the process.
$ ffmpeg -i video-948_source.mp4 -threads 16 video-948_source.gif $ ls -lh video-948_source.gif -rw-r--r-- 1 leimao leimao 1.4G Dec 16 18:42 video-948_source.gif
Holy! The size of the generated GIF is 1.4GB! We need to do something to reduce the size.
There are generally a couple of ways to achieve this:
- Reduce resolution
- Reduce FPS (frame per second)
In this case, I did:
$ ffmpeg -i video-948_source.mp4 -ss 1 -t 5 -vf fps=10,scale=480:-1 -threads 16 video-948_source.gif $ ls -lh video-948_source.gif -rw-r--r-- 1 leimao leimao 3.1M Dec 16 18:54 video-948_source.gif
-ssis the starting time of the video clip from the original video. In this case, it is 1 second.
-tis the duration of the video clip from the original video. In this case, it is 5 seconds.
-vfis the filter_graph. In this case, I set the FPS to be 10 and reduce the resolution to be 3840 × 2160 to 480 × 270.
The size of the generated GIF this time is 3.1MB. This is quite suitable for many purposes.
FFmpeg could do conversions between different formats, such as MP4 to AVI, etc. Simply change the
gif in the command to
avi and you are all set.
There are also more sophisticated options from FFmpeg, please check
ffmpeg --help for more details.