[Libav-user] [newbie] how to extract current timestamp of h264 avi file

Alexandre Millette amillett at matrox.com
Tue Jul 31 21:08:01 CEST 2012


Hello,

aa aaaa wrote:
> So I would like someone to help me out with the steps I need to do in 
> order to get the timestamp of a frame in a h264 avi file.


I will assume you already have the libraries you need and they work in 
your environment.

First include the one you need, like this:

extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
};

Then prepare some object you will need:

AVFormatContext* mpFormatCtx
AVCodecContext* mpCodecCtx;
AVCodec* mpCodec;

Here's a function that will open the file and get the context needed later:

int ReadFile(const char* apFileName)
{
    av_register_all();
    mpFormatCtx = 0;
    // Open video file
    if( avformat_open_input( &mpFormatCtx, apFileName, NULL, NULL ) != 0)
        // Error
    // Retrieve stream information
    if( avformat_find_stream_info( mpFormatCtx, NULL ) < 0 )
        // Error
    // Find the first video stream
    mVideoStream = -1;
    for( unsigned int i = 0; i < mpFormatCtx->nb_streams; i++ )
    {
        if( mpFormatCtx->streams[i]->codec->codec_type == 
AVMEDIA_TYPE_VIDEO )
        {
            mVideoStream = i;
            break;
        }
    }
    if( mVideoStream == -1 ) // no video stream found
        // Error
    // Get a pointer to the codec context for the video stream
    mpCodecCtx = mpFormatCtx->streams[mVideoStream]->codec;
    // Find the decoder for the video stream
    mpCodec = avcodec_find_decoder( mpCodecCtx->codec_id );
    if( mpCodec == NULL)
        // Error
    // Open codec
    if( avcodec_open( mpCodecCtx, mpCodec ) < 0 )
        // Error
    return 0;
}

At this point it's possible you have all the info you need, depending on 
what you want.
If what you want is, say, the timestamp of the frame number 86 and you 
know that the video file has all it's frames of the same length (h264 
accepts frames of uneven length IIRC), you can use the information 
stored in the
mpFormatCtx->streams[mVideoStream]
structure that you just filled.
For example you may use r_frame_rate to get the FPS, converting it into 
the MPF (microseconds per frame) like this :
int micro_sec_per_frame = int( 1000000 /
   ((float)mpFormatCtx->streams[mVideoStream]->r_frame_rate.num /
   (float)mpFormatCtx->streams[mVideoStream]->r_frame_rate.den) );
Then your timestamp, in microseconds, is :
int timestamp = (86-1) * micro_sec_per_frame;

But I get the feeling that you want a bit more than just that...
You may have to decode the video frame by frame, but that's quite a bit 
more code and you shoul specify what you want exactly.

Hope this helps,
Alex M


More information about the Libav-user mailing list