[ACCEPTED]-how to use libavcodec/ffmpeg to find duration of video file-ffmpeg
libavcodec is pretty hard to program against, and 14 it's also hard to find documentation, so 13 I feel your pain. This tutorial is a good start. Here is 12 the main API docs.
The main data structure 11 for querying video files is AVFormatContext. In the tutorial, it's 10 the first thing you open, using av_open_input_file
-- the 9 docs for that say it's deprecated and you 8 should use avformat_open_input instead.
From there, you can 7 read properties out of the AVFormatContext: duration
in 6 some fractions of a second (see the docs), file_size
in 5 bytes, bit_rate
, etc.
So putting it together should 4 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);
If you have a file format 3 with no headers, like MPEG, you may need 2 to add this line after avformat_open_input
to read information 1 from the packets (which might be slower):
avformat_find_stream_info(pFormatCtx, NULL);
Edit:
- Added allocation and de-allocation of pFormatCtx in the code example.
- Added
avformat_find_stream_info(pFormatCtx, NULL)
to work with video types that have no headers such as MPEG
I had to add a call to
avformat_find_stream_info(pFormatCtx,NULL)
after avformat_open_input
to get mgiuca's 3 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 2 duration is in uSeconds, divide by AV_TIME_BASE 1 to get seconds.
used this function its working :
extern "C"
JNIEXPORT jint JNICALL
Java_com_ffmpegjni_videoprocessinglibrary_VideoProcessing_getDuration(JNIEnv *env,
jobject instance,
jstring input_) {
av_register_all();
AVFormatContext *pFormatCtx = NULL;
if (avformat_open_input(&pFormatCtx, jStr2str(env, input_), NULL, NULL) < 0) {
throwException(env, "Could not open input file");
return 0;
}
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
throwException(env, "Failed to retrieve input stream information");
return 0;
}
int64_t duration = pFormatCtx->duration;
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
return (jint) (duration / AV_TIME_BASE);
}
When I 2 m using (jint) (duration / AV_TIME_BASE) this 1 video duration is getting wrong.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.