100行代码实现ffmpeg下读取文件帧

话不多说,直接上代码。

#include <stdio.h>
#include <iostream>

using namespace std;

 

extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
  
};
 

int main(int argc, char* argv[])
{
	av_register_all();
	char szfilePath[100] = {"F:\\test\\ts.ts"};
	
	

	AVFormatContext *pavFormatContext = avformat_alloc_context();

	int lRet = avformat_open_input(&pavFormatContext, szfilePath, NULL, NULL);
	if (lRet < 0)
	{
		cout << "avformat_open_input fail!!!" << endl;
		return 0;
	}
	
	
	lRet = avformat_find_stream_info(pavFormatContext, NULL);
	if (lRet < 0)
	{
		cout << "avformat_find_stream_info fail!!!" << endl;
		return 0;
	}

	int lVidepId = -1;
	for (int i =0 ;i<= pavFormatContext->nb_streams; i++)
	{
		if (AVMEDIA_TYPE_VIDEO == pavFormatContext->streams[i]->codec->codec_type)
		{
			lVidepId = i;
			if (AV_CODEC_ID_H264 == pavFormatContext->streams[i]->codec->codec_id)
			{
				cout << "code id is AV_CODEC_ID_H264"<< endl;
			}

			break;
		}
	}
	
	AVCodecContext *pavCodecContest =  pavFormatContext->streams[lVidepId]->codec;

	AVCodec *pavCodec = avcodec_find_decoder(pavCodecContest->codec_id);
	if (NULL == pavCodec)
	{
		cout << "avcodec_find_decoder fail!!!" << endl;
		return 0;
	}
	lRet = avcodec_open2(pavCodecContest, pavCodec, NULL);
	if (lRet < 0)
	{
		cout << "avformat_find_stream_info fail!!!" << endl;
		return 0;
	}
	
	AVFrame *pavFrame = av_frame_alloc();

	AVPacket *pavPacket = (AVPacket *)av_malloc(sizeof(AVPacket));

	int count = 1;
	while(1)
	{
		if (av_read_frame(pavFormatContext, pavPacket) < 0)
		{
			break;
		}
		else
		{
			if (lVidepId == pavPacket->stream_index)
			{
				cout<< "Write " << count <<" Frame" << endl;
				FILE *pfile = fopen("F:\\test\\a.es", "ab+");
				fwrite(pavPacket->data,1, pavPacket->size, pfile);
				fclose(pfile);
				count ++;
			}
		}
		
	}

	system("pause");

	return 0;
}

参考资料:https://blog.csdn.net/leixiaohua1020/article/details/8652605 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值