Search code examples
c++cvideoffmpegframe-rate

How to specify a fractional framerate with ffmpeg C/C++ when stitching together images?


I want to specify fractional frame rate's like 23.797 or 59.94 when creating my encoder. Here is how I do it currently:

AVStream* st;
...
st->time_base = (AVRational){1, STREAM_FRAME_RATE };

But looking at ffmpeg's source code at rational.h we can see that AVRational struct takes int's instead of float's. So my 23.797 turns into 23 thus encoding wrong. How can I specify fps with floating numbers?


Solution

  • As per the comment, you can make use of av_d2q from the libavutil library. By way of a basic example...

    #include <iostream>
    #include <limits>
    
    extern "C" {
    #include <libavutil/avutil.h>
    }
    
    int main ()
    {
      auto fps = 23.797;
      auto r = av_d2q(1 / fps, std::numeric_limits<int>::max());
      std::cout << "time base is " << r.num << "/" << r.den << " seconds\n";
    }
    

    The above gives me the following output...

    time base is 1000/23797 seconds