How to Move FFmpeg Overlay in a Circle
This article explains how to program an overlay video or image to
move in a continuous circle over a background video using the FFmpeg
overlay filter. By utilizing mathematical expressions with
sine and cosine functions based on the timestamp variable, you can
precisely control the radius, center, and speed of the circular
motion.
To move an overlay in a circle, you must dynamically calculate its X
and Y coordinates for every frame. In mathematics, circular motion is
plotted using cosine for the X-axis and sine for the Y-axis. FFmpeg
allows you to implement these trigonometric functions directly within
the overlay filter using the t (time in
seconds) variable.
The Basic Command Syntax
Here is the standard FFmpeg command to overlay an image
(logo.png) onto a background video
(background.mp4) in a circular path:
ffmpeg -i background.mp4 -i logo.png -filter_complex "overlay=x='(W-w)/2 + 200*cos(2*t)':y='(H-h)/2 + 200*sin(2*t)'" output.mp4Deconstructing the Math
The overlay filter uses the x and
y parameters to position the top-left corner of the
overlay. To create a perfect circle, the formulas are broken down as
follows:
- Centering the Circle (
(W-w)/2and(H-h)/2):WandHrepresent the width and height of the main background video.wandhrepresent the width and height of the overlay input.- Subtracting the overlay size from the background size and dividing by two centers the starting point of the circle on the screen.
- Defining the Radius (
200*):- The multiplier before the cosine and sine functions determines the radius of the circular path in pixels. In the example above, the circle has a radius of 200 pixels. Increasing this number makes a wider circle; decreasing it makes a tighter circle.
- Calculating the Angle over Time (
cos(2*t)andsin(2*t)):tis the current playback time of the video in seconds. As time progresses, the angle changes, moving the overlay along the path.- The multiplier inside the parenthesis (in this case,
2) controls the speed of the rotation. A value of2means the overlay will complete one full rotation every \(\pi\) seconds (approximately 3.14 seconds). Increasing this number speeds up the rotation, while decreasing it slows it down.
Adjusting Direction and Starting Point
You can customize the motion further by modifying the mathematical
operators: * Change Direction: To make the overlay
rotate counter-clockwise instead of clockwise, change the plus sign in
the Y expression to a minus sign:
y='(H-h)/2 - 200*sin(2*t)'. * Change the Starting
Position: To change where the overlay begins its loop at
t=0, you can add a phase shift (in radians) inside the sine
and cosine functions, such as cos(2*t + 1.57).