Loop Video Overlays in FFmpeg Using movie and amovie

This guide explains how to use FFmpeg's movie and amovie source filters to overlay a looping video and audio file onto a primary video. You will learn the exact command-line syntax required to repeat an overlay clip indefinitely and sync it seamlessly with your main media.

The Looping Command

To overlay a looping video (with audio) onto a main video, you must load the overlay file directly inside the filtergraph using the movie (for video) and amovie (for audio) filters. This allows you to utilize the loop parameter.

Here is the complete command to achieve this:

ffmpeg -i main_video.mp4 -filter_complex \
"movie=overlay.mp4:loop=0,setpts=N/FRAME_RATE/TB[over_v]; \
 amovie=overlay.mp4:loop=0,asetpts=N/SR/TB[over_a]; \
 [0:v][over_v]overlay=10:10:shortest=1[out_v]; \
 [0:a][over_a]amix=inputs=2:duration=first[out_a]" \
 -map "[out_v]" -map "[out_a]" -c:v libx264 -c:a aac output.mp4

How the Filters Work

Using movie and amovie requires resetting the presentation timestamps (PTS) of the looping stream so FFmpeg knows how to render the repeating frames and audio samples.

1. Loading and Looping the Streams

  • movie=overlay.mp4:loop=0: Loads the overlay video. Setting loop=0 instructs FFmpeg to loop the video infinitely.
  • setpts=N/FRAME_RATE/TB: This is a critical step. When a video loops, its internal timestamps must be regenerated sequentially. This expression resets the timestamps based on the frame count (N), frame rate, and time base (TB), preventing the video from freezing after the first loop plays.
  • amovie=overlay.mp4:loop=0: Loads the overlay audio and loops it infinitely.
  • asetpts=N/SR/TB: Resets the audio timestamps sequentially using the sample count (N), sample rate (SR), and time base (TB) to ensure continuous, uncorrupted audio playback.

2. Merging the Streams

  • [0:v][over_v]overlay=10:10:shortest=1[out_v]: Positions the looped overlay video onto the main video at the coordinates x=10 and y=10. The shortest=1 parameter is vital; it tells FFmpeg to stop encoding as soon as the main video (the shortest finite stream) ends, preventing the infinite loop from running forever.
  • [0:a][over_a]amix=inputs=2:duration=first[out_a]: Mixes the background audio from the main video with the looping audio from the overlay. The duration=first parameter ensures the audio stream cuts off when the main input video ends.

3. Mapping and Encoding

  • -map "[out_v]" -map "[out_a]": Directs FFmpeg to use the processed video and audio outputs from the filtergraph for the final file.
  • -c:v libx264 -c:a aac: Encodes the output video to H.264 format and the audio to AAC format.