Blogs
Setting up a terminal to be fast and charming
💻
2022-10-03
Better GIF quality with FFmpeg
📺
2022-10-02
Asymmetric encryption with the power of symmetric encryption in Node.js
🔑
2021-12-12
Creating customized blog using Gatsby + Notion
🧭
2021-07-09
Fixing ambiguous AWS ELB 504 random errors at scale
🤕
2020-08-12

Better GIF quality with FFmpeg

📺 | 2022-10-02

App link: MP4 to GIF converter

I was recently facing a problem with the quality of GIFs on Crusher's README page. Check before/after version here.

Even with good resolution, the conversion quality was not up to the mark.

Before:


After:

After stumbling on the internet while scratching my head, I came across a post by Threads (implementation doesn't work) and one on pkh.com.

1st culprit: standard palette

The default GIF algorithm conversion process uses 256 standard colors. This is done to cover all varieties of content.

With standard palette, we generally see gradient banding and out-of-place pixel colors.

Solution: In general for our use case, we don't use all the colors. Generating our own color palette can be a good way to overcome this.

We will use the palettegen tool to generate a palette.

2nd culprit: Dithering

Dithering is a way to correct colors in spatial space range. Here is an example of an image with limited color set, without and with proper dithering.

We're going to use Floyd–Steinberg dithering; it worked the best for us. We'll use the paletteuse tool to generate the code. You can experiment with different dithering modes.

FFmpeg script

Here's a bash script to convert MP4 to GIF:

filename=$(basename -- "$1")
pattern_name="${1}.png"
gif_name="${1}.gif"
filters="fps=15,scale=1080:-1:flags=lanczos"

ffmpeg -v warning -i $1 -vf "$filters,palettegen" -y $pattern_name
ffmpeg -v warning -i $1 -i $pattern_name -lavfi "$filters [x]; [x][1:v] paletteuse=dither=floyd_steinberg" -y $gif_name

Deploying with Streamlit

Streamlit is a fantastic tool to convert Python-based programs to fully functional web apps. It is mainly used for data models, but we used it to deploy our nifty tool. And within a few hours, we had a properly running app.

It is a framework + infrastructure with Streamlit Cloud. The only con is that we don't have GPU access.

For that, we should use Gradio on Hugging Face Space.