Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ffmpeg, C++ - get fps in program

Tags:

c++

ffmpeg

I have a video which has 23.98 fps, this can be seen from Quicktime and ffmpeg in the command line. OpenCV, wrongly, thinks it has 23 fps. I am interested in finding a programmatic way to find out a video fps' from ffmpeg.

like image 829
Rupert Cobbe-Warburton Avatar asked Dec 17 '13 15:12

Rupert Cobbe-Warburton


2 Answers

To get video Frames per Second (fps) value using FFMPEG-C++

/* 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;
like image 83
Abdullah Farweez Avatar answered Nov 20 '22 14:11

Abdullah Farweez


A quick look into the OpenCV sources show the following:

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;
}

so looks quite right. Maybe run a debug session through this part to verify the values at this point? The avg_frame_rate of AVStream is an AVRational so it should be able to hold the precise value. Maybe if your code uses the second if block due to an older ffmpeg version the time_base is not set right?

EDIT

If you debug take a look if the r_frame_rate and avg_frame_rate differ, since at least according to this they tend to differ based on the codec used. Since you have not mentioned the video format it's hard to guess, but seems that at least for H264 you should use avg_ frame_rate straightforward and a value obtained from r_frame_rate could mess things up.

like image 3
Rudolfs Bundulis Avatar answered Nov 20 '22 15:11

Rudolfs Bundulis