How to Swap Video Regions Using FFmpeg Swaprect

The swaprect filter in FFmpeg allows you to swap two rectangular areas of identical dimensions within the same video frame. This article provides a straightforward guide on how to configure the swaprect filter, explaining its core syntax, parameter options, and practical command-line examples for both static and dynamic swaps.

Understanding the swaprect Syntax

The swaprect filter takes the width and height of the target area, followed by the top-left coordinates of both rectangles you want to interchange.

The basic filter syntax is:

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

Parameters

  • w: The width of the rectangles to swap.
  • h: The height of the rectangles to swap.
  • x1: The horizontal (X) coordinate of the top-left corner of the first rectangle.
  • y1: The vertical (Y) coordinate of the top-left corner of the first rectangle.
  • x2: The horizontal (X) coordinate of the top-left corner of the second rectangle.
  • y2: The vertical (Y) coordinate of the top-left corner of the second rectangle.

Basic Usage Example

To swap a 200x200 pixel area located at (100, 100) with another 200x200 pixel area located at (500, 300):

ffmpeg -i input.mp4 -vf "swaprect=200:200:100:100:500:300" -c:a copy output.mp4

In this command:

  • -vf applies the video filter.
  • -c:a copy keeps the original audio intact without re-encoding.

Using Expressions and Constants

The filter parameters support mathematical expressions and pre-defined variables based on input dimensions:

  • w / in_w: Input video width.
  • h / in_h: Input video height.
  • n: Frame count (starting from 0).
  • t: Timestamp of the frame in seconds.

Example: Swapping the Left and Right Halves of a Video

If you want to swap the left half of a video frame with the right half:

ffmpeg -i input.mp4 -vf "swaprect=w/2:h:0:0:w/2:0" -c:a copy output.mp4

Here:

  • The rectangle width is set to w/2 (half the video width).
  • The rectangle height is set to h (the full video height).
  • The first rectangle starts at (0, 0) (left side).
  • The second rectangle starts at (w/2, 0) (right side).

Example: Dynamic/Moving Swap Over Time

You can use the timestamp variable t to move the swapped area dynamically:

ffmpeg -i input.mp4 -vf "swaprect=150:150:50:50:50+50*t:200" -c:a copy output.mp4

In this example, the second rectangle shifts horizontally across the screen at a rate of 50 pixels per second.

Important Constraints

  • Both rectangles must have identical widths and heights.
  • Both rectangles must remain entirely within the boundaries of the frame; if either rectangle extends past the video edge, FFmpeg will return an error or clip the operation.