Reverse Video in FFmpeg with setpts Filter
Reversing video playback in FFmpeg requires reordering the video
frames and resetting their presentation timestamps so the media player
can read them correctly. While the reverse filter does the
job of flipping the frame sequence, the setpts filter is
essential for regenerating the Presentation Timestamps (PTS) so that the
reversed video plays smoothly from the beginning. This article provides
the exact commands and explanations needed to reverse both video and
audio using FFmpeg.
The Command to Reverse Video
To reverse a video and correct its timestamps, use the following command in your terminal:
ffmpeg -i input.mp4 -vf "reverse,setpts=PTS-STARTPTS" output.mp4How the Filters Work
reverse: This filter reverses the video frames. It buffers the clip and outputs the frames in reverse order.setpts=PTS-STARTPTS: Thesetpts(Set Presentation Timestamp) filter modifies the timestamp of each frame. When frames are reversed, their original timestamps become disordered. ApplyingPTS-STARTPTSresets the timestamps to start at zero and increment consecutively, ensuring smooth playback and preventing media players from freezing.
Reversing Both Video and Audio
The basic command only reverses the video track. If your video has
audio, you must also reverse the audio stream using the
areverse filter to keep them in sync:
ffmpeg -i input.mp4 -vf "reverse,setpts=PTS-STARTPTS" -af "areverse" output.mp4-vf: Specifies the video filter chain (reversefollowed bysetpts).-af: Specifies the audio filter (areverse).
Memory Limitations
The reverse and areverse filters load the
entire video and audio streams into your system memory (RAM) to perform
the reversal.
Because of this, the process is highly memory-intensive: * Short clips (under 15 seconds) will process quickly and smoothly. * Long videos may crash FFmpeg or freeze your system due to running out of RAM. For longer files, it is best to slice the video into smaller segments, reverse each segment, and then concatenate them back together.