Skip to content

Instantly share code, notes, and snippets.

@tejainece
Created May 7, 2014 09:43
Show Gist options
  • Save tejainece/6f7f5d5fec677eeedd15 to your computer and use it in GitHub Desktop.
Save tejainece/6f7f5d5fec677eeedd15 to your computer and use it in GitHub Desktop.
Get duration, width and height of a video using ffmpeg
#include <stdio.h>
#include <assert.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
void openVideoFile(char *filename) {
AVFormatContext* pFormatCtx;
AVCodecContext* pCodecCtx;
int videoStream = -1;
int i = 0;
// open video file
int ret = avformat_open_input(&pFormatCtx, filename, NULL, NULL);
if (ret != 0) {
printf("Unable to open video file: %s\n", filename);
return;
}
// Retrieve stream information
ret = avformat_find_stream_info(pFormatCtx, NULL);
assert(ret >= 0);
printf("\n");
printf("Duration: %lus\n", pFormatCtx->duration/1000000);
}
int main(int argc, char **argv) {
if(argc != 2) {
printf("Usage: %s <path-to-video>\n", argv[0]);
exit(1);
}
// register all formats and codecs
av_register_all();
openVideoFile(argv[1]);
}
#include <stdio.h>
#include <assert.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
void openVideoFile(char *filename) {
AVFormatContext* pFormatCtx;
AVCodecContext* pCodecCtx;
int videoStream = -1;
int i = 0;
// open video file
int ret = avformat_open_input(&pFormatCtx, filename, NULL, NULL);
if (ret != 0) {
printf("Unable to open video file: %s\n", filename);
return;
}
// Retrieve stream information
ret = avformat_find_stream_info(pFormatCtx, NULL);
assert(ret >= 0);
for(i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO && videoStream < 0) {
videoStream = i;
}
} // end for i
assert(videoStream != -1);
// Get a pointer to the codec context for the video stream
pCodecCtx=pFormatCtx->streams[videoStream]->codec;
assert(pCodecCtx != NULL);
printf("\n");
printf("Width: %d\n", pCodecCtx->width);
printf("Height: %d\n", pCodecCtx->height);
}
int main(int argc, char **argv) {
if(argc != 2) {
printf("Usage: %s <path-to-video>\n", argv[0]);
exit(1);
}
// register all formats and codecs
av_register_all();
openVideoFile(argv[1]);
}
CC = gcc
LD_FLAGS = -lavformat -lavcodec
all: get_width_and_height
get_width_and_height: get_width_and_height.c
$(CC) -o $@ $< $(LD_FLAGS)
clean:
rm get_width_and_height
@dmitryshm
Copy link

it doesn't work for rtp video streams

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment