【FFmpeg】调用ffmpeg库进行RTMP推流和拉流

【FFmpeg】调用ffmpeg库实现RTMP推流

  • 1.FFmpeg编译
  • 2.RTMP服务器搭建
  • 3.调用FFmpeg库实现RTMP推流和拉流
    • 3.1 基本框架
    • 3.2 实现代码
    • 3.3 测试
      • 3.3.1 推流
      • 3.3.2 拉流

参考:雷霄骅博士, 调用ffmpeg库进行RTMP推流
====== 示例工程 ======
【FFmpeg】调用FFmpeg库实现264软编
【FFmpeg】调用FFmpeg库实现264软解

1.FFmpeg编译

参考: FFmpeg在Windows下的编译
本文使用FFmpeg-7.0版本

2.RTMP服务器搭建

将本机配置成为服务器,实现本地的推流和拉流操作。RTMP服务器的搭建参考:RTMP服务器的搭建

RTMP是Adobe提出的一种应用层的协议,用于解决多媒体数据传输流的多路复用(Multiplexing)和分包(packetizing)的问题传输,传输媒体的格式为FLV,因此本文推流的格式是flv格式。flv文件可以使用ffmpeg命令行,从yuv文件转换而来。

3.调用FFmpeg库实现RTMP推流和拉流

3.1 基本框架

在实现时,对参考博客中的部分函数进行了修改

  1. 不再使用av_register_all()函数对编解码器进行初始化
  2. 增加av_log_set_level(AV_LOG_TRACE)增加日志输出信息
  3. 使用本机IP127.0.0.1
  4. 修改部分参数的调用,因为部分变量存储的位置发生了变化
  5. 修改部分函数的调用,因为使用的FFmpeg版本不同
  6. 将推流和拉流的部分合并,用一套代码实现

在编码过程当中,主要使用了如下的函数

函数名作用
av_log_set_level配置输出日志级别 (AV_LOG_TRACE最详细)
avformat_network_init初始化网络模块
avformat_open_input打开输入文件,并且将文件信息赋值给AVFormatContext保存
avformat_find_stream_info根据AVFormatContext查找流信息
av_dump_format将AVFormatContext中的媒体文件的信息进行格式化输出
avformat_alloc_output_context2根据format_name(或filename或oformat)创建输出文件的AVFormatContext信息
avformat_new_stream根据AVFormatContext和AVCodecContext创建新的流
avcodec_parameters_copy拷贝AVCodecParameters
avio_open根据url进行AVIOContext的创建与初始化(这个url在推流时就是服务器地址)
avformat_write_header为流分配priv_data并且将流的头信息写入到输出媒体文件
av_read_frame根据AVFormatContext所提供的的信息读取一帧,存入AVPacket
av_interleaved_write_frame以交错的方式将帧送入到媒体文件中
av_packet_unref释放AVPacket
av_write_trailer将流的尾部写入到输出的媒体文件中,并且释放文件中的priv_data
avformat_close_input释放AVFormatContext

从使用的函数来看,主要的操作流程和数据流走向大约为:

  1. 初始化网络模块,为RTMP传输进行准备(avformat_network_init)
  2. 打开输入文件,创建输入文件结构体并且读取输入文件信息(avformat_open_input),此时也会创建输入的流信息结构体
  3. 根据输入文件查找流信息,赋值给流信息结构体(avformat_find_stream_info)
  4. 打印输入文件信息(av_dump_format)
  5. 根据输出文件信息来创建输出文件结构体(avformat_alloc_output_context2)
  6. 创建输出流(avformat_new_stream)
  7. 将输入流的参数拷贝给输出给输出流(avcodec_parameters_copy)
  8. 打印输出文件信息(av_dump_format)
  9. 打开输出口,准备推流(avio_open)
  10. 写入流的头部信息(avformat_write_header)
  11. 读取一帧信息,存储到AVPacket中(av_read_frame)
  12. 处理时间戳;PTS是播放时间戳,告诉播放器播放这一帧的时间;DTS是解码时间戳,告诉播放器解码这一帧的时间;PTS通常是按照递增顺序排列的。这里雷博士认为延时很重要,如果不对前后帧推流的时间进行控制,帧会瞬时推送到服务器端,会出现服务器无法正常接收帧的情况
  13. 将帧推流(av_interleaved_write_frame)
  14. 写入流的尾部信息(av_write_trailer)
  15. 释放结构体信息(av_packet_unref、av_write_trailer和avformat_close_input)

