How to Use FFmpeg swaprect Filter to Swap Video Areas

The FFmpeg swaprect video filter allows you to swap two rectangular areas of the same size within a video frame. This article provides a quick and clear guide on how to use this filter, detailing its syntax, parameters, and practical command-line examples to help you easily exchange video regions.

Understanding the swaprect Syntax

The swaprect filter requires you to define the dimensions of the rectangles and the top-left coordinates of both areas you wish to swap. Both rectangles must have the exact same width and height.

The basic syntax is as follows:

swaprect=w:h:x1:y1:x2:y2

Parameter Breakdown

You can use constants within these parameters, such as: * w or h: Width or height of the rectangle itself. * iw or ih: Input video width or height. * a: Aspect ratio of the input video.

Practical Example

Suppose you have a 1920x1080 video, and you want to swap a 300x300 pixel area in the top-left corner with a 300x300 pixel area in the top-right corner.

The FFmpeg command to perform this swap is:

ffmpeg -i input.mp4 -vf "swaprect=300:300:0:0:1620:0" output.mp4

Using Dynamic Expressions

You can also use mathematical expressions to determine the coordinates dynamically. For example, to swap the left half of a video with the right half of the same video, you can use the input width (iw) and input height (ih) variables.

To swap two vertical halves of a 1920x1080 video (each half being 960 pixels wide and 1080 pixels high):

ffmpeg -i input.mp4 -vf "swaprect=iw/2:ih:0:0:iw/2:0" output.mp4

In this command: * iw/2 sets the width of the swap area to half the video width. * ih sets the height to the full video height. * 0:0 targets the left half of the screen. * iw/2:0 targets the right half of the screen starting at the midpoint.