用FFmpeg将rtsp视频流保存成文件

ffmpeg:FFmpeg的名称来自MPEG视频编码标准,前面的“FF”代表“Fast Forward,是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

库的组成:

libavformat:用于各种音视频封装格式的生成和解析,包括获取解码所需信息以生成解码上下文结构和读取音视频帧等功能;

libavcodec:用于各种类型声音/图像编解码;

libavutil:包含一些公共的工具函数;

libswscale:用于视频场景比例缩放、色彩映射转换;

libpostproc:用于后期效果处理;

ffmpeg:该项目提供的一个工具,可用于格式转换、解码或电视卡即时编码等;

ffsever:一个 HTTP 多媒体即时广播串流服务器;

ffplay:是一个简单的播放器,使用ffmpeg 库解析和解码,通过SDL显示;

用FFmpeg将rtsp视频流保存成文件的demo:

#include <stdio.h>
#include <stdlib.h>

#ifdef __cplusplus 
extern "C"
{
#endif
	/*Include ffmpeg header file*/
#include <libavformat/avformat.h> 
#include <libavcodec/avcodec.h> 
#include <libswscale/swscale.h> 

#include <libavutil/imgutils.h>  
#include <libavutil/opt.h>     
#include <libavutil/mathematics.h>   
#include <libavutil/samplefmt.h>
#ifdef __cplusplus
}
#endif

void main()
{
	AVFormatContext *pFormatCtx;
	char filepath[] = "rtsp://192.168.0.103:554/11";
	AVPacket *packet;

	//初始化
	av_register_all();
	avformat_network_init();
	pFormatCtx = avformat_alloc_context();
	AVDictionary* options = NULL;
	av_dict_set(&options, "buffer_size", "1024000", 0); //设置缓存大小,1080p可将值跳到最大
	av_dict_set(&options, "rtsp_transport", "tcp", 0); //以udp的方式打开,
	av_dict_set(&options, "stimeout", "5000000", 0); //设置超时断开链接时间,单位us
	av_dict_set(&options, "max_delay", "500000", 0); //设置最大时延
	packet = (AVPacket *)av_malloc(sizeof(AVPacket));

	//打开网络流或文件流
	if (avformat_open_input(&pFormatCtx, filepath, NULL, NULL) != 0)
	{
		printf("Couldn't open input stream.\n");
		return;
	}
	
	//查找码流信息
	if (avformat_find_stream_info(pFormatCtx, NULL)<0)
	{
		printf("Couldn't find stream information.\n");
		return;
	}
	
	//查找码流中是否有视频流
	int videoindex = -1;
	unsigned i = 0;
	for (i = 0; i<pFormatCtx->nb_streams; i++)
		if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			videoindex = i;
			break;
		}
	if (videoindex == -1)
	{
		printf("Didn't find a video stream.\n");
		return;
	}

	//保存一段的时间视频,写到文件中
	FILE *fpSave;
	fpSave = fopen("geth264_test.h264", "wb");
	for (i = 0; i < 200; i++)   //这边可以调整i的大小来改变文件中的视频时间
	{
		if (av_read_frame(pFormatCtx, packet) >= 0)
		{
			if (packet->stream_index == videoindex)
			{
				fwrite(packet->data, 1, packet->size, fpSave);  
			}
			av_packet_unref(packet);
		}
	}

	fclose(fpSave);
	av_free(pFormatCtx);
	av_free(packet);
}

编译:arm-hisiv400-linux-gcc VedioToH264_demo.c -o ffmpegtest  -I ./ffmpeg/include/ -L ./ffmpeg/lib/ -I h264/include/ -L h264/lib/  -pthread -lm -lavformat -lavdevice -lavfilter -lavcodec -lavutil -lswresample -lswscale -lrt -lx264 -ldl

结果:

猜你喜欢

转载自blog.csdn.net/weixin_42432281/article/details/88348124
今日推荐