ffmpeg4 代码输出mp4文件帧数

代码无误。
需要注意的是编译环境,本人用的是ffmpeg4版本,源码编译安装。
最后会输出一个i的值,就是这个视频的帧数了。

#include <iostream>
#include <cmath>
extern "C"{
#include <libavdevice/avdevice.h>
#include <libavcodec/avcodec.h>
#include <libavfilter/avfilter.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavutil/time.h>
#include <libavutil/audio_fifo.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
}
/*
    解码视频流,获得视频的帧数
*/



using namespace std;

int main()
{
    char filePath[]       = "/home/workspace/myffmpeg/jay.mp4";//文件地址
    int  videoStreamIndex = -1;//视频流所在流序列中的索引
    int ret=0;//默认返回值

    //需要的变量名并初始化
    AVFormatContext *fmtCtx=NULL;
    AVPacket *pkt =NULL;
    AVCodecContext *codecCtx=NULL;
    AVCodecParameters *avCodecPara=NULL;
    AVCodec *codec=NULL;

    
    //创建AVFormatcontext结构体
    fmtCtx=avformat_alloc_context();
    if(avformat_open_input(&fmtCtx,filePath,NULL,NULL)<0)
    {
        cout<<"文件流创建失败"<<endl;
        
    }
    //获得视频流
    if (avformat_find_stream_info(fmtCtx,NULL)<0)
    {
        cout<<"没有获得视频流"<<endl;
       
    }
    
    for(int i=0;i<fmtCtx->nb_streams;i++){
        if (fmtCtx->streams[ i ]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoStreamIndex = i;
            break;//找到视频流就退出
        }
    }

    //如果videoStream为-1 说明没有找到视频流
    if (videoStreamIndex == -1) {
        printf("找不到视频流");
    
    }

    //打印输入和输出信息:长度 比特率 流格式等
    av_dump_format(fmtCtx, 0, filePath, 0);


    //查找解码器       通过解码器的id找解码器   avCodecPara是解码器上下文
    avCodecPara = fmtCtx->streams[videoStreamIndex]->codecpar;
    codec = avcodec_find_decoder(avCodecPara->codec_id);
    if(codec==NULL){
        cout<<"没有找到对应的解码器"<<endl;
    
    }

    //创建解码器内容
    codecCtx = avcodec_alloc_context3(codec);
    avcodec_parameters_to_context(codecCtx,avCodecPara);
    if(codecCtx == NULL){
        cout<<"创建解码器空间失败"<<endl;
        
    }

    //打开解码器
    if((ret=avcodec_open2(codecCtx,codec,NULL))<0){
        cout<<"不能打开解码器"<<endl;
    }

    //分配AVPacket
    int i=0;
    pkt=av_packet_alloc();//分配packet
    av_new_packet(pkt,codecCtx->width*codecCtx->height); //调整packet的数据

    //读取视频信息
    while(av_read_frame(fmtCtx,pkt)>=0){
        if(pkt->stream_index==videoStreamIndex){
            i++;
        }
        av_packet_unref(pkt);//重置pkt内容
    }
    cout<<"输出帧数i:"<<i<<endl;

    av_packet_free(&pkt);
    avcodec_close(codecCtx);
    avcodec_parameters_free(&avCodecPara);
    // avformat_close_input(&fmtCtx);
    // avformat_free_context(fmtCtx);

    // av_free(codec);

    return ret;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值