最近在研究视频的播放的快进快退功能,先把相关的调研结果整理一下,做个记录。
裸的H264码流,如果实现快进快退必须基于 I 帧才能实现:在播放前对整个码流进行统计,总共有多少帧,所有的 I 帧在什么位置。在播放的时候,再根据用户快进或快退的位置判断相邻最近的 I 帧在什么位置,然后从那一个 I 帧开始解码播放。
无论哪个播放器要想实现快进快退都只有按照上述方法来做。暴风影音也不例外。如果一个视频序列中只有第一帧是 I 帧,那么是根本无法实现快进快退的,暴风影音也不可能做到,不信你可以用暴风影音试试我附件里的这个裸流.
ffmpeg 提供了一个speed up/down的功能filter:
You can change the speed of a video stream using the setpts video filter. Note that in the following examples, the audio stream is not changed, so it should ideally be disabled with -an.
To double the speed of the video, you can use:
ffmpeg -i input.mkv -filter:v "setpts=0.5*PTS" output.mkv
The filter works by changing the presentation timestamp (PTS) of each video frame. For example, if there are two succesive frames shown at timestamps 1 and 2, and you want to speed up the video, those timestamps need to become 0.5 and 1, respectively. Thus, we have to multiply them by 0.5.
Note that this method will drop frames to achieve the desired speed. You can avoid dropped frames by specifying a higher output frame rate than the input. For example, to go from an input of 4 FPS to one that is sped up to 4x that (16 FPS):
ffmpeg -i input.mkv -r 16 -filter:v "setpts=0.25*PTS" output.mkv
To slow down your video, you have to use a multiplier greater than 1:
ffmpeg -i input.mkv -filter:v "setpts=2.0*PTS" output.mkv
You can speed up or slow down audio with the atempo audio filter. To double the speed of audio:
ffmpeg -i input.mkv -filter:a "atempo=2.0" -vn output.mkv
The atempo filter is limited to using values between 0.5 and 2.0 (so it can slow it down to no less than half the original speed, and speed up to no more than double the input). If you need to, you can get around this limitation by stringing multiple atempo filters together. The following with quadruple the audio speed:
ffmpeg -i input.mkv -filter:a "atempo=2.0,atempo=2.0" -vn output.mkv
Using a complex filtergraph, you can speed up video and audio at the same time:
ffmpeg -i input.mkv -filter_complex "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]" -map "[v]" -map "[a]" output.mkv