pcm使用ffmpeg编码h264,然后用srs-librtmp推流 C++例子

时间: 2023-08-02 16:10:53 浏览: 78
以下是用ffmpeg编码h264并用srs-librtmp推流的C++例子: ```cpp #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <time.h> #include <stdint.h> #include <math.h> #include <signal.h> extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/opt.h> #include <libavutil/imgutils.h> #include <libavutil/mathematics.h> #include <libavutil/time.h> #include <libswscale/swscale.h> #include <libswresample/swresample.h> #include <librtmp/rtmp.h> #include <librtmp/log.h> } #define W 640 #define H 480 #define FPS 30 #define BITRATE 500000 AVFormatContext *pFormatCtx; AVOutputFormat *pOutputFmt; AVStream *pVideoStream; AVCodecContext *pVideoCodecCtx; AVCodec *pVideoCodec; AVFrame *pVideoFrame; AVPacket videoPkt; uint8_t *videoBuf; SwsContext *pImgConvertCtx; RTMP *pRtmp; RTMPPacket rtmpPkt; int64_t pts = 0; void signal_handler(int signo) { if (signo == SIGINT) { printf("Got SIGINT signal, exiting...\n"); exit(1); } } void init_video_codec() { pVideoCodec = avcodec_find_encoder(AV_CODEC_ID_H264); if (!pVideoCodec) { fprintf(stderr, "Failed to find H.264 codec\n"); exit(1); } pVideoCodecCtx = avcodec_alloc_context3(pVideoCodec); if (!pVideoCodecCtx) { fprintf(stderr, "Failed to allocate H.264 codec context\n"); exit(1); } pVideoCodecCtx->bit_rate = BITRATE; pVideoCodecCtx->width = W; pVideoCodecCtx->height = H; pVideoCodecCtx->time_base.num = 1; pVideoCodecCtx->time_base.den = FPS; pVideoCodecCtx->gop_size = FPS * 2; pVideoCodecCtx->max_b_frames = 1; pVideoCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P; if (pOutputFmt->flags & AVFMT_GLOBALHEADER) pVideoCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; av_opt_set(pVideoCodecCtx->priv_data, "preset", "ultrafast", 0); av_opt_set(pVideoCodecCtx->priv_data, "tune", "zerolatency", 0); if (avcodec_open2(pVideoCodecCtx, pVideoCodec, NULL) < 0) { fprintf(stderr, "Failed to open H.264 codec\n"); exit(1); } pVideoFrame = av_frame_alloc(); if (!pVideoFrame) { fprintf(stderr, "Failed to allocate video frame\n"); exit(1); } pVideoFrame->format = pVideoCodecCtx->pix_fmt; pVideoFrame->width = pVideoCodecCtx->width; pVideoFrame->height = pVideoCodecCtx->height; if (av_frame_get_buffer(pVideoFrame, 32) < 0) { fprintf(stderr, "Failed to allocate video frame buffer\n"); exit(1); } videoBuf = (uint8_t*)av_malloc(av_image_get_buffer_size(pVideoCodecCtx->pix_fmt, pVideoCodecCtx->width, pVideoCodecCtx->height, 1)); if (!videoBuf) { fprintf(stderr, "Failed to allocate video buffer\n"); exit(1); } av_image_fill_arrays(pVideoFrame->data, pVideoFrame->linesize, videoBuf, pVideoCodecCtx->pix_fmt, pVideoCodecCtx->width, pVideoCodecCtx->height, 1); } void init_sws_context() { pImgConvertCtx = sws_getContext(pVideoCodecCtx->width, pVideoCodecCtx->height, AV_PIX_FMT_BGR24, pVideoCodecCtx->width, pVideoCodecCtx->height, pVideoCodecCtx->pix_fmt, SWS_BICUBIC, NULL, NULL, NULL); if (!pImgConvertCtx) { fprintf(stderr, "Failed to create SwsContext\n"); exit(1); } } void init_output() { avformat_alloc_output_context2(&pFormatCtx, NULL, "flv", NULL); if (!pFormatCtx) { fprintf(stderr, "Failed to allocate output context\n"); exit(1); } pOutputFmt = pFormatCtx->oformat; if (pOutputFmt->video_codec == AV_CODEC_ID_NONE) { fprintf(stderr, "Failed to find suitable video codec\n"); exit(1); } init_video_codec(); init_sws_context(); pVideoStream = avformat_new_stream(pFormatCtx, pVideoCodec); if (!pVideoStream) { fprintf(stderr, "Failed to allocate video stream\n"); exit(1); } pVideoStream->id = 0; pVideoStream->time_base.num = 1; pVideoStream->time_base.den = FPS; pVideoStream->codecpar->codec_id = pVideoCodec->id; pVideoStream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; pVideoStream->codecpar->width = W; pVideoStream->codecpar->height = H; pVideoStream->codecpar->format = pVideoCodecCtx->pix_fmt; if (avformat_write_header(pFormatCtx, NULL) < 0) { fprintf(stderr, "Failed to write header\n"); exit(1); } } void init_rtmp(const char *url) { RTMP_LogSetLevel(RTMP_LOGDEBUG); pRtmp = RTMP_Alloc(); if (!pRtmp) { fprintf(stderr, "Failed to allocate RTMP object\n"); exit(1); } if (!RTMP_Init(pRtmp)) { fprintf(stderr, "Failed to initialize RTMP object\n"); exit(1); } if (!RTMP_SetupURL(pRtmp, (char*)url)) { fprintf(stderr, "Failed to set RTMP URL\n"); exit(1); } RTMP_EnableWrite(pRtmp); if (!RTMP_Connect(pRtmp, NULL)) { fprintf(stderr, "Failed to connect to RTMP server\n"); exit(1); } if (!RTMP_ConnectStream(pRtmp, 0)) { fprintf(stderr, "Failed to connect to RTMP stream\n"); exit(1); } } void cleanup() { av_write_trailer(pFormatCtx); avcodec_free_context(&pVideoCodecCtx); av_frame_free(&pVideoFrame); av_free(videoBuf); sws_freeContext(pImgConvertCtx); RTMP_Close(pRtmp); RTMP_Free(pRtmp); avformat_free_context(pFormatCtx); } void encode_frame() { AVFrame *pFrameBGR24 = av_frame_alloc(); if (!pFrameBGR24) { fprintf(stderr, "Failed to allocate BGR24 frame\n"); exit(1); } pFrameBGR24->format = AV_PIX_FMT_BGR24; pFrameBGR24->width = W; pFrameBGR24->height = H; if (av_frame_get_buffer(pFrameBGR24, 32) < 0) { fprintf(stderr, "Failed to allocate BGR24 frame buffer\n"); exit(1); } // generate test pattern for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { uint8_t r, g, b; if (x < W / 2) { r = 255 * x * 2 / W; g = 255 * y / H; b = 255 - 255 * x * 2 / W; } else { r = 255 - 255 * (x - W / 2) * 2 / W; g = 255 - 255 * y / H; b = 255 * (x - W / 2) * 2 / W; } pFrameBGR24->data[0][y * pFrameBGR24->linesize[0] + x * 3] = b; pFrameBGR24->data[0][y * pFrameBGR24->linesize[0] + x * 3 + 1] = g; pFrameBGR24->data[0][y * pFrameBGR24->linesize[0] + x * 3 + 2] = r; } } sws_scale(pImgConvertCtx, pFrameBGR24->data, pFrameBGR24->linesize, 0, H, pVideoFrame->data, pVideoFrame->linesize); av_init_packet(&videoPkt); videoPkt.data = NULL; videoPkt.size = 0; pVideoFrame->pts = pts++; int ret = avcodec_send_frame(pVideoCodecCtx, pVideoFrame); if (ret < 0) { fprintf(stderr, "Failed to send video frame: %s\n", av_err2str(ret)); exit(1); } while (ret >= 0) { ret = avcodec_receive_packet(pVideoCodecCtx, &videoPkt); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; else if (ret < 0) { fprintf(stderr, "Failed to receive video packet: %s\n", av_err2str(ret)); exit(1); } rtmpPkt.m_nChannel = 0x04; rtmpPkt.m_headerType = RTMP_PACKET_TYPE_VIDEO; rtmpPkt.m_nTimeStamp = videoPkt.pts * 1000 / FPS; rtmpPkt.m_nBodySize = videoPkt.size; rtmpPkt.m_nInfoField2 = pRtmp->m_stream_id; rtmpPkt.m_body = videoPkt.data; if (!RTMP_IsConnected(pRtmp)) break; if (!RTMP_SendPacket(pRtmp, &rtmpPkt, TRUE)) { fprintf(stderr, "Failed to send RTMP packet\n"); exit(1); } av_packet_unref(&videoPkt); } av_frame_free(&pFrameBGR24); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s <rtmp url>\n", argv[0]); exit(1); } init_output(); init_rtmp(argv[1]); signal(SIGINT, signal_handler); while (1) { encode_frame(); usleep(1000000 / FPS); } cleanup(); return 0; } ``` 这个例子会生成一个测试图案并用ffmpeg编码成H.264,然后用srs-librtmp推流到指定的RTMP服务器上。你需要将代码中的推流地址替换为你自己的RTMP服务器地址。

