How can I insert the missing keyframe in the video using FFmpeg?

I converted a video using FFmpeg and now want to add the missing keyframe at the beginning of the newly generated video. How can I do that? Are there any flags to use?

Hi Lvan!

In order to insert the missing keyframe in the video, FFmpeg provides various flags/options to perform different tasks, and to add a keyframe at the beginning of a video using FFmpeg, you can use the -force_key_frames option and specify the position of the keyframe you want to add.

For example:

ffmpeg -i input.mp4 -c copy -force_key_frames "expr:gte(t,n_forced*2)" output.mp4

  • -i input.mp4 is the input video file.
  • -c copy is used to copy the audio and video streams without re-encoding and making sure to fast process.
  • -force_key_frames "expr:gte(t,n_forced*2)" is the main part of this command. At regular intervals, in this case, every two seconds, it forces a keyframe. The interval can be changed to suit your needs.
  • The expression expr:gte(t,n_forced*2) It determines whether the current time (t) is greater than or equal to the number of forced keyframes times the interval, in this case, two seconds.
  • output.mp4 is the output video file.

For example, to add a keyframe at the very beginning of the video, you can use a command like this:
ffmpeg -i input.mp4 -force_key_frames “expr:gte(t,0)” output.mp4
This will tell FFmpeg to generate a keyframe at the first frame of the video (which is at time t=0). You can also use this option to specify the interval at which keyframes should be generated, by using a value like expr:gte(t,n), where n is the number of seconds between keyframes.

Will this increase the size of the final video?

Yes, adding keyframes can increase the size of the output video file, as keyframes contain more information than normal frames and are therefore larger.

You can use the -g option to specify the maximum number of frames between keyframes, which can help to balance the trade-off between file size and seeking performance.
For more information about the -force_key_frames option and other options related to keyframes, you can refer to the FFmpeg documentation.