how to use libavcodec/ffmpeg to find duration of video file

I needed a library to perform basic functions such as length, size, etc of a video file (i'm guessing through the metadata or tags) so I chose ffmpeg. Valid video formats are primarily those prevalent in movie files viz. wmv, wmvhd, avi, mpeg, mpeg-4, etc. If you can, please help me with the method(s) to be used for knowing the duration the video file. I'm on a Linux platform.

Answers


libavcodec is pretty hard to program against, and it's also hard to find documentation, so I feel your pain. This tutorial is a good start. Here is the main API docs.

The main data structure for querying video files is AVFormatContext. In the tutorial, it's the first thing you open, using av_open_input_file -- the docs for that say it's deprecated and you should use avformat_open_input instead.

From there, you can read properties out of the AVFormatContext: duration in some fractions of a second (see the docs), file_size in bytes, bit_rate, etc.

So putting it together should look something like:

AVFormatContext* pFormatCtx = avformat_alloc_context();
avformat_open_input(&pFormatCtx, filename, NULL, NULL);
int64_t duration = pFormatCtx->duration;
// etc
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);

Edit: Added allocation and de-allocation of pFormatCtx in the code example.


I had to add a call to

avformat_find_stream_info(pFormatCtx,NULL)

after avformat_open_input to get mgiuca's answer to work. (can't comment on it)

#include <libavformat/avformat.h>
...
av_register_all();
AVFormatContext* pFormatCtx = avformat_alloc_context();
avformat_open_input(&pFormatCtx, filename, NULL, NULL);
avformat_find_stream_info(pFormatCtx,NULL)
int64_t duration = pFormatCtx->duration;
// etc
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);

The duration is in uSeconds, divide by AV_TIME_BASE to get seconds.


Need Your Help

Many-to-many updates, deletes etc… vb.net 2005

asp.net sql vb.net many-to-many

Forgive what is probably a question that get's asked a lot, but I'm just not getting it. I've searched quite a bit, but I can't quite see clearly from other's posts what I'm missing

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.