相关推荐

最新推荐

recommend-type

C++实验RTMP协议发送 H.264编码

RTMP(Real Time Messaging Protocol)是专门用来传输音视频数据的流媒体协议,最初由Macromedia 公司创建,后来归Adobe公司所有,是一种私有协议,主要用来联系Flash Player和RtmpServer,如FMS, Red5, crtmpserver...
recommend-type

Java解码H264格式视频流中的图片

"Java解码H264格式视频流中的图片" ...Java解码H264格式视频流中的图片需要使用到一些专门的库和工具,例如JavaCV和FFmpeg,并且需要注意版本问题。通过使用这些库和工具,我们可以将H264格式的视频流转换为图片。
recommend-type

ffmpeg H264解码decode_mb_cavlc函数参数解释

"ffmpeg H264解码decode_mb_cavlc函数参数解释" 本文将详细解释ffmpeg H264解码slice的decode_mb_cavlc函数参数,包括mb_skip_run、mb_field_decoding_flag、mb_type、i_mb_type_info、b_mb_type_info、p_mb_type_...
recommend-type

Linux服务器安装ffmpeg+libx264+libmp3lame

ffmpeg是一个很强大的音视频处理工具,官网是:http://ffmpeg.org/ 官网介绍ffmpeg是:一个完整的、跨平台的解决方案,可以记录、转换和传输音频和视频。...Linux服务器安装ffmpeg+libx264+libmp3lame
recommend-type

