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

时间: 2023-08-02 19:10:53 浏览: 285
以下是用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编码

在C++中实现RTMP协议发送H.264编码的音视频,涉及到多个关键步骤和技术,主要包括音视频采集、编码、封装以及RTMP协议的实现。以下是对这些知识点的详细解释: 1. **音视频采集**:通常使用DirectShow框架来捕获...
recommend-type

Android使用MediaCodec将摄像头采集的视频编码为h264

Android使用MediaCodec将摄像头采集的视频编码为h264 Android平台上,MediaCodec是Android 4.1(Jelly Bean)引入的一个新的多媒体编码解码器框架,它提供了一个统一的接口来访问各种硬件编码器和解码器。...
recommend-type

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

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

Linux服务器安装ffmpeg+libx264+libmp3lame

在 Linux 服务器上安装 FFmpeg,通常需要先安装一些依赖库,例如 libx264(用于 H.264 视频编码)和 libmp3lame(用于 MP3 音频编码)。以下是一个详细的安装步骤: 1. **检查并安装 GCC**: GCC 是 GNU Compiler ...
recommend-type

Spring Websocket快速实现与SSMTest实战应用

标题“websocket包”指代的是一个在计算机网络技术中应用广泛的组件或技术包。WebSocket是一种网络通信协议,它提供了浏览器与服务器之间进行全双工通信的能力。具体而言,WebSocket允许服务器主动向客户端推送信息,是实现即时通讯功能的绝佳选择。 描述中提到的“springwebsocket实现代码”,表明该包中的核心内容是基于Spring框架对WebSocket协议的实现。Spring是Java平台上一个非常流行的开源应用框架,提供了全面的编程和配置模型。在Spring中实现WebSocket功能,开发者通常会使用Spring提供的注解和配置类,简化WebSocket服务端的编程工作。使用Spring的WebSocket实现意味着开发者可以利用Spring提供的依赖注入、声明式事务管理、安全性控制等高级功能。此外,Spring WebSocket还支持与Spring MVC的集成,使得在Web应用中使用WebSocket变得更加灵活和方便。 直接在Eclipse上面引用,说明这个websocket包是易于集成的库或模块。Eclipse是一个流行的集成开发环境(IDE),支持Java、C++、PHP等多种编程语言和多种框架的开发。在Eclipse中引用一个库或模块通常意味着需要将相关的jar包、源代码或者配置文件添加到项目中,然后就可以在Eclipse项目中使用该技术了。具体操作可能包括在项目中添加依赖、配置web.xml文件、使用注解标注等方式。 标签为“websocket”,这表明这个文件或项目与WebSocket技术直接相关。标签是用于分类和快速检索的关键字,在给定的文件信息中,“websocket”是核心关键词,它表明该项目或文件的主要功能是与WebSocket通信协议相关的。 文件名称列表中的“SSMTest-master”暗示着这是一个版本控制仓库的名称,例如在GitHub等代码托管平台上。SSM是Spring、SpringMVC和MyBatis三个框架的缩写,它们通常一起使用以构建企业级的Java Web应用。这三个框架分别负责不同的功能:Spring提供核心功能;SpringMVC是一个基于Java的实现了MVC设计模式的请求驱动类型的轻量级Web框架;MyBatis是一个支持定制化SQL、存储过程以及高级映射的持久层框架。Master在这里表示这是项目的主分支。这表明websocket包可能是一个SSM项目中的模块,用于提供WebSocket通讯支持,允许开发者在一个集成了SSM框架的Java Web应用中使用WebSocket技术。 综上所述,这个websocket包可以提供给开发者一种简洁有效的方式,在遵循Spring框架原则的同时,实现WebSocket通信功能。开发者可以利用此包在Eclipse等IDE中快速开发出支持实时通信的Web应用,极大地提升开发效率和应用性能。
recommend-type

电力电子技术的智能化:数据中心的智能电源管理

# 摘要 本文探讨了智能电源管理在数据中心的重要性,从电力电子技术基础到智能化电源管理系统的实施,再到技术的实践案例分析和未来展望。首先,文章介绍了电力电子技术及数据中心供电架构,并分析了其在能效提升中的应用。随后,深入讨论了智能化电源管理系统的组成、功能、监控技术以及能
recommend-type

