ffmpeg提取h264视频帧率的源码
时间: 2023-09-07 22:14:22 浏览: 139
ffmpeg解码h264
以下是使用FFmpeg提取H.264视频帧率的样例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/mathematics.h>
int main(int argc, char* argv[])
{
AVFormatContext *pFormatCtx = NULL;
int i, videoStream;
AVCodecContext *pCodecCtxOrig = NULL, *pCodecCtx = NULL;
AVCodec *pCodec = NULL;
AVFrame *pFrame = NULL;
AVPacket packet;
int frameFinished;
float fps = 0;
if(argc < 2)
{
printf("Usage: %s <video_file>\n", argv[0]);
return -1;
}
av_register_all();
if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL) != 0)
{
printf("Error: Couldn't open input file!\n");
return -1;
}
if(avformat_find_stream_info(pFormatCtx, NULL) < 0)
{
printf("Error: Couldn't find stream information!\n");
return -1;
}
av_dump_format(pFormatCtx, 0, argv[1], 0);
videoStream = -1;
for(i = 0; i < pFormatCtx->nb_streams; i++)
{
if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoStream = i;
break;
}
}
if(videoStream == -1)
{
printf("Error: Couldn't find a video stream!\n");
return -1;
}
pCodecCtxOrig = pFormatCtx->streams[videoStream]->codec;
pCodec = avcodec_find_decoder(pCodecCtxOrig->codec_id);
if(pCodec == NULL)
{
printf("Error: Unsupported codec!\n");
return -1;
}
pCodecCtx = avcodec_alloc_context3(pCodec);
if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0)
{
printf("Error: Couldn't copy codec context!\n");
return -1;
}
if(avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
{
printf("Error: Couldn't open codec!\n");
return -1;
}
pFrame = av_frame_alloc();
while(av_read_frame(pFormatCtx, &packet) >= 0)
{
if(packet.stream_index == videoStream)
{
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
if(frameFinished)
{
fps = av_q2d(pFormatCtx->streams[videoStream]->r_frame_rate);
break;
}
}
av_free_packet(&packet);
}
av_free(pFrame);
avcodec_close(pCodecCtx);
avcodec_close(pCodecCtxOrig);
avformat_close_input(&pFormatCtx);
printf("FPS: %.2f\n", fps);
return 0;
}
```
运行样例代码时,需要将 H.264 视频文件名作为命令行参数传递给程序。程序将会输出视频的帧率。
阅读全文