合信TP-i系列HMI触摸屏CAD图.zip

合信TP-i系列HMI触摸屏CAD图
recommend-type

BSC关键绩效财务与客户指标详解

BSC(Balanced Scorecard,平衡计分卡)是一种战略绩效管理系统,它将企业的绩效评估从传统的财务维度扩展到非财务领域,以提供更全面、深入的业绩衡量。在提供的文档中,BSC绩效考核指标主要分为两大类:财务类和客户类。 1. 财务类指标: - 部门费用的实际与预算比较:如项目研究开发费用、课题费用、招聘费用、培训费用和新产品研发费用,均通过实际支出与计划预算的百分比来衡量,这反映了部门在成本控制上的效率。 - 经营利润指标:如承保利润、赔付率和理赔统计,这些涉及保险公司的核心盈利能力和风险管理水平。 - 人力成本和保费收益:如人力成本与计划的比例,以及标准保费、附加佣金、续期推动费用等与预算的对比,评估业务运营和盈利能力。 - 财务效率:包括管理费用、销售费用和投资回报率,如净投资收益率、销售目标达成率等,反映公司的财务健康状况和经营效率。 2. 客户类指标: - 客户满意度:通过包装水平客户满意度调研,了解产品和服务的质量和客户体验。 - 市场表现:通过市场销售月报和市场份额,衡量公司在市场中的竞争地位和销售业绩。 - 服务指标:如新契约标保完成度、续保率和出租率,体现客户服务质量和客户忠诚度。 - 品牌和市场知名度:通过问卷调查、公众媒体反馈和总公司级评价来评估品牌影响力和市场认知度。 BSC绩效考核指标旨在确保企业的战略目标与财务和非财务目标的平衡,通过量化这些关键指标,帮助管理层做出决策,优化资源配置,并驱动组织的整体业绩提升。同时,这份指标汇总文档强调了财务稳健性和客户满意度的重要性,体现了现代企业对多维度绩效管理的重视。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【实战演练】俄罗斯方块:实现经典的俄罗斯方块游戏,学习方块生成和行消除逻辑。

