前言
使用ffmpeg推流很简单,使用ffmpeg命令推流更简单。本篇以本文标题《ffmpeg推流flv到rtmp》为中心。只推流输入flv格式的媒体文件,只推流到rtmp。
原因很简单,简化一切复杂的流程,稍后再说原因。我们通过多篇慢慢的提升代码复杂度,例如:把mp4推流到rtmp需要使用ffmpeg代码做什么和flv推流到rtmp有什么不同,等问题都会讲解。
编写代码
为了方便我引入的头文件有点多:
技巧:
你可以专门提出来一个.h头文件,引入一些公共的头文件,这样再写一个新.cpp文件的时候就不用每次都引入这么多了。
这样其他地方只很简单的引入即可:
整体函数模型:
创建输入和输出的ffmpeg上下文:
打开输入文件,初始化输入上下文
查找分析输入媒体流
创建输出流上下文
创建输出流
因为输入的是flv,所以直接把输入的参数都拷贝过来了。
需要注意的是:如果是mp4什么的, 就需要其他的解码,编码处理了。
dump信息:
这里也需要注意,为什么两个av_dump_format之间需要增加休眠的sleep代码?这个可以自己做个实验把sleep去掉试试。欢迎留言实验结果。
打开输出流
写入头数据
创建AVPacket,读输入数据时用到,因为ffmpeg会把读取到的数据,封装成一个一个的AVPacket
获取当前时间
循环读取数据
释放资源
main函数:
测试
运行程序:
ffplay播放:
我们输入一个mp4测试下:
因为我们只实现了最最最简单的把flv推流到了rtmp,没有加入编码和解码的功能部分,所以不行。
下一篇,我们就来研究下,如何把mp4和flv等格式兼容起来。
总结
因为rtmp只能接收flv格式的视频容器,所以需要把数据封装成flv之后,rtmp才可以识别到。