3.2 实现代码

在调试时,发现如果AVPacket这里定义如果是指针的话,会出现av_read_frame第二帧读取失败的情况,这里有待进一步学习。

在代码中,利用bool is_sender来控制是发送还是接收,发送和接收都使用同一套代码,只是在时间戳部分有所区别,即发送端需要计算而接收端不需要使用。不过这里的in_url和out_url还是固定的,实际使用时得重新配置。

#pragma warning(disable : 4996)#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "streamer.h"#ifdef _WIN32
//Windows
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/avutil.h"
#include "libavutil/opt.h"
#include "libavutil/time.h"
#include "libavutil/timestamp.h"
#include "libavutil/mathematics.h"
#include "libavutil/log.h"
};
#else
//Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/avutil.h"
#include "libavutil/opt.h"
#ifdef __cplusplus
};
#endif
#endifint streamer_internal(const char* in_url, const char* out_url, bool is_sender)
{// set log level// av_log_set_level(AV_LOG_TRACE);AVOutputFormat* av_out_fmt = NULL;AVFormatContext* av_in_fmt_ctx = NULL;AVFormatContext* av_out_fmt_ctx = NULL;AVPacket av_pkt;const char* in_filename = in_url;const char* out_filename = out_url;int ret = 0;int i = 0;int video_idx = -1;int frame_idx = 0;int64_t start_time = 0;// bool b_sender = 0;//in_filename = "enc_in_all.flv"; // input flv file//out_filename = "rtmp://127.0.0.1:1935/live/stream"; // output url//in_filename = "rtmp://127.0.0.1:1935/live/stream"; // input flv file//out_filename = "receive.flv"; // output url// av_register_all(); // 新版本ffmpeg不再使用// init networkavformat_network_init();if ((ret = avformat_open_input(&av_in_fmt_ctx, in_filename, 0, 0)) < 0) {fprintf(stderr, "Could not open input file.");goto end;}if ((ret = avformat_find_stream_info(av_in_fmt_ctx, 0)) < 0) {fprintf(stderr, "Failed to retrive input stream information");goto end;}for (i = 0; i < av_in_fmt_ctx->nb_streams; i++) {if (av_in_fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {video_idx = i;break;}}// 将AVFormatContext结构体中媒体文件的信息进行格式化输出av_dump_format(av_in_fmt_ctx, 0, in_filename, 0);// Output// av_out_fmt_ctx是函数执行成功之后的上下文信息结构体// "flv"是输出格式// out_filename是输出文件ret = avformat_alloc_output_context2(&av_out_fmt_ctx, NULL, NULL, out_filename); // RTMP// ret = avformat_alloc_output_context2(&av_out_fmt_ctx, NULL, "flv", out_filename); // RTMP// avformat_alloc_output_context2(&av_out_fmt_ctx, NULL, "mpegts", out_filename); // UDPif (ret < 0) {fprintf(stderr, "Could not create output context, error code:%d\n", ret);//ret = AVERROR_UNKNOWN;goto end;}// av_out_fmt_ctx->oformat;for (i = 0; i < av_in_fmt_ctx->nb_streams; i++) {AVStream* in_stream = av_in_fmt_ctx->streams[i];// 为av_out_fmt_ctx创建一个新的流,第二个参数video_codec没有被使用AVStream* out_stream = avformat_new_stream(av_out_fmt_ctx, av_in_fmt_ctx->video_codec);//AVStream* out_stream = avformat_new_stream(av_out_fmt_ctx, in_stream->codec->codec);if (!out_stream) {fprintf(stderr, "Failed to allocating output stream\n");ret = AVERROR_UNKNOWN;goto end;}// Copy the setting of AVCodecContext// ret = avcodec_copy_context(out_stream->codecpar, in_stream->codecpar);ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);if (ret < 0) {fprintf(stderr, "Failed to copy context from input to output stream codec context\n");goto end;}out_stream->codecpar->codec_tag = 0;if (av_out_fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) {// out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;// out_stream->event_flags |= AV_CODEC_FLAG_GLOBAL_HEADER;}}// Dump format// 将AVFormatContext结构体中媒体文件的信息进行格式化输出av_dump_format(av_out_fmt_ctx, 0, out_filename, 1);// Open output URL if (!(av_out_fmt_ctx->oformat->flags & AVFMT_NOFILE)) {// 打开文件ret = avio_open(&av_out_fmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);if (ret < 0) {fprintf(stderr, "Could not open output URL '%s'", out_filename);goto end;}}// Write file headerret = avformat_write_header(av_out_fmt_ctx, NULL);if (ret < 0) {fprintf(stderr, "Error occured when opening output URL\n");goto end;}if (is_sender) {start_time = av_gettime();}while(1) {AVStream* in_stream;AVStream* out_stream;// get an AVPacket// 这里如果使用av_pkt指针的话,第二帧时就会出错ret = av_read_frame(av_in_fmt_ctx, &av_pkt);if (ret < 0) {break;}// write ptsif (av_pkt.pts == AV_NOPTS_VALUE && is_sender) {// write ptsAVRational time_base1 = av_in_fmt_ctx->streams[video_idx]->time_base;// Duration between 2 frames (us)int64_t calc_duration = (double)AV_TIME_BASE / av_q2d(av_in_fmt_ctx->streams[video_idx]->r_frame_rate);// parameters// pts是播放时间戳,告诉播放器什么时候播放这一帧视频,PTS通常是按照递增顺序排列的,以保证正确的时间顺序和播放同步// dts是解码时间戳,告诉播放器什么时候解码这一帧视频av_pkt.pts = (double)(frame_idx * calc_duration) / (double)(av_q2d(time_base1) * AV_TIME_BASE);av_pkt.dts = av_pkt.pts;av_pkt.duration = (double)calc_duration / (double)(av_q2d(time_base1) * AV_TIME_BASE);}// important: delayif (av_pkt.stream_index == video_idx && is_sender) {AVRational time_base = av_in_fmt_ctx->streams[video_idx]->time_base;AVRational time_base_q = { 1, AV_TIME_BASE };int64_t pts_time = av_rescale_q(av_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);}// av_usleep(50);}in_stream = av_in_fmt_ctx->streams[av_pkt.stream_index];out_stream = av_out_fmt_ctx->streams[av_pkt.stream_index];// copy packet// convert PTS/DTSav_pkt.pts = av_rescale_q_rnd(av_pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));av_pkt.dts = av_rescale_q_rnd(av_pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));av_pkt.duration = av_rescale_q(av_pkt.duration, in_stream->time_base, out_stream->time_base);av_pkt.pos = -1;// print to screenif (av_pkt.stream_index == video_idx) {if (is_sender) {fprintf(stdout, "Send %8d video frames to output URL\n", frame_idx);}else {fprintf(stdout, "Receive %8d video frames from input URL\n", frame_idx);}frame_idx++;}ret = av_interleaved_write_frame(av_out_fmt_ctx, &av_pkt);// ret = av_write_frame(av_out_fmt_ctx, av_pkt);if (ret < 0) {fprintf(stderr, "Error muxing packet, error code:%d\n", ret);break;}// av_packet_free(&av_pkt);av_packet_unref(&av_pkt);} // write file trailerav_write_trailer(av_out_fmt_ctx);end:avformat_close_input(&av_in_fmt_ctx);// close output/*if (av_out_fmt_ctx && !(av_out_fmt->flags & AVFMT_NOFILE)) {avio_close(av_out_fmt_ctx->pb);}*//*avformat_free_context(av_out_fmt_ctx);if (ret < 0 && ret != AVERROR_EOF) {fprintf(stderr, "Error occured\n");return -1;}*/return 0;
}int streamer()
{const char* in_url = "rtmp://127.0.0.1:1935/live/stream"; // input flv fileconst char* out_url = "receive.flv"; // output urlbool is_sender = 0;streamer_internal(in_url, out_url, is_sender);return 0;
}