通过spark sql读取关系型数据库mysql中的数据

Spark SQL是Apache Spark的一个模块,它允许用户在Scala、Python或SQL上下文中查询结构化数据。如果你想从MySQL关系型数据库中读取数据并处理,你可以按照以下步骤操作: 1. 首先,你需要安装`PyMySQL`库(如果使用的是Python),它是Python与MySQL交互的一个Python驱动程序。在命令行输入 `pip install PyMySQL` 来安装。 2. 在Spark环境中,导入`pyspark.sql`库,并创建一个`SparkSession`,这是Spark SQL的入口点。 ```python from pyspark.sql imp
recommend-type

新版微软inspect工具下载:32位与64位版本

根据给定文件信息,我们可以生成以下知识点: 首先,从标题和描述中,我们可以了解到新版微软inspect.exe与inspect32.exe是两个工具,它们分别对应32位和64位的系统架构。这些工具是微软官方提供的,可以用来下载获取。它们源自Windows 8的开发者工具箱,这是一个集合了多种工具以帮助开发者进行应用程序开发与调试的资源包。由于这两个工具被归类到开发者工具箱,我们可以推断,inspect.exe与inspect32.exe是用于应用程序性能检测、问题诊断和用户界面分析的工具。它们对于开发者而言非常实用,可以在开发和测试阶段对程序进行深入的分析。 接下来,从标签“inspect inspect32 spy++”中,我们可以得知inspect.exe与inspect32.exe很有可能是微软Spy++工具的更新版或者是有类似功能的工具。Spy++是Visual Studio集成开发环境(IDE)的一个组件,专门用于Windows应用程序。它允许开发者观察并调试与Windows图形用户界面(GUI)相关的各种细节,包括窗口、控件以及它们之间的消息传递。使用Spy++,开发者可以查看窗口的句柄和类信息、消息流以及子窗口结构。新版inspect工具可能继承了Spy++的所有功能,并可能增加了新功能或改进,以适应新的开发需求和技术。 最后,由于文件名称列表仅提供了“ed5fa992d2624d94ac0eb42ee46db327”,没有提供具体的文件名或扩展名,我们无法从这个文件名直接推断出具体的文件内容或功能。这串看似随机的字符可能代表了文件的哈希值或是文件存储路径的一部分,但这需要更多的上下文信息来确定。 综上所述,新版的inspect.exe与inspect32.exe是微软提供的开发者工具,与Spy++有类似功能,可以用于程序界面分析、问题诊断等。它们是专门为32位和64位系统架构设计的,方便开发者在开发过程中对应用程序进行深入的调试和优化。同时,使用这些工具可以提高开发效率,确保软件质量。由于这些工具来自Windows 8的开发者工具箱,它们可能在兼容性、效率和用户体验上都经过了优化,能够为Windows应用的开发和调试提供更加专业和便捷的解决方案。
recommend-type

如何运用电力电子技术实现IT设备的能耗监控

# 摘要 随着信息技术的快速发展,IT设备能耗监控已成为提升能效和减少环境影响的关键环节。本文首先概述了电力电子技术与IT设备能耗监控的重要性,随后深入探讨了电力电子技术的基础原理及其在能耗监控中的应用。文章详细分析了IT设备能耗监控的理论框架、实践操作以及创新技术的应用,并通过节能改造案例展示了监控系统构建和实施的成效。最后,本文展望了未来能耗监控技术的发展趋势,同时
recommend-type

2635.656845多位小数数字,js不使用四舍五入保留两位小数,然后把结果千分位,想要的结果是2,635.65;如何处理

在JavaScript中,如果你想要将2635.656845这个数字精确地保留两位小数,并且去掉多余的千分位,可以使用`toFixed()`函数结合字符串切片的方法来实现。不过需要注意的是,`toFixed()`会返回一个字符串,所以我们需要先转换它。 以下是一个示例: ```javascript let num = 2635.656845; // 使用 toFixed() 保留两位小数,然后去掉多余的三位 let roundedNum = num.toFixed(2).substring(0, 5); // 如果最后一个字符是 '0',则进一步判断是否真的只有一位小数 if (round