对应RTMP推流,业界有很多开源方案。如使用ffmpeg推流,librtmp(rtmp-dump),gstream推流。由于ffmpeg和gstreamer比较庞大,仅仅用来推流,有大炮打蚊子之嫌。针对客户端特别是瘦客户端,使用librtmp(rtmp-dump)方案更加精简,更加高效。
本方案基本思路:

1.下载并编译librtmp。
1下载地址:http://rtmpdump.mplayerhq.hu/download/
编译成功后产生一个librtmp.so 库。
2.调用librtmp,封装一个视频层Wrapper_RtmpLib.cpp,该类定义如下:
1class Wrapper_RtmpLib 2{
3 public:
4 Wrapper_RtmpLib(char * url);
5 ~Wrapper_RtmpLib();
6 int Open();
7 int SendData(char * data,int dataLength,unsigned int timeStamp,int debug = -1);
8 int IsConnect();
9 int Close();
10 private:
11 int InitSockets();
12 void CleanupSockets();
13 int pushSPSPPS(char *sps, int spsLen, char *pps,int ppsLen, int m_stream_id,unsigned int timeStamp);
14 int pushVideoData(char *data, int dataLen, boolkeyFrame, int m_stream_id,unsigned int AtimeStamp);
15 int GetStartPrixLen(char *Pack, int offest);
16 char * rtmpUrl = NULL;
17 RTMP * m_pRtmp = NULL;
18 NALU * CopyNALU(NALU * src);
19 void FreeNALU(NALU * nalu);
20};
Wrapper_RtmpLib类负责对外提供RTMP推流接口。
基本使用步骤:
1一. 定义一个Wrapper_RtmpLib对象test
2二. Test.open(),与服务器建立rtmp信令相关连接
3三. int SendData(char * data,int dataLength, unsigned int timeStamp,intdebug = -1);发送RTMP数据
注意data,必须是一个完整的NAL单元。所以应用程序调该接口前必须解析出NAL单元。
下面是一个h264裸文件推送RTMP过程。
1#include
2#include"Wrapper_RtmpLib.hpp"
3#include
4#include
5#include
6#include
7#define LEN_R 1400
8//检测启动码,并获取启动码的长度
9
10int GetStartCode(char *Pack, int offest) 11{
12 intiStartPrexLen = 0;
13 if(Pack[offest] == '\x00' && Pack[offest + 1] =='\x00'&&Pack[offest + 2] == '\x00'&&Pack[offest + 3] == '\x01')
14 {
15 iStartPrexLen= 4;
16 returniStartPrexLen;
17 }
18 elseif (Pack[offest] == '\x00' && Pack[offest + 1] =='\x00'&&Pack[offest + 2] == '\x01')
19 {
20 iStartPrexLen= 3;
21 returniStartPrexLen;
22 }
23 else
24 {
25 returniStartPrexLen;
26 }
27}
28#include
29void delaytime(int ms) 30{
31// return;
32 structtimespec tvUec;
33 clock_gettime(CLOCK_MONOTONIC,&tvUec);
34 longlong pretime = tvUec.tv_nsec / 1000000 + tvUec.tv_sec * 1000;
35 longlong nowtime = tvUec.tv_nsec / 1000000 + tvUec.tv_sec * 1000;
36 while(1)
37 {
38 clock_gettime(CLOCK_MONOTONIC,&tvUec);
39 nowtime= tvUec.tv_nsec / 1000000 + tvUec.tv_sec * 1000;
40 if(nowtime - pretime > ms-10) //程序自身耗时,预估耗时10ms。实现网络流不要延时,仅供测试
41
42 {
43 return;
44 }
45 }
46
47}
48void help(char *p) 49{
50 printf("Use:");
51

本文介绍了如何使用librtmp进行RTMP推流,包括编译librtmp库,封装视频层Wrapper_RtmpLib,以及推流的基本步骤。特别强调SendData需发送完整NAL单元,并给出了h264文件推送到RTMP服务器的示例。同时提醒在云主机上推流需要注意使用内网IP。
最低0.47元/天 解锁文章
2943

被折叠的 条评论
为什么被折叠?