![【实战演练】俄罗斯方块:实现经典的俄罗斯方块游戏,学习方块生成和行消除逻辑。](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/70a49cc62dcc46a491b9f63542110765~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp) # 1. 俄罗斯方块游戏概述** 俄罗斯方块是一款经典的益智游戏,由阿列克谢·帕基特诺夫于1984年发明。游戏目标是通过控制不断下落的方块,排列成水平线,消除它们并获得分数。俄罗斯方块风靡全球,成为有史以来最受欢迎的视频游戏之一。 # 2.
recommend-type

卷积神经网络实现手势识别程序

卷积神经网络(Convolutional Neural Network, CNN)在手势识别中是一种非常有效的机器学习模型。CNN特别适用于处理图像数据,因为它能够自动提取和学习局部特征,这对于像手势这样的空间模式识别非常重要。以下是使用CNN实现手势识别的基本步骤: 1. **输入数据准备**:首先,你需要收集或获取一组带有标签的手势图像,作为训练和测试数据集。 2. **数据预处理**:对图像进行标准化、裁剪、大小调整等操作,以便于网络输入。 3. **卷积层(Convolutional Layer)**:这是CNN的核心部分,通过一系列可学习的滤波器(卷积核)对输入图像进行卷积,以
recommend-type

绘制企业战略地图:从财务到客户价值的六步法

"BSC资料.pdf" 战略地图是一种战略管理工具,它帮助企业将战略目标可视化,确保所有部门和员工的工作都与公司的整体战略方向保持一致。战略地图的核心内容包括四个相互关联的视角:财务、客户、内部流程和学习与成长。 1. **财务视角**:这是战略地图的最终目标,通常表现为股东价值的提升。例如,股东期望五年后的销售收入达到五亿元,而目前只有一亿元,那么四亿元的差距就是企业的总体目标。 2. **客户视角**:为了实现财务目标,需要明确客户价值主张。企业可以通过提供最低总成本、产品创新、全面解决方案或系统锁定等方式吸引和保留客户,以实现销售额的增长。 3. **内部流程视角**:确定关键流程以支持客户价值主张和财务目标的实现。主要流程可能包括运营管理、客户管理、创新和社会责任等,每个流程都需要有明确的短期、中期和长期目标。 4. **学习与成长视角**:评估和提升企业的人力资本、信息资本和组织资本,确保这些无形资产能够支持内部流程的优化和战略目标的达成。 绘制战略地图的六个步骤: 1. **确定股东价值差距**:识别与股东期望之间的差距。 2. **调整客户价值主张**:分析客户并调整策略以满足他们的需求。 3. **设定价值提升时间表**:规划各阶段的目标以逐步缩小差距。 4. **确定战略主题**:识别关键内部流程并设定目标。 5. **提升战略准备度**:评估并提升无形资产的战略准备度。 6. **制定行动方案**:根据战略地图制定具体行动计划,分配资源和预算。 战略地图的有效性主要取决于两个要素: 1. **KPI的数量及分布比例**:一个有效的战略地图通常包含20个左右的指标,且在四个视角之间有均衡的分布,如财务20%,客户20%,内部流程40%。 2. **KPI的性质比例**:指标应涵盖财务、客户、内部流程和学习与成长等各个方面,以全面反映组织的绩效。 战略地图不仅帮助管理层清晰传达战略意图,也使员工能更好地理解自己的工作如何对公司整体目标产生贡献,从而提高执行力和组织协同性。