3.3 测试

3.3.1 推流

使用代码进行推流,可以访问http://localhost/stat地址查看推流的状态。

...
...Metadata:encoder         : Lavf61.3.100Duration: 00:00:40.00, start: 0.000000, bitrate: 18849 kb/sStream #0:0: Video: h264 (High), yuv420p(progressive), 1920x1200, 25 fps, 25 tbr, 1k tbn
Output #0, flv, to 'rtmp://127.0.0.1:1935/live/stream':Stream #0:0: Video: h264 (High), yuv420p(progressive), 1920x1200, q=2-31
Send        0 video frames to output URL
Send        1 video frames to output URL
Send        2 video frames to output URL
Send        3 video frames to output URL
Send        4 video frames to output URL
Send        5 video frames to output URL
Send        6 video frames to output URL
Send        7 video frames to output URL
Send        8 video frames to output URL
Send        9 video frames to output URL
Send       10 video frames to output URL
Send       11 video frames to output URL
Send       12 video frames to output URL
Send       13 video frames to output URL
Send       14 video frames to output URL
Send       15 video frames to output URL
Send       16 video frames to output URL
Send       17 video frames to output URL
Send       18 video frames to output URL
...
...

3.3.2 拉流

拉流时,需要对齐推流和拉流时的RTMP地址。如果不对齐,拉流将会一直处于idel状态。

