In ffmpeg, how to search to a keyframe BEFORE a specified time?


For a video in the mp4 or flv container formats, I need to:

  1. Get its duration.

  2. Get a keyframe at 25% of its duration. If frame at 25% isn't a keyframe, seek to the first keyframe before that frame.

  3. Seek to audio at 10ms before that keyframe.

According to the following comment on StackOverflow, av_seek_frame seems to only seek to a keyframe after a specified time.


Given that it appears I can only seek after a specified time, how is it possible to get the required keyframe and to seek to the correct part in a mp4 or flv container as specified above?

My Ideas

  • My best bet is probably parsing the header (and index, where applicable) manually, and then use the av_seek_frame with the AVSEEK_FLAG_BYTE flag.

  • Or I can just walk the whole file, and just check if AVFrame->key_frame is true or not.

It would be awesome if the trim filter could support different seek methods, but I guess I have to get correct timestamps by myself, is that correct?