Question

I'm trying to understand how to seek in videos encoded with p-frames (e.g. H.264)-- right now I only know how to seek in videos encoded with codecs in which every frame is a keyframe (e.g. MJPEG).

Given a timestamp, ultimately it should play the frame for that timestamp. But for now, I'm just trying to play the keyframe near the timestamp. So, first--

ret = av_seek_frame(pFormatCtx, videoStream, avTime, 0); 
avcodec_flush_buffers(pCodecCtx);

Then some intervening code, including av_read_frame. Then--

ret = avcodec_decode_video2(pCodecCtx, captureFrame, &gotPicture, &packet); 

Observations:

  • For some videos, this works. For others, avcodec_decode_video2 returns an error (negative number). Example of a working video: here. Example of a non-working video: here.

  • For MJPEG videos, this works.

  • If I take out the av_seek_frame, so that it just plays through the frames in sequence, it works.

Was it helpful?

Solution

Replace this--

ret = av_seek_frame(pFormatCtx, videoStream, avTime, isPlayingBackward ? AVSEEK_FLAG_BACKWARD : 0); 
avcodec_flush_buffers(pCodecCtx);

with this--

ret = avformat_seek_file(pFormatCtx, videoStream, 0, avTime, avTime, 0); 

(Caveat: The docs for avformat_seek_file say: "This is part of the new seek API which is still under construction. Thus do not use this yet. It may change at any time, do not expect ABI compatibility yet!")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top