Input #0, flv, from 'rtmp://127.0.0.1:1935/live/stream':Metadata:|RtmpSampleAccess: trueServer          : NGINX RTMP (github.com/arut/nginx-rtmp-module)displayWidth    : 1920displayHeight   : 1200fps             : 25profile         :level           :Duration: 00:00:00.00, start: 59.120000, bitrate: N/AStream #0:0: Video: h264 (High), yuv420p(progressive), 1920x1200, 25 fps, 25 tbr, 1k tbn
Output #0, flv, to 'receive.flv':Stream #0:0: Video: h264 (High), yuv420p(progressive), 1920x1200, q=2-31
Receive        0 video frames from input URL
Receive        1 video frames from input URL
Receive        2 video frames from input URL
Receive        3 video frames from input URL
Receive        4 video frames from input URL
Receive        5 video frames from input URL
Receive        6 video frames from input URL
Receive        7 video frames from input URL
Receive        8 video frames from input URL
Receive        9 video frames from input URL
Receive       10 video frames from input URL
Receive       11 video frames from input URL
Receive       12 video frames from input URL

另外,推流和拉流也可以使用其他已有工具,例如推流直接使用ffmpeg.exe,拉流使用ffplay.exe(或VLC Media Player)

CSDN: https://blog.csdn.net/weixin_42877471
Github: https://github.com/DoFulangChen/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/10209.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

/usr/bin/ld: cannot find -l<nameOfTheLibrary>

在编译程序报了如下错误&#xff1a;/usr/bin/ld: cannot find -lmtcr_ul: No such file or directory 他的命名规则时"lnameOfTheLibrary"&#xff0c;所以我缺少一个mtcr_ul相关的库 问题原因 根本原因&#xff1a;还是某一个lib库文件不存在&#xff0c;你可以通…

