Search code examples
ffmpegtransparencyoverlapanimated-gif

ffmpeg overlay transparent animated gif over video and keep gif background transparency


I'm trying to overlap an animated gif over a video with no success.

My goals are the next:

  1. gif animation have to loop until video ends.
  2. gif is scaled so it covers the whole video.
  3. gif preserves transparency.

The most I have achieved regarding this is that the gif covers the whole video with the scale filter and that it loops until video ends (but this not in the best way, I guess).

Regarding loop I know I can use -ignore_loop 0 gif filter parameter with shortest=1 in overlay but this way it is not working so I ended up with -frames:v 900 (my video is 30fps and 30sec long so 900 is the number of frames).

My most important issue is I'm not able to keep gif transparency and everything I've tried resulted in no success.

This is my ffmpeg command with arguments, so I hope anybody can help (I'm using ffmpeg 4.1).

ffmpeg -y 
-i videoin.mp4 
-i anim01.gif 
-filter_complex [1:v]scale=1080:1920[ovrl] [0:v][ovrl]overlay=main_w-overlay_w:main_h-overlay_h
-frames:v 900 
-codec:a copy
-codec:v libx264
-preset ultrafast
video.mp4

Solution

  • Ok, I'll answer my own question. The first part, not being able to achieve gif transparency, such a silly issue!! The gif I was using was not transparent and I didn't realized!! OMG, I thought, so this is the first thing to check whenever you have a transparency issue.

    The second, looping the gif until the video ends, I wasn't able to do it with -ignore_loop 0 along with shortest=1 but what I did is -ignore_loop 0 and -frames:v 900 and that worked like a charm.

    What was not working was not the -ignore_loop 0 but the shortest=1 and so ffmpeg was never ending encoding but if you set it to finish at a certain number of frames that resolves the problem.

    900 comes from 30fps x 30 sec video.

    In the end, my complete ffmpeg command line parameters ended up as follows:

    ffmpeg -y -i xxx.mp4 -ignore_loop 0 -i xxx.gif -filter_complex "[1:v]scale=1080:1920[ovrl];[0:v][ovrl]overlay=0:0" -frames:v 900 -codec:a copy -codec:v libx264 -max_muxing_queue_size 2048 video.mp4