35

How to set the keyframe interval to 5 seconds using FFmpeg?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Samarth Misra
  • 361
  • 1
  • 3
  • 6

2 Answers2

38

You'll need to reencode. Set x264's keyint parameter to 5*fps and disable scenecut. If your fps is 24 for example :

ffmpeg -i <input> -vcodec libx264 -x264-params keyint=120:scenecut=0 -acodec copy out.mp4

This is obviously not optimal for quality but it'll match your demand.

Edited to change no-scenecut to scenecut=0, as per sigh-boy suggestion.

Ely
  • 1,189
  • 9
  • 12
  • 3
    It hurts either the quality or the bitrate. Smart encorders will place keyframes when there is a scenecut so that future frames can have a clean reference. If you force the interval, keyframes won't be optimal at all for future frames and this will hurt the stream overall. – Ely Aug 25 '15 at 16:00
  • I'm curious since the link in sigh-boy's answer says: _Setting scenecut to 0 is equivalent to setting --no-scenecut._ – arielnmz May 31 '21 at 00:59
26

Sigh.

The misinformation regarding the no-scenecut option has been going on for longer than I can remember. Never enter a value for no-scenecut.

A link to documentation can be found here.

For FFmpeg you need to use the following two switches:

-g 120 will define a GOP of 120 frames to create a five second GOP for 23.976fps content. This works in conjunction with the no-scenecut option.

-x264opts no-scenecut will force keyframes to be created per the GOP value that FFmpeg uses. The default for libx264 is to create a keyframe when it detects a scene change. If you inspect an output file using MediInfo without that option will see scenecut=40. When done properly that will be scenecut=0. If this option is not used then keyframes will be misaligned for ABR content and segment sizes will be unpredictable.

Do not take my word for it, please run the following under a bash shell where $inputfile is the name of the file you want to analyze. If you use the two switches shown above then you will see a very even cadence of keyframes dump to the command prompt.

ffprobe -select_streams v -show_frames -show_entries \
  frame=pict_type -of csv $inputfile | grep -n I | cut -d ':' -f 1

You can also reference an article that I wrote regarding how to create proper ABR frame aligned content here.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
Navilor
  • 377
  • 3
  • 2