SpringAMQP Work Queue 工作队列

消息模型: 代码模拟: 相较于之前的基础队列&#xff0c;该队列新增了消费者 不再是一个&#xff0c;所以我们通过代码模拟出两个consumer消费者。在原来的消费者类里写两个方法 其中消费者1效率高 消费者2效率低 RabbitListener(queues "simple.queue")public voi…

简化 KNN 检索【翻译】Simplifying kNN search

简化 KNN 检索 #转载 #大数据/ES #翻译 这篇文章是关于如何简化 k 最近邻&#xff08;k-Nearest Neighbors&#xff0c;简称 kNN&#xff09;搜索的深入探讨。以下是对全文的翻译(借助 kimi AI)&#xff1a; 在这篇博客文章中&#xff0c;我们将深入探讨我们为使 kNN 搜索的入…

mes系统业务学习

MES-生产溯源: 一物一码&#xff1a;一物一码&#xff0c;通过包装物或产品本身的条码追溯相关联原料、供应商、客户、订单、生产人员、生产过程、质检报告、售后等关键信息&#xff0c;覆盖产品全生命周期。精准质量追溯&#xff1a;通过采集扫描即时记录跟踪每一个关键信息&…

Arduino-ILI9341驱动开发TFT屏显示任意内容三

Arduino-ILI9341驱动开发TFT屏显示任意内容三 1.概述 这篇文章介绍使用ILI9341驱动提供的函数控制TFT屏显示字符串、图形、符号等等内容的编辑和展示。 2.硬件 2.1.硬件列表 名称数量Arduino Uno12.8" TFT彩色液晶触摸屏模块&#xff08;ILI9431&#xff09;110K 电阻…

SpringBootWeb 篇-深入了解请求响应(服务端接收不同类型的请求参数的方式)

&#x1f525;博客主页&#xff1a; 【小扳_-CSDN博客】 ❤感谢大家点赞&#x1f44d;收藏⭐评论✍ 文章目录 1.0 请求响应概述 1.1 简单参数 1.2 实体参数 2.3 数组集合参数 2.4 日期参数 2.5 json 参数 2.6 路径参数 3.0 完整代码 1.0 请求响应概述 当客户端发送不同的请求参…

Selenium定位方法及代码

天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物。 每个人都有惰性&#xff0c;但不断学习是好好生活的根本&#xff0c;共勉&#xff01; 文章均为学习整理笔记&#xff0c;分享记录为主&#xff0c;如有错误请指正&#xff0c;共同学习进步。…

中国1KM年相对湿度数据集1981-2020

大气相对湿度&#xff08;RH&#xff09;是气象/气候监测和研究的关键因素。然而&#xff0c;相对湿度在气候变化研究中的应用并不是很普遍&#xff0c;部分原因是相对湿度观测系列容易由于观测系统中的非气候变化而产生不均匀偏差。 该数据集是中国1km分辨率年相对湿度数据&am…

使用依赖注入(DI)的方式实现对冗余代码的解耦

