Search code examples
audiovideoffmpeg

Calculate PTS and DTS for encoding new video and audio in ffmpeg


I encode a new H.264 video muxed with audio in MP4 file.

How to correctly calculate PTS and DTS for AVPacket and AVFrame for video and audio?

I generate new video frames and new audio from my source. There are no original PTS/DTS information. I know frame rate which I need to use (time_base).


Solution

  • Assuming your frame rate is constant. And after setting stream time bases correctly. Start both pts's from zero (0). Audio pts will increase by 'sample per frame' for each frame. This is typically audio_sample_rate / frame_rate (i.e. 48000/60 = 800).

    For the video, things are different and somewhat simpler. Video pts will increase same amount of 'Video frame duration' per frame. Use this cheat sheet to calculate the duration:

    FPS     Frame duration
    23.98   2002
    24.00   2000
    25.00   2000
    29.97   2002
    30.00   2000
    50.00   1000
    59.94   1001
    60.00   1000
    

    Yes these somewhat hacky but will work.