C++ FFMPEG推RTMP流demo

#include<stdio.h>
#include<string>
#include<vector>
extern "C"
{
    
    
#include "libavformat/avformat.h"
#include "libavutil/mathematics.h"
#include "libavutil/time.h"
}
using namespace std;
/*
libavformat是FFmpeg中处理音频、视频以及字幕封装和解封装的通用框架,内置了很多处理多媒体文件的Muxer和Demuxer,它支持如AVInputFormat的输入容器和AVOuputFormat的输出容器,同时也支持基于网络的一些流媒体协议,如HTTP、RTSP、RTMP等
libavutil是一个实用库,用于辅助多媒体编程。此库包含安全的可移植字符串函数、随机数生成器、数据结构、附加数学函数、加密和多媒体相关功能(如像素和样本格式的枚举)
*/

int main(std::string task_path,std::string objective_path,std::vector<std::string> warmup_path
                 ,int start_timeMS, int persistent_timeMS)
{
    
    
	AVOutputFormat *ofmt = NULL;
	//AVOutputFormat 结构体主要用于muxer,是音视频文件的一个封装器
	AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
	//AVFormatContext是包含码流参数较多的结构体,包含一些视频文件名,视频时长,视频码率等封装格式信息。
	AVPacket pkt;
	//AVPacket是存储压缩编码数据相关信息的结构体
	const char *in_filename, *out_filename;
	int ret, i;
	int videoindex = -1;
	int frame_index = 0;
	int64_t start_time = 0;
	in_filename = "/home/centos/1.flv";
	out_filename = "rtmp://10.237.92.44/live/livestream";
	//out_filename = "http://10.237.92.44:8080/live/livestream.m3u8";
	//av_register_all();
	//注册了所有的文件格式和编解码器的库,FFmpeg4以后不需要显示的去调用
	avformat_network_init();
	//加载socket库以及网络加密协议相关的库,为后续使用网络相关功能提供支持
	if((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0 )
	{
    
    
		printf("Could not open input file.");
		goto end;
	}
	//avformat_open_input()。该函数用于打开多媒体数据并且获得一些相关的信息。
	if((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0){
    
    
		printf("Failed to retrieve input stram information");
		goto end;
	}
	//avformat_find_stream_info()。该函数可以读取一部分视音频数据并且获得一些相关的信息。
	//函数正常执行后返回值大于等于0。
	for(i = 0 ; i < ifmt_ctx -> nb_streams ; i++)
		if(ifmt_ctx -> streams[i] -> codecpar -> codec_type == AVMEDIA_TYPE_VIDEO)
		{
    
    
			videoindex = i;
			break;
		}
	//nb_streams 代表音视频流的个数,是avformatcontext的内容之一
	//stream是具体视音频流
	av_dump_format(ifmt_ctx, videoindex, in_filename, 0);
	//打印关于输入或输出格式的详细信息
	avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_filename);
	/*
	ctx:函数调用成功之后创建的AVFormatContext结构体。
	oformat:指定AVFormatContext中的AVOutputFormat,用于确定输出格式。如果指定为NULL,可以设定后两个参数(format_name或者filename)由FFmpeg猜测输出格式。
	PS:使用该参数需要自己手动获取AVOutputFormat,相对于使用后两个参数来说要麻烦一些。
	format_name:指定输出格式的名称。根据格式名称,FFmpeg会推测输出格式。输出格式可以是“flv”,“mkv”等等。
	filename:指定输出文件的名称。根据文件名称,FFmpeg会推测输出格式。文件名称可以是“xx.flv”,“yy.mkv”等等。
	函数执行成功的话,其返回值大于等于0。
 	*/
	if(!ofmt_ctx){
    
    
		printf("Could not create output context\n");
		ret = AVERROR_UNKNOWN;	
		goto end;
	}
	//判断是否创建了输出的结构体
	ofmt = ofmt_ctx -> oformat;
	//oformat 输出容器格式
	for(i = 0 ; i < ifmt_ctx -> nb_streams ; i++)
	{
    
    
		AVStream *in_stream = ifmt_ctx -> streams[i];
		AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);
		//AVStream是存储每一个视频/音频流信息的结构体	
		//avformat_new_stream 在 AVFormatContext 中创建 Stream 通道
		//AVStream->codec = AVCodecContext        AVCodecContext->codec 采用的解码器AVCodec
		if(!out_stream){
    
    
			printf("Faild allocating output stream\n");
			ret = AVERROR_UNKNOWN;
			goto end;
		}
		ret = avcodec_copy_context(out_stream -> codec, in_stream->codec);
		//复制AVCodecContext的设置
		if(ret < 0){
    
    
			printf("Failed to copy context from input to output stream codec context\n");
			goto end;
		}
		out_stream->codec->codec_tag = 0;
		if(ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
			out_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
	}
	av_dump_format(ofmt_ctx, 0, out_filename, 1);
	//转储格式
	if(!(ofmt->flags & AVFMT_NOFILE)){
    
    
		ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
		if(ret < 0){
    
    
			printf("Could not open output URL '%s'", out_filename);
			goto end;
		}
	}
	//avio_open和avio_open2用于打开输入或输出文件
	ret = avformat_write_header(ofmt_ctx, NULL);
	//写文件头
	if(ret < 0){
    
    
		printf("Error occurred when opening output URL\n");
		goto end;
	}
	
	start_time = av_gettime();
	while(1){
    
    
		AVStream *in_stream, *out_stream;
		ret = av_read_frame(ifmt_ctx, &pkt);
		//获取一个AVPacket
		//AVPacket是存储压缩编码数据相关信息的结构体
		if(ret < 0)
			break;
		if(pkt.pts == AV_NOPTS_VALUE) {
    
    
			AVRational time_base1 = in_stream->time_base;
			int64_t calc_duration = (double)AV_TIME_BASE / av_q2d(in_stream->r_frame_rate);
			pkt.pts = (double)(frame_index*calc_duration) / (double)(av_q2d(time_base1)*AV_TIME_BASE);
			pkt.dts = pkt.pts;
			pkt.duration = (double)calc_duration / (double)(av_q2d(time_base1)*AV_TIME_BASE);
			frame_index++;
		}
		//tiem_base1表示时间基,可以通过时间基把PTS,DTS转化成真正的时间。虽然其他结构体也有这个字段,但只有AVStream中的time_base是可用的。PTS*time_base=真正的时间
		//AV_TIME_BASE=1000000us calc_duration为以内部时间基的一帧显示长度
		//frame_index*calc_duration为真正的显示时间 / 时间基
		//pkt.duration数据包的持续时间
		if(pkt.stream_index == videoindex)
		{
    
    
			AVRational time_base=ifmt_ctx->streams[videoindex]->time_base;
			AVRational time_base_q={
    
    1,AV_TIME_BASE};
			int64_t pts_time = av_rescale_q(pkt.dts, time_base, time_base_q);
			int64_t now_time = av_gettime() - start_time;
			if (pts_time > now_time)
				av_usleep(pts_time - now_time);
		}
	
		//stream_index 表示该AVPacket所属的视频流或音频流
		//这里是为了将先解码,但是后面用到的帧,延迟播放
		in_stream = ifmt_ctx->streams[pkt.stream_index];
		out_stream = ofmt_ctx->streams[pkt.stream_index];
		
		pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
		pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));
		pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
		pkt.pos = -1;
		//转换PTS&DTS
		if(pkt.stream_index == videoindex){
    
    
			printf("Send %8d video frams to output URL\n",frame_index);
			frame_index++;
		}
		//ret = av_write_frame(ofmt_ctx,&pkt);
		ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
		if(ret < 0){
    
    
			printf("Error muxing pakcet\n");
			break;
		}
		av_free_packet(&pkt);
	}
	av_write_trailer(ofmt_ctx);
	//写文件尾
	
end:
	avformat_close_input(&ifmt_ctx);
	//avformat_close_input()函数用于关闭一个AVFormatContext,一般情况下是和avformat_open_input()成对使用的。
	if(ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
		avio_close(ofmt_ctx->pb);
	//关闭 AVIOContext 访问的资源并释放它。
	//AVFormatContext->pb:输入数据的缓存
	//AVIOContext是FFMPEG管理输入输出数据的结构体。
	avformat_free_context(ofmt_ctx);
	//释放AVFormatContext结构的内存
	if(ret < 0 && ret != AVERROR_EOF){
    
    
		printf("Error coourred\n");
		return -1;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46324584/article/details/127263694