1.1、优化前代码 GetMapping("/test") public void test(RequestParam("params") String params){if("1".equals(params)){// 逻辑代码}if("2".equals(params)){// 逻辑代码}if("3".equals(params)){// 逻辑代码} }1.2、优…

『大模型笔记』Google DeepMind and Isomorphic Labs联合发布AlphaFold 3!

Google DeepMind and Isomorphic Labs联合发布AlphaFold 3! 文章目录 一. Google DeepMind and Isomorphic Labs联合发布AlphaFold 3!AlphaFold 3 及其后续研究总结视频中提到的局限性AlphaFold Server结论二. 参考文献中文字幕视频链接,欢迎关注我的xhs账号:Google CEO 皮…

【MsSQL】数据库基础 库的基本操作

目录 一&#xff0c;数据库基础 1&#xff0c;什么是数据库 2&#xff0c;主流的数据库 3&#xff0c;连接服务器 4&#xff0c;服务器&#xff0c;数据库&#xff0c;表关系 5&#xff0c;使用案例 二&#xff0c;库的操作 1&#xff0c;创建数据库 2&#xff0c;创建…

华为配置Ethernet over GRE实现AC与无线网关之间的二层互通

华为配置Ethernet over GRE实现AC与无线网关之间的二层互通 组网图形 图1 通过Ethernet over GRE实现AC与无线网关之间的二层互通的组网图 组网需求数据规划配置思路操作步骤配置文件 组网需求 如图1所示&#xff0c;某企业通过无线网络为用户提供上网服务&#xff0c;其中A…

探索静态住宅代理IP:网络安全的隐形守护者

在当今这个数字化高速发展的时代&#xff0c;网络安全问题愈发凸显其重要性。无论是企业级的网络运营&#xff0c;还是个人用户的网络活动&#xff0c;都需要一个安全、稳定的网络环境。而在这个环境中&#xff0c;静态住宅代理IP以其独特的优势&#xff0c;逐渐成为了网络安全…

Java——类与对象

目录 一、面向对象的初步认识 1.1 什么是面向对象 1.2 面向对象与面向过程 二、类的定义与使用 2.1 简单认识类 2.2 类的定义格式 三、类的实例化 3.1 什么是实例化 3.2 类和对象的说明 四、this引用 4.1 为什么要有this引用 4.2 什么是this引用 ​编辑 4.3 this引用…

鸿蒙OpenHarmony:【常见编译问题和解决方法】

常见问题 常见编译问题和解决方法 鸿蒙开发指导文档&#xff1a;gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md点击或者复制转到。 提示“usr/sbin/ninja: invalid option -- w” 现象描述&#xff1a; 编译失败&#xff0c;提示“usr/sbin/ninja: invalid…

GO: 定时器NewTimer、NewTicker 和time.After

Go 之iota iota是一个常量计数器&#xff0c;一般在常量表达式中使用&#xff0c;可以理解为const定义常量的行数的索引&#xff0c;注意是行数 使用场景 主要应用在需要枚举的地方 示例1 package main import "fmt" const (NoPay iota // 订单未支付 0Pai…

设备二维码怎么生成?三分钟即可搞定

在现代工业生产中&#xff0c;设备的维护和巡检是保障生产连续性和安全性的重要环节。随着技术的发展&#xff0c;二维码技术因其便捷性和高效性被广泛应用于设备巡检中。 给每个设备配备一个二维码&#xff0c;一线人员用手机扫一扫&#xff0c;几秒钟就能上报巡检结果&#…

Measurement and Analysis of Large-Scale Network File System Workloads——论文泛读

ATC 2008 Paper 分布式元数据论文阅读笔记整理 问题 网络文件系统在当今的数据存储中发挥着越来越重要的作用。使用网络文件系统可以降低管理成本&#xff0c;从多个位置可靠地访问的数据。这些系统的设计通常以对文件系统工作负载和用户行为的理解为指导[12&#xff0c;19&a…

Chrome浏览器的一些实用命令

Chrome浏览器提供了许多实用的命令和内部页面&#xff0c;可以帮助用户更高效地管理和使用浏览器。以下是一些常用的Chrome命令和内部页面&#xff1a; chrome://about/: 查看所有支持的命令和内部页面。在地址栏中输入这个命令后&#xff0c;会列出所有可用的内部命令和URL&a…

C++ LCR 090. 打家劫舍 II

文章目录 一、题目描述二、参考代码 一、题目描述 一个专业的小偷&#xff0c;计划偷窃一个环形街道上沿街的房屋&#xff0c;每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 &#xff0c;这意味着第一个房屋和最后一个房屋是紧挨着的。同时&#xff0c;相邻的房屋…