ffmpeg,C++-在程序中获取fps

ffmpeg, C++ - get fps in program

本文关键字:获取 fps 程序 C++- ffmpeg      更新时间:2023-10-16

我有一个视频,每秒23.98帧,这可以从命令行中的Quicktime和ffmpeg中看到。OpenCV错误地认为它有23帧/秒。我感兴趣的是找到一种从ffmpeg中找到视频fps的编程方法。

使用FFMPEG-C++获取视频每秒帧数(fps)值

/* find first stream */
for(int i=0; i<pAVFormatContext->nb_streams ;i++ )
{
if( pAVFormatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO ) 
/* if video stream found then get the index */
{
  VideoStreamIndx = i;
  break;
}
}

 /* if video stream not availabe */
 if((VideoStreamIndx) == -1)
 {
   std::cout<<"video streams not found"<<std::endl;
   return -1;
 }
 /* get video fps */
 double videoFPS = av_q2d(ptrAVFormatContext->streams[VideoStreamIndx]->r_frame_rate);
 std::cout<<"fps :"<<videoFPS<<std::endl;

快速查看OpenCV源代码显示以下内容:

double CvCapture_FFMPEG::get_fps()
{
    double fps = r2d(ic->streams[video_stream]->r_frame_rate);
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
    if (fps < eps_zero)
    {
        fps = r2d(ic->streams[video_stream]->avg_frame_rate);
    }
#endif
    if (fps < eps_zero)
    {
        fps = 1.0 / r2d(ic->streams[video_stream]->codec->time_base);
    }
    return fps;
}

所以看起来很对。也许通过这个部分运行调试会话来验证此时的值?AVStream的avg_frame_rateAVRational,因此它应该能够保持精确的值。也许,如果您的代码由于较旧的ffmpeg版本而使用第二个if块,则time_base设置不正确?

编辑

如果您进行调试,请查看r_frame_rateavg_frame_rate是否不同,因为至少根据这一点,它们往往会根据所使用的编解码器而不同。由于您没有提到视频格式,因此很难猜测,但似乎至少对于H264,您应该直接使用avg_ frame_rate,并且从r_frame_rate获得的值可能会把事情搞砸。

2013年03月29日发布的libavformat版本55.1.100中增加了av_guess_frame_rate()

/**
 * Guess the frame rate, based on both the container and codec information.
 *
 * @param ctx the format context which the stream is part of
 * @param stream the stream which the frame is part of
 * @param frame the frame for which the frame rate should be determined, may be NULL
 * @return the guessed (valid) frame rate, 0/1 if no idea
 */
AVRational av_guess_frame_rate(AVFormatContext *ctx, AVStream *stream, AVFrame *frame);