How to Crop Video with a Bouncing Box in FFmpeg

This article explains how to use the FFmpeg crop filter to create a dynamic, bouncing crop box that moves across your video screen. You will learn the exact command-line syntax, how the mathematical expressions control the movement, and how to customize the speed and size of the cropping area.

To create a bouncing crop box in FFmpeg, you must utilize the crop filter with dynamic expressions for the x (horizontal) and y (vertical) coordinates. By using time-based trigonometric functions, you can keep the crop box within the video boundaries while animating it continuously.

The FFmpeg Command

Run the following command in your terminal to apply a bouncing 640x360 crop box to an input video:

ffmpeg -i input.mp4 -vf "crop=640:360:'(in_w-out_w)*(1+sin(1.5*t))/2':'(in_h-out_h)*(1+sin(2.3*t))/2'" -c:a copy output.mp4

How the Command Works

The crop filter uses the syntax crop=w:h:x:y. Here is the breakdown of how the motion is calculated:

  • 640:360: Sets the width (out_w) and height (out_h) of your output crop box.
  • in_w and in_h: Refer to the input video's original width and height.
  • t: Represents the current timestamp of the video in seconds. This variable updates every frame, driving the animation.
  • (in_w-out_w): Represents the maximum range of movement. This ensures the crop box never goes off the edge of the screen.
  • sin(1.5*t) and sin(2.3*t): Generates a smooth wave between -1 and 1. Using different multipliers (frequencies) like 1.5 and 2.3 prevents the box from moving in a boring diagonal line, creating a natural bouncing effect.
  • (1+sin(...))/2: Normalizes the sine wave value to a range between 0 and 1.

When multiplied by the range of movement, the coordinates smoothly oscillate between 0 (the top/left edge) and the maximum safe boundary (the bottom/right edge).

Customizing the Animation

You can easily adjust the parameters to change the behavior of the crop box:

  • Change Crop Size: Modify the first two numbers in the filter. For a square 400x400 crop, use: crop=400:400...
  • Change Movement Speed: Adjust the multipliers inside the sine function. Increasing the number makes the bounce faster. For example, changing 1.5*t to 3*t doubles the horizontal speed.
  • Change the Path Pattern: Adjusting the relationship between the X and Y multipliers will alter the movement pattern. Using uneven ratios (like 1.1 and 2.7) creates more complex, non-repeating paths.