How to control key-frame generation of ffmpeg?

2019-01-09 13:30发布

问题:

I'm making a segmenter that intervene ffmpeg's write_frame function and write output data to separate files. Each segmented file contains segment of about 3 seconds video.

The code does following:

1 - Get transcoded packet  
2 - Check if it contains key frame data, if yes goto 3. 
3 - Check the duration of current segment, if it exceed 3 seconds, goto 4 
4 - Close file, and create new segment, write packet to segment file, goto-1

General speaking, every segment contains at least 3 seconds video data, and it starts with a key frame.

The problem is that the output video's duration are very different, some contain 3 seconds, some contain 5 or 6.

I suspect that the problem due to how ffmpeg generate key frames during transcoding. If the "distance" between two adjacent keyframes are 6s, i got 6 seconds segment.

Here is my questions:

  1. is that true that ffmpeg generate keyframes at irregular intervals (and interval time can be up to few second (eg. 6)?

  2. How can we control the ffmpeg key frame generation? (i guess there should be a ffmpeg command's argument for this, -force_key_frames maybe, but I'm not sure)

回答1:

  1. It is possible for ffmpeg to generate Key frame at irregular interval, based on scene change detection.

  2. key frame interval can be controlled by GOP size. the following options can be used

-g (FFmpeg) Keyframe interval, also known as GOP length. This determines the maximum distance between I-frames. Very high GOP lengths will result in slightly more efficient compression, but will make seeking in the video somewhat more difficult.

-keyint_min (FFmpeg) Minimum GOP length, the minimum distance between I-frames.



标签: ffmpeg libav