How to Use FFmpeg Loop Filter for Video Frames

To loop a specific sequence of frames within a video stream using FFmpeg, you need to use the video loop filter. This article provides a direct, step-by-step guide on how to configure this filter, explaining its key parameters—loop, size, and start—and demonstrates how to construct the exact command to achieve seamless frame looping.

Understanding the FFmpeg Loop Filter

The loop filter in FFmpeg allows you to repeat a specific segment of video frames. It requires three primary arguments:

  • loop: The number of times the sequence should be repeated. Set this to -1 for infinite loops, or a positive integer (e.g., 5) for a specific number of repetitions.
  • size: The total number of frames in the sequence that you want to loop.
  • start: The 0-based index of the first frame where the loop sequence begins.

The Basic Command Syntax

The basic syntax for applying the loop filter is as follows:

ffmpeg -i input.mp4 -vf "loop=loop=NUMBER_OF_LOOPS:size=NUMBER_OF_FRAMES:start=START_FRAME" output.mp4

Practical Example

If you have a 30 fps video and want to loop a 3-second sequence (90 frames) starting at the 5-second mark (frame 150) a total of 5 times, your command will look like this:

ffmpeg -i input.mp4 -vf "loop=loop=5:size=90:start=150" output.mp4

How to Calculate Frames from Time

To use the loop filter accurately, you must convert your desired timecodes into frame numbers using the video's frame rate (FPS).

  1. Find the video FPS: You can find the frame rate of your input video using ffprobe:

    ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of default=noprint_wrappers=1:nokey=1 input.mp4
  2. Calculate the start frame (start): Multiply the start time in seconds by the FPS. \[\text{Start Frame} = \text{Start Time (seconds)} \times \text{FPS}\]

  3. Calculate the sequence size (size): Multiply the duration of the loop in seconds by the FPS. \[\text{Size (Frames)} = \text{Loop Duration (seconds)} \times \text{FPS}\]

For example, if your video is 24 fps, and you want to loop a segment from 00:00:02 to 00:00:04 (a 2-second duration):

  • start = 2 seconds * 24 fps = 48
  • size = 2 seconds * 24 fps = 48

Command:

ffmpeg -i input.mp4 -vf "loop=loop=3:size=48:start=48" output.mp4

Important Considerations

  • Audio Sync: The loop filter only loops the video stream. If your input video has audio, the audio will continue to play linearly and will fall out of sync with the looped video. To disable audio, add the -an flag to your command, or use a separate audio filter chain to loop the audio.
  • Output Duration: By default, FFmpeg will extend the output video duration to accommodate the newly added looped frames.