void GetKeyFrame(const char* first_path)
{
int nFrameCount = 0;
m_vecKeyFrame.clear();
AVFormatContext *pFormatCtx = avformat_alloc_context();;
if(avformat_open_input(&pFormatCtx, first_path,
NULL,NULL)!=0)
{
return;
}
if(avformat_find_stream_info(pFormatCtx,NULL)<0)
return;
int videoStream=-1;
for(int i=0; inb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
{
videoStream=i;
break;
}
if(videoStream==-1)
printf("error!\n");// Didn't find a video stream
// 得到视频流编码上下文的指针
AVCodecContext
*pCodecCtx=pFormatCtx->streams[videoStream]->codec;
AVCodec *pCodec;
// 寻找视频流的解码器
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL)
printf("error!\n");// 找不到解码器
// 打开解码器
avcodec_open2
if(avcodec_open2(pCodecCtx, pCodec,NULL)<0)
printf("error!\n"); // 打不开解码器
AVPacket packet={0};
AVFrame *frame = av_frame_alloc();
int got_picture=0;
while(av_read_frame(pFormatCtx,&packet) >= 0)
{
if (packet.stream_index == videoStream)
{
nFrameCount ++;
avcodec_decode_video2(pCodecCtx,frame,&got_picture,&packet);
if (got_picture)
{
if (frame->key_frame == 1)
{
m_vecKeyFrame.push_back(nFrameCount);
}
}
}
av_free_packet(&packet);
}
av_free(frame);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
}