ffmpeg dump specific length of video after seeking PICT_TYPE_I keyframe

559 views Asked by At

I have a flv video and want to dump let's say 3s length of the video after first keyframe PICT_TYPE_I meet after 00:39. I ready the document of ffmpeg seeking and quote here

ffmpeg -ss 00:23:00 -i Mononoke.Hime.mkv -frames:v 1 out1.jpg

This example will produce one image frame (out1.jpg) at the twenty-third minute from the beginning of the movie. The input will be parsed using keyframes, which is very fast. As of FFmpeg 2.1, when transcoding with ffmpeg (i.e. not just stream copying), -ss is now also "frame-accurate" even when used as an input option. Previous behavior (seeking only to the nearest preceding keyframe, even if not precisely accurate) can be restored with the -noaccurate_seek option.

So I think if I use this command (put -ss before -i)

ffmpeg -noaccurate_seek -ss 00:39 -i input.flv  -r 10 -s 720x400 -t 3.12 dump.flv

And this should dump a video that last 3.12s and begin with the first keyframe after 00:39 right? after all, this is what I need.

But the result is dump.flv not start with a keyframe, ie a PICT_TYPE_I frame.

I know I could find all keyframe start time with ffprobe and re-calculate the -ss seeking time to achieve this. But is there a better way?

1

There are 1 answers

0
Gyan On

If audio is of no concern, you can use

ffmpeg -ss 39.00 -i in.flv -vf select='if(eq(pict_type,I),st(1,t),gt(t,ld(1)))',setpts=N/FRAME_RATE/TB -an -t 3.12 out.flv

Here, the select filter discards all frames before the first keyframe which is after the seek point. The t value controls the total duration selected.

Do note that video duration is quantized i.e. a 25 fps video can have duration in steps of 0.04s.