When processing video files with FFmpeg, there are multiple ways to repeat the last frame of a video. The following is a common method to achieve this:
Method: Using ffprobe and ffmpeg
Step 1: Determine the total number of frames and frame rate
First, use ffprobe to obtain the total number of frames and frame rate to identify the timestamp of the last frame.
bashffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -of default=nokey=1:noprint_wrappers=1 input.mp4
This command outputs the total number of frames. Next, retrieve the frame rate:
bashffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of default=nokey=1:noprint_wrappers=1 input.mp4
This command outputs a frame rate such as 25/1, indicating 25 frames per second.
Step 2: Calculate the video duration
With the frame rate and total number of frames, compute the video duration. Let N represent the total number of frames and F represent the frame rate.
bashduration=$(echo "scale=2; N / F" | bc)
Step 3: Use ffmpeg to repeat the last frame
Next, use ffmpeg to repeat the last frame of the video. For example, extend the last frame by repeating it for an additional 5 seconds.
bashffmpeg -i input.mp4 -filter_complex "[0:v]trim=duration=$duration,setpts=PTS-STARTPTS[v0];[0:v]trim=start=$duration,setpts=PTS-STARTPTS[v1];[v1]tpad=stop_mode=clone:stop_duration=5[v2];[v0][v2]concat[v]" -map "[v]" -c:v libx264 -preset fast -crf 22 -c:a copy output.mp4
This command performs the following operations:
[0:v]trim=duration=$duration,setpts=PTS-STARTPTS[v0]: Extracts the video up to the frame before the last frame.[0:v]trim=start=$duration,setpts=PTS-STARTPTS[v1]: Extracts the last frame.[v1]tpad=stop_mode=clone:stop_duration=5[v2]: Repeats the last frame for 5 seconds.[v0][v2]concat[v]: Concatenates the initial video segment with the repeated last frame.
Example
Suppose you have a video input.mp4 with a frame rate of 25fps and 1000 total frames. Using the above method, the video duration is calculated as 40 seconds (1000/25), and ffmpeg is used to repeat the last frame for 5 seconds.
This method works for various video lengths and formats, and the repetition duration and other parameters can be adjusted as needed.