cffmpegh.264durationvideo-codecs

How can i know the duration of any h264 file?


I have one file in which only h264 frames are there in form of NAL unit. So now is there any method so i can count the duration of that file?

I dont know how many frames are there in file. I have only file size.

PS: All i want to do is in C language and on Linux platform.


Solution

  • Container file

    First, there is no such a thing as H264 file. There can be a container file (MP4, AVI, MKV) that holds the H264 encoded video. That container format usually also holds the data telling you the contained video duration. So you have to parse that file, check the format documentation to see where the duration is saved, and then extract it.

    Easiest way is to use FFMPEG like Augusto suggested.

    NAL Byte Stream

    If your file is only NAL units saved one after another, like in a NAL byte stream, there IS NO WAY that you can get the video duration! Since H264 encoded picture doesn't hold timing information.

    If that is the case, you still can make an approximation if you know the video FPS... You need to count all frames in the file excluding:

    And then do the math: NUMBER_OF_FRAMES / FPS = DURATION_IN_SECONDS

    RTP stream

    If you are wrong and there is RTP header on top of each NAL unit, you can easily get the video duration by checking the RTP time of each RTP header. What the bytes in RTP Header mean, you can find out here: http://www.networksorcery.com/enp/protocol/rtp.htm. You want to get the TIMESTAMP part (4 bytes integer) from each one. The code should do this:

    int last_timestamp = GetNextTimestamp();
    double duration_in_ms = 0;
    
    while(true)
    {
        int next = GetNextTimestamp();
        duration_in_ms += (next - last_timestamp)/90000.0;
        last_timestamp = next;
    }