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 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章