FFmpeg swaprect Filter Coordinates and Dimensions

The FFmpeg swaprect filter enables you to swap two rectangular regions of identical size within a video stream. This guide provides a straightforward breakdown of how to define the width, height, and positional coordinates for both target rectangles using both positional and named parameters.

Syntax and Parameters

The swaprect filter requires dimensions and positional coordinates for two regions. Both regions must have the exact same width and height.

The basic syntax is:

swaprect=w=WIDTH:h=HEIGHT:x1=X1:y1=Y1:x2=X2:y2=Y2

You can also use positional arguments without names:

swaprect=WIDTH:HEIGHT:X1:Y1:X2:Y2

Here is what each parameter controls:

  • w: The width of the swapped rectangles. The default value is w/2 (half the frame's width).
  • h: The height of the swapped rectangles. The default value is h/2 (half the frame's height).
  • x1: The horizontal (X) coordinate of the top-left corner of the first rectangle. The default is 0.
  • y1: The vertical (Y) coordinate of the top-left corner of the first rectangle. The default is 0.
  • x2: The horizontal (X) coordinate of the top-left corner of the second rectangle. The default is w/2.
  • y2: The vertical (Y) coordinate of the top-left corner of the second rectangle. The default is h/2.

All coordinate systems in FFmpeg measure (0, 0) from the top-left corner of the video frame, with values extending downward and to the right.

Basic Examples

Swapping Fixed-Size Regions

To swap a 200×200 pixel area located at (50, 50) with a 200×200 pixel area located at (400, 300):

ffmpeg -i input.mp4 -vf "swaprect=w=200:h=200:x1=50:y1=50:x2=400:y2=300" -c:a copy output.mp4

Using shorthand positional arguments, the equivalent command is:

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

Using Dynamic Expressions

The swaprect filter allows arithmetic expressions and internal video variables rather than static numbers:

  • w / W: Input frame width.
  • h / H: Input frame height.
  • a: Video aspect ratio (w / h).
  • sar: Sample aspect ratio.
  • dar: Display aspect ratio.

Swapping the Left and Right Halves of a Video

To divide a video directly down the center and swap the left and right halves:

ffmpeg -i input.mp4 -vf "swaprect=w=iw/2:h=ih:x1=0:y1=0:x2=iw/2:y2=0" -c:a copy output.mp4

Swapping Top and Bottom Halves

To split a frame horizontally and swap the upper and lower halves:

ffmpeg -i input.mp4 -vf "swaprect=w=iw:h=ih/2:x1=0:y1=0:x2=0:y2=ih/2" -c:a copy output.mp4

Swapping Diagonally Opposite Corners

To swap a 100×100 box in the top-left corner with a 100×100 box in the bottom-right corner dynamically:

ffmpeg -i input.mp4 -vf "swaprect=w=100:h=100:x1=0:y1=0:x2=w-100:y2=h-100" -c:a copy output.mp4

Ensure that your calculated areas do not exceed the boundary dimensions of the source video frame to avoid filter initialization errors.