Crop Video with Dynamic Time Variables in FFmpeg
This article explains how to dynamically crop a video using FFmpeg by
leveraging variables that change based on the playback time. You will
learn the syntax of the crop filter, how to use the time variable
t to animate the crop area, and see practical command-line
examples to implement this in your video processing workflows.
To crop a video dynamically in FFmpeg, you use the crop
video filter. The standard syntax for this filter is
crop=w:h:x:y, where w and h
represent the width and height of the cropped output, and x
and y represent the horizontal and vertical coordinates of
the top-left corner of the crop box. While the output width and height
must remain constant throughout the video, the coordinates
x and y can be expressed as mathematical
formulas containing the variable t (current timestamp in
seconds) or n (the frame number).
For example, to crop a video to a static size of 400x400 pixels while moving the crop box horizontally from left to right at a rate of 100 pixels per second, you can use the following command:
ffmpeg -i input.mp4 -vf "crop=400:400:100*t:(ih-oh)/2" output.mp4In this command, 100*t calculates the X-coordinate
dynamically. At 0 seconds, x is 0; at 3 seconds,
x becomes 300. The expression (ih-oh)/2
centers the crop vertically, where ih is the input height
and oh is the output height (400).
To prevent the crop area from moving past the boundaries of the
video, which would cause FFmpeg to return an error, you must constrain
the expression using the min or clip
functions. For a 1920x1080 input video, the maximum safe X-coordinate
for a 400-pixel wide crop is 1520 (1920 - 400). You can cap the movement
like this:
ffmpeg -i input.mp4 -vf "crop=400:400:'min(100*t, 1920-400)':(ih-oh)/2" output.mp4Using trigonometric functions like sin or
cos allows you to create continuous, oscillating movement.
The following command sways the cropped window back and forth
horizontally over the center of the video:
ffmpeg -i input.mp4 -vf "crop=400:400:'(iw-ow)/2 + (iw-ow)/2*sin(t)':(ih-oh)/2" output.mp4In this expression, iw and ow represent the
input and output widths. The sin(t) function oscillates
between -1 and 1 as time t progresses, causing the cropped
area to slide smoothly from left to right and back again.