RTMPdump使用相關


在FFMPEG中使用libRTMP的經驗

FFMPEG在編譯的時候可以選擇支持RTMP的類庫libRTMP。這樣ffmpeg就可以支持rtmp://, rtmpt://, rtmpe://, rtmpte://,以及 rtmps://協議了。但是如何使用ffmpeg支持RTMP協議還是有一定的學問的。本文總結一下部分經驗。

ffmpeg 接受一個字符串的輸入方式,比如:“rtmp://xxxx live=1 playpath=xxx ...”這種的輸入形式,即第一個字符串是rtmp的url,然后加一個空格,然后再附加一些參數。附加的參數的格式形如“playpath=xxxx” 這種形式。這個乍一看讓人覺得有點不習慣。因為一般的輸入只包含一個字符串,比如說一個流媒體的url或者是文件的路徑,不會采用“url+空格+參數1+參數2+...”的形式。

例如,當需要打開一個直播流的時候,可以用如下字符串(這里連接的是中國教育電視台1頻道(網絡直播)):

rtmp://pub1.guoshi.com/live/newcetv1

當需要用ffmpeg保存RTMP直播流媒體的時候:

ffmpeg -i "rtmp://pub1.guoshi.com/live/newcetv1 live=1" -vcodec copy -acodec copy ttt.flv

當需要用ffplay播放RTMP直播流媒體的時候:

ffplay "rtmp://pub1.guoshi.com/live/newcetv1 live=1"

在使用FFMPEG類庫進行編程的時候,也是一樣的,只需要將字符串傳遞給avformat_open_input()就行了,形如(這里連接的是香港電視台頻道(網絡直播)):

char url[]="rtmp://live.hkstv.hk.lxdns.com/live/hks live=1";  
avformat_open_input(&pFormatCtx,url,NULL,&avdic)

注:librtmp支持的參數:http://rtmpdump.mplayerhq.hu/librtmp.3.html

基於RTMP的實時流媒體的QoE分析

Holly French等人在論文《Real Time Video QoE Analysis of RTMP Streams》中,研究了基於RTMP的實時視頻的QoE。在此記錄一下。

他們的研究結果表明,碼率(bitrate)與幀率或者帶寬結合,可以相對准確的反映RTMP視頻流的QoE。

他們的實驗設計如下圖所示。分析服務器包含質量分析器以及相應的數據庫。web服務器提供了顯示視頻的頁面。Flash流媒體服務器是提供視頻源。Flash流媒體服務器和客戶端之間有一個網絡模擬器,可以模擬網絡上的丟包和延時。

實驗一共有10人參加,平均每人觀看10個視頻。測試序列如下表所示:

引入的丟包率在0-15%,時延在0-100ms。

實驗的結果如下圖所示。橫坐標為3個測試序列,其中每個序列都通過不同的指標預測RTMP流的QoE。縱坐標為精確度。

從實驗的結果來看,對於高清晰度的視頻,使用帶寬+碼率(BW+BR)預測QoE的精確度能達到80%。

對於標准清晰度的視頻,使用碼率+幀率(BR+FR)或者單獨使用碼率預測QoE的精確度能達到70%。

最終可以得出結論:碼率(bitrate)與幀率或者帶寬結合,可以相對准確的反映RTMP視頻流的QoE。

最簡單的基於FFmpeg的推流器(以推送RTMP為例)

本文記錄一個最簡單的基於FFmpeg的推流器(simplest ffmpeg streamer)。推流器的作用就是將本地的視頻數據推送至流媒體服務器。本文記錄的推流器,可以將本地的 MOV / AVI / MKV / MP4 / FLV 等格式的媒體文件,通過流媒體協議(例如RTMP,HTTP,UDP,TCP,RTP等等)以直播流的形式推送出去。由於流媒體協議種類繁多,不一一記錄。在這里記錄將本地文件以RTMP直播流的形式推送至RTMP流媒體服務器(例如 Flash Media Server,Red5,Wowza等等)的方法。
在這個推流器的基礎上可以進行多種方式的修改,實現各式各樣的推流器。例如:
* 將輸入文件改為網絡流URL,可以實現轉流器。
* 將輸入的文件改為回調函數(內存讀取)的形式,可以推送內存中的視頻數據。
* 將輸入文件改為系統設備(通過libavdevice),同時加上編碼的功能,可以實現實時推流器(現場直播)。

PS:本程序並不包含視頻轉碼的功能。

簡介

RTMP 推流器(Streamer)的在流媒體系統中的作用可以用下圖表示。首先將視頻數據以RTMP的形式發送到流媒體服務器端(Server,比如 FMS,Red5,Wowza等),然后客戶端(一般為Flash Player)通過訪問流媒體服務器就可以收看實時流了。

運行本程序之前需要先運行RTMP流媒體服務器,並在流媒體服務器上建立相應的Application。有關流媒體服務器的操作不在本文的論述范圍內,在此不再詳述。本程序運行后,即可通過RTMP客戶端(例如 Flash Player, FFplay等等)收看推送的直播流。

需要要注意的地方

封裝格式

RTMP采用的封裝格式是FLV。因此在指定輸出流媒體的時候需要指定其封裝格式為“flv”。同理,其他流媒體協議也需要指定其封裝格式。例如采用UDP推送流媒體的時候,可以指定其封裝格式為“mpegts”。

延時

發送流媒體的數據的時候需要延時。不然的話,FFmpeg處理數據速度很快,瞬間就能把所有的數據發送出去,流媒體服務器是接受不了的。因此需要按照視頻實際的幀率發送數據。本文記錄的推流器在視頻幀與幀之間采用了av_usleep()函數休眠的方式來延遲發送。這樣就可以按照視頻的幀率發送數據了,參考代碼如下。

//
int64_t start_time=av_gettime();  
while (1) {  
////Important:Delay
if(pkt.stream_index==videoindex){  
        AVRational time_base=ifmt_ctx->streams[videoindex]->time_base;  
        AVRational time_base_q={1,AV_TIME_BASE};  
        int64_t pts_time = av_rescale_q(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);  
    }  
//
}  
//
PTS/DTS問題

沒有封裝格式的裸流(例如H.264裸流)是不包含PTS、DTS這些參數的。在發送這種數據的時候,需要自己計算並寫入AVPacket的PTS,DTS,duration等參數。這里還沒有深入研究,簡單寫了一點代碼,如下所示。

//FIX:No PTS (Example: Raw H.264)
//Simple Write PTS
if(pkt.pts==AV_NOPTS_VALUE){  
//Write PTS
    AVRational time_base1=ifmt_ctx->streams[videoindex]->time_base;  
//Duration between 2 frames (us)
    int64_t calc_duration=(double)AV_TIME_BASE/av_q2d(ifmt_ctx->streams[videoindex]->r_frame_rate);  
//Parameters
    pkt.pts=(double)(frame_index*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE);  
    pkt.dts=pkt.pts;  
    pkt.duration=(double)calc_duration/(double)(av_q2d(time_base1)*AV_TIME_BASE);  
}

程序流程圖

程序的流程圖如下圖所示。可以看出和《最簡單的基於FFMPEG的封裝格式轉換器(無編解碼)》中的封裝格式轉換器比較類似。它們之間比較明顯的區別在於:
1. Streamer輸出為URL
2. Streamer包含了延時部分

代碼

代碼如下。

/**
 * 最簡單的基於FFmpeg的推流器(推送RTMP)
 * Simplest FFmpeg Streamer (Send RTMP)
 * 
 * 雷霄驊 Lei Xiaohua
 * leixiaohua1020@126.com
 * 中國傳媒大學/數字電視技術
 * Communication University of China / Digital TV Technology
 * http://blog.csdn.net/leixiaohua1020
 * 
 * 本例子實現了推送本地視頻至流媒體服務器(以RTMP為例)。
 * 是使用FFmpeg進行流媒體推送最簡單的教程。
 *
 * This example stream local media files to streaming media 
 * server (Use RTMP as example). 
 * It's the simplest FFmpeg streamer.
 * 
 */

#include <stdio.h>

#define __STDC_CONSTANT_MACROS

#ifdef _WIN32
//Windows
extern "C"
{  
#include "libavformat/avformat.h"
#include "libavutil/mathematics.h"
#include "libavutil/time.h"
};  
#else
//Linux...
#ifdef __cplusplus
extern "C"
{  
#endif
#include <libavformat/avformat.h>
#include <libavutil/mathematics.h>
#include <libavutil/time.h>
#ifdef __cplusplus
};  
#endif
#endif

int main(int argc, char* argv[])  
{  
    AVOutputFormat *ofmt = NULL;  
//輸入對應一個AVFormatContext,輸出對應一個AVFormatContext
//(Input AVFormatContext and Output AVFormatContext)
    AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;  
    AVPacket pkt;  
const char *in_filename, *out_filename;  
int ret, i;  
int videoindex=-1;  
int frame_index=0;  
    int64_t start_time=0;  
//in_filename  = "cuc_ieschool.mov";
//in_filename  = "cuc_ieschool.mkv";
//in_filename  = "cuc_ieschool.ts";
//in_filename  = "cuc_ieschool.mp4";
//in_filename  = "cuc_ieschool.h264";
    in_filename  = "cuc_ieschool.flv";//輸入URL(Input file URL)
//in_filename  = "shanghai03_p.h264";

    out_filename = "rtmp://localhost/publishlive/livestream";//輸出 URL(Output URL)[RTMP]  
//out_filename = "rtp://233.233.233.233:6666";//輸出 URL(Output URL)[UDP]

    av_register_all();  
//Network
    avformat_network_init();  
//輸入(Input)
if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {  
        printf( "Could not open input file.");  
goto end;  
    }  
if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {  
        printf( "Failed to retrieve input stream information");  
goto end;  
    }  

for(i=0; i<ifmt_ctx->nb_streams; i++)   
if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){  
            videoindex=i;  
break;  
        }  

    av_dump_format(ifmt_ctx, 0, in_filename, 0);  

//輸出(Output)

    avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_filename); //RTMP
//avformat_alloc_output_context2(&ofmt_ctx, NULL, "mpegts", out_filename);//UDP

if (!ofmt_ctx) {  
        printf( "Could not create output context\n");  
        ret = AVERROR_UNKNOWN;  
goto end;  
    }  
    ofmt = ofmt_ctx->oformat;  
for (i = 0; i < ifmt_ctx->nb_streams; i++) {  
//根據輸入流創建輸出流(Create output AVStream according to input AVStream)
        AVStream *in_stream = ifmt_ctx->streams[i];  
        AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);  
if (!out_stream) {  
            printf( "Failed allocating output stream\n");  
            ret = AVERROR_UNKNOWN;  
goto end;  
        }  
//復制AVCodecContext的設置(Copy the settings of AVCodecContext)
        ret = avcodec_copy_context(out_stream->codec, in_stream->codec);  
if (ret < 0) {  
            printf( "Failed to copy context from input to output stream codec context\n");  
goto end;  
        }  
        out_stream->codec->codec_tag = 0;  
if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)  
            out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;  
    }  
//Dump Format------------------
    av_dump_format(ofmt_ctx, 0, out_filename, 1);  
//打開輸出URL(Open output URL)
if (!(ofmt->flags & AVFMT_NOFILE)) {  
        ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);  
if (ret < 0) {  
            printf( "Could not open output URL '%s'", out_filename);  
goto end;  
        }  
    }  
//寫文件頭(Write file header)
    ret = avformat_write_header(ofmt_ctx, NULL);  
if (ret < 0) {  
        printf( "Error occurred when opening output URL\n");  
goto end;  
    }  

    start_time=av_gettime();  
while (1) {  
        AVStream *in_stream, *out_stream;  
//獲取一個AVPacket(Get an AVPacket)
        ret = av_read_frame(ifmt_ctx, &pkt);  
if (ret < 0)  
break;  
//FIX:No PTS (Example: Raw H.264)
//Simple Write PTS
if(pkt.pts==AV_NOPTS_VALUE){  
//Write PTS
            AVRational time_base1=ifmt_ctx->streams[videoindex]->time_base;  
//Duration between 2 frames (us)
            int64_t calc_duration=(double)AV_TIME_BASE/av_q2d(ifmt_ctx->streams[videoindex]->r_frame_rate);  
//Parameters
            pkt.pts=(double)(frame_index*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE);  
            pkt.dts=pkt.pts;  
            pkt.duration=(double)calc_duration/(double)(av_q2d(time_base1)*AV_TIME_BASE);  
        }  
//Important:Delay
if(pkt.stream_index==videoindex){  
            AVRational time_base=ifmt_ctx->streams[videoindex]->time_base;  
            AVRational time_base_q={1,AV_TIME_BASE};  
            int64_t pts_time = av_rescale_q(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);  

        }  

        in_stream  = ifmt_ctx->streams[pkt.stream_index];  
        out_stream = ofmt_ctx->streams[pkt.stream_index];  
/* copy packet */
//轉換PTS/DTS(Convert PTS/DTS)
        pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));  
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));  
        pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);  
        pkt.pos = -1;  
//Print to Screen
if(pkt.stream_index==videoindex){  
            printf("Send %8d video frames to output URL\n",frame_index);  
            frame_index++;  
        }  
//ret = av_write_frame(ofmt_ctx, &pkt);
        ret = av_interleaved_write_frame(ofmt_ctx, &pkt);  

if (ret < 0) {  
            printf( "Error muxing packet\n");  
break;  
        }  

        av_free_packet(&pkt);  

    }  
//寫文件尾(Write file trailer)
    av_write_trailer(ofmt_ctx);  
end:  
    avformat_close_input(&ifmt_ctx);  
/* close output */
if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))  
        avio_close(ofmt_ctx->pb);  
    avformat_free_context(ofmt_ctx);  
if (ret < 0 && ret != AVERROR_EOF) {  
        printf( "Error occurred.\n");  
return -1;  
    }  
return 0;  
}

結果

程序開始運行后。截圖如下所示。

可以通過網頁播放器播放推送的直播流。

例如下圖所示,使用Flash Media Server 的Samples文件夾下的videoPlayer播放直播流的截圖如下圖所示。(直播地址:rtmp://localhost/publishlive/livestream)

此外,也可以通過FFplay這樣的客戶端播放直播流。

更新-1.1 (2015.2.13)=========================================

這次考慮到了跨平台的要求,調整了源代碼。經過這次調整之后,源代碼可以在以下平台編譯通過:

VC++:打開sln文件即可編譯,無需配置。

cl.exe:打開compile_cl.bat即可命令行下使用cl.exe進行編譯,注意可能需要按照VC的安裝路徑調整腳本里面的參數。編譯命令如下。

::VS2010 Environment  
call "D:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"  
::include  
@set INCLUDE=include;%INCLUDE%;  
::lib  
@set LIB=lib;%LIB%;  
::compile and link  
cl simplest_ffmpeg_streamer.cpp /link avcodec.lib avformat.lib avutil.lib ^  
avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib /OPT:NOREF

MinGW:MinGW命令行下運行compile_mingw.sh即可使用MinGW的g++進行編譯。編譯命令如下。

g++ simplest_ffmpeg_streamer.cpp -g -o simplest_ffmpeg_streamer.exe \  
-I /usr/local/include -L /usr/local/lib -lavformat -lavcodec -lavutil

GCC:Linux或者MacOS命令行下運行compile_gcc.sh即可使用GCC進行編譯。編譯命令如下。

gcc simplest_ffmpeg_streamer.cpp -g -o simplest_ffmpeg_streamer.out \  
-I /usr/local/include -L /usr/local/lib -lavformat -lavcodec -lavutil

PS:相關的編譯命令已經保存到了工程文件夾中

最簡單的基於librtmp的示例:接收(RTMP保存為FLV)

本文記錄一個基於libRTMP的接收流媒體的程序:Simplest libRTMP Receive。該程序可以將RTMP流保存成本地FLV文件。實際上本文記錄的程序就是一個“精簡”過的RTMPDump。RTMPDump功能比較多,因而其代碼比較復雜導致很多初學者不知從何下手。而本文記錄的這個程序只保留了RTMPDump中最核心的函數,更加方便新手入門學習 libRTMP。

流程圖

使用librtmp接收RTMP流的函數執行流程圖如下圖所示。

流程圖中關鍵函數的作用如下所列:
InitSockets():初始化Socket
RTMP_Alloc():為結構體“RTMP”分配內存。
RTMP_Init():初始化結構體“RTMP”中的成員變量。
RTMP_SetupURL():設置輸入的RTMP連接的URL。
RTMP_Connect():建立RTMP連接,創建一個RTMP協議規范中的NetConnection。
RTMP_ConnectStream():創建一個RTMP協議規范中的NetStream。
RTMP_Read():從服務器讀取數據。
RTMP_Close():關閉RTMP連接。
RTMP_Free():釋放結構體“RTMP”。
CleanupSockets():關閉Socket。
其中NetStream和NetConnection是RTMP協議規范中的兩個邏輯結構。NetStream建立在NetConnection之上。一個NetConnection可以包含多個NetStream。它們之間的關系如下圖所示。

源代碼

/**
 * Simplest Librtmp Receive
 *
 * 雷霄驊,張暉
 * leixiaohua1020@126.com
 * zhanghuicuc@gmail.com
 * 中國傳媒大學/數字電視技術
 * Communication University of China / Digital TV Technology
 * http://blog.csdn.net/leixiaohua1020
 *
 * 本程序用於接收RTMP流媒體並在本地保存成FLV格式的文件。
 * This program can receive rtmp live stream and save it as local flv file.
 */
#include <stdio.h>
#include "librtmp/rtmp_sys.h"
#include "librtmp/log.h"

int InitSockets()  
{  
WORD version;  
    WSADATA wsaData;  
    version = MAKEWORD(1, 1);  
return (WSAStartup(version, &wsaData) == 0);  
}  

void CleanupSockets()  
{  
    WSACleanup();  
}  

int main(int argc, char* argv[])  
{  
    InitSockets();  

double duration=-1;  
int nRead;  
//is live stream ?
bool bLiveStream=true;                


int bufsize=1024*1024*10;             
char *buf=(char*)malloc(bufsize);  
    memset(buf,0,bufsize);  
long countbufsize=0;  

FILE *fp=fopen("receive.flv","wb");  
if (!fp){  
        RTMP_LogPrintf("Open File Error.\n");  
        CleanupSockets();  
return -1;  
    }  

/* set log level */
//RTMP_LogLevel loglvl=RTMP_LOGDEBUG;
//RTMP_LogSetLevel(loglvl);

    RTMP *rtmp=RTMP_Alloc();  
    RTMP_Init(rtmp);  
//set connection timeout,default 30s
    rtmp->Link.timeout=10;     
// HKS's live URL
if(!RTMP_SetupURL(rtmp,"rtmp://live.hkstv.hk.lxdns.com/live/hks"))  
    {  
        RTMP_Log(RTMP_LOGERROR,"SetupURL Err\n");  
        RTMP_Free(rtmp);  
        CleanupSockets();  
return -1;  
    }  
if (bLiveStream){  
        rtmp->Link.lFlags|=RTMP_LF_LIVE;  
    }  

//1hour
    RTMP_SetBufferMS(rtmp, 3600*1000);        

if(!RTMP_Connect(rtmp,NULL)){  
        RTMP_Log(RTMP_LOGERROR,"Connect Err\n");  
        RTMP_Free(rtmp);  
        CleanupSockets();  
return -1;  
    }  

if(!RTMP_ConnectStream(rtmp,0)){  
        RTMP_Log(RTMP_LOGERROR,"ConnectStream Err\n");  
        RTMP_Close(rtmp);  
        RTMP_Free(rtmp);  
        CleanupSockets();  
return -1;  
    }  

while(nRead=RTMP_Read(rtmp,buf,bufsize)){  
        fwrite(buf,1,nRead,fp);  

        countbufsize+=nRead;  
        RTMP_LogPrintf("Receive: %5dByte, Total: %5.2fkB\n",nRead,countbufsize*1.0/1024);  
    }  

if(fp)  
        fclose(fp);  

if(buf){  
        free(buf);  
    }  

if(rtmp){  
        RTMP_Close(rtmp);  
        RTMP_Free(rtmp);  
        CleanupSockets();  
        rtmp=NULL;  
    }     
return 0;  
}

運行結果

程序運行后,會將URL為“rtmp://live.hkstv.hk.lxdns.com/live/hks”的直播流(實際上是香港衛視)在本地保存為“receive.flv”。保存后的文件使用播放器就可以觀看。

最簡單的基於librtmp的示例:發布(FLV通過RTMP發布)

本文記錄一個基於libRTMP的發布流媒體的程序:Simplest libRTMP Send FLV。該程序可以將本地FLV文件發布到RTMP流媒體服務器。是最簡單的基於libRTMP的流媒體發布示例。

流程圖


使用librtmp發布RTMP流的可以使用兩種API:RTMP_SendPacket()和RTMP_Write()。使用 RTMP_SendPacket()發布流的時候的函數執行流程圖如下圖所示。使用RTMP_Write()發布流的時候的函數執行流程圖相差不大。

流程圖中關鍵函數的作用如下所列:

InitSockets():初始化Socket
RTMP_Alloc():為結構體“RTMP”分配內存。
RTMP_Init():初始化結構體“RTMP”中的成員變量。
RTMP_SetupURL():設置輸入的RTMP連接的URL。
RTMP_EnableWrite():發布流的時候必須要使用。如果不使用則代表接收流。
RTMP_Connect():建立RTMP連接,創建一個RTMP協議規范中的NetConnection。
RTMP_ConnectStream():創建一個RTMP協議規范中的NetStream。
Delay:發布流過程中的延時,保證按正常播放速度發送數據。
RTMP_SendPacket():發送一個RTMP數據RTMPPacket。
RTMP_Close():關閉RTMP連接。
RTMP_Free():釋放結構體“RTMP”。
CleanupSockets():關閉Socket。

源代碼

源代碼中包含了使用兩種API函數RTMP_SendPacket()和RTMP_Write()發布流媒體的源代碼,如下所示。

/**
 * Simplest Librtmp Send FLV
 *
 * 雷霄驊,張暉
 * leixiaohua1020@126.com
 * zhanghuicuc@gmail.com
 * 中國傳媒大學/數字電視技術
 * Communication University of China / Digital TV Technology
 * http://blog.csdn.net/leixiaohua1020
 *
 * 本程序用於將FLV格式的視音頻文件使用RTMP推送至RTMP流媒體服務器。
 * This program can send local flv file to net server as a rtmp live stream.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#ifndef WIN32
#include <unistd.h>
#endif


#include "librtmp/rtmp_sys.h"
#include "librtmp/log.h"

#define HTON16(x)  ((x>>8&0xff)|(x<<8&0xff00))
#define HTON24(x)  ((x>>16&0xff)|(x<<16&0xff0000)|(x&0xff00))
#define HTON32(x)  ((x>>24&0xff)|(x>>8&0xff00)|\
         (x<<8&0xff0000)|(x<<24&0xff000000))  
#define HTONTIME(x) ((x>>16&0xff)|(x<<16&0xff0000)|(x&0xff00)|(x&0xff000000))

/*read 1 byte*/
int ReadU8(uint32_t *u8,FILE*fp){  
if(fread(u8,1,1,fp)!=1)  
return 0;  
return 1;  
}  
/*read 2 byte*/
int ReadU16(uint32_t *u16,FILE*fp){  
if(fread(u16,2,1,fp)!=1)  
return 0;  
         *u16=HTON16(*u16);  
return 1;  
}  
/*read 3 byte*/
int ReadU24(uint32_t *u24,FILE*fp){  
if(fread(u24,3,1,fp)!=1)  
return 0;  
         *u24=HTON24(*u24);  
return 1;  
}  
/*read 4 byte*/
int ReadU32(uint32_t *u32,FILE*fp){  
if(fread(u32,4,1,fp)!=1)  
return 0;  
         *u32=HTON32(*u32);  
return 1;  
}  
/*read 1 byte,and loopback 1 byte at once*/
int PeekU8(uint32_t *u8,FILE*fp){  
if(fread(u8,1,1,fp)!=1)  
return 0;  
         fseek(fp,-1,SEEK_CUR);  
return 1;  
}  
/*read 4 byte and convert to time format*/
int ReadTime(uint32_t *utime,FILE*fp){  
if(fread(utime,4,1,fp)!=1)  
return 0;  
         *utime=HTONTIME(*utime);  
return 1;  
}  

int InitSockets()  
{  
WORD version;  
         WSADATA wsaData;  
         version=MAKEWORD(2,2);  
return (WSAStartup(version, &wsaData) == 0);  
}  

void CleanupSockets()  
{  
         WSACleanup();  
}  

//Publish using RTMP_SendPacket()
int publish_using_packet(){  
         RTMP *rtmp=NULL;                             
         RTMPPacket *packet=NULL;  
         uint32_t start_time=0;  
         uint32_t now_time=0;  
//the timestamp of the previous frame
long pre_frame_time=0;  
long lasttime=0;  
int bNextIsKey=1;  
         uint32_t preTagsize=0;  

//packet attributes
         uint32_t type=0;                          
         uint32_t datalength=0;             
         uint32_t timestamp=0;             
         uint32_t streamid=0;                          

FILE*fp=NULL;  
         fp=fopen("cuc_ieschool.flv","rb");  
if (!fp){  
                   RTMP_LogPrintf("Open File Error.\n");  
                   CleanupSockets();  
return -1;  
         }  

/* set log level */
//RTMP_LogLevel loglvl=RTMP_LOGDEBUG;
//RTMP_LogSetLevel(loglvl);

if (!InitSockets()){  
                   RTMP_LogPrintf("Init Socket Err\n");  
return -1;  
         }  

         rtmp=RTMP_Alloc();  
         RTMP_Init(rtmp);  
//set connection timeout,default 30s
         rtmp->Link.timeout=5;                        
if(!RTMP_SetupURL(rtmp,"rtmp://localhost/publishlive/livestream"))  
         {  
                   RTMP_Log(RTMP_LOGERROR,"SetupURL Err\n");  
                   RTMP_Free(rtmp);  
                   CleanupSockets();  
return -1;  
         }  

//if unable,the AMF command would be 'play' instead of 'publish'
         RTMP_EnableWrite(rtmp);       

if (!RTMP_Connect(rtmp,NULL)){  
                   RTMP_Log(RTMP_LOGERROR,"Connect Err\n");  
                   RTMP_Free(rtmp);  
                   CleanupSockets();  
return -1;  
         }  

if (!RTMP_ConnectStream(rtmp,0)){  
                   RTMP_Log(RTMP_LOGERROR,"ConnectStream Err\n");  
                   RTMP_Close(rtmp);  
                   RTMP_Free(rtmp);  
                   CleanupSockets();  
return -1;  
         }  

         packet=(RTMPPacket*)malloc(sizeof(RTMPPacket));  
         RTMPPacket_Alloc(packet,1024*64);  
         RTMPPacket_Reset(packet);  

         packet->m_hasAbsTimestamp = 0;          
         packet->m_nChannel = 0x04;  
         packet->m_nInfoField2 = rtmp->m_stream_id;  

         RTMP_LogPrintf("Start to send data ...\n");  

//jump over FLV Header
         fseek(fp,9,SEEK_SET);       
//jump over previousTagSizen
         fseek(fp,4,SEEK_CUR);     
         start_time=RTMP_GetTime();  
while(1)  
         {  
if((((now_time=RTMP_GetTime())-start_time)  
                              <(pre_frame_time)) && bNextIsKey){          
//wait for 1 sec if the send process is too fast
//this mechanism is not very good,need some improvement
if(pre_frame_time>lasttime){  
                                     RTMP_LogPrintf("TimeStamp:%8lu ms\n",pre_frame_time);  
                                     lasttime=pre_frame_time;  
                            }  
                            Sleep(1000);  
continue;  
                   }  

//not quite the same as FLV spec
if(!ReadU8(&type,fp))       
break;  
if(!ReadU24(&datalength,fp))  
break;  
if(!ReadTime(×tamp,fp))  
break;  
if(!ReadU24(&streamid,fp))  
break;  

if (type!=0x08&&type!=0x09){  
//jump over non_audio and non_video frame,
//jump over next previousTagSizen at the same time
                            fseek(fp,datalength+4,SEEK_CUR);  
continue;  
                   }  

if(fread(packet->m_body,1,datalength,fp)!=datalength)  
break;  

                   packet->m_headerType = RTMP_PACKET_SIZE_LARGE;  
                   packet->m_nTimeStamp = timestamp;  
                   packet->m_packetType = type;  
                   packet->m_nBodySize  = datalength;  
                   pre_frame_time=timestamp;  

if (!RTMP_IsConnected(rtmp)){  
                            RTMP_Log(RTMP_LOGERROR,"rtmp is not connect\n");  
break;  
                   }  
if (!RTMP_SendPacket(rtmp,packet,0)){  
                            RTMP_Log(RTMP_LOGERROR,"Send Error\n");  
break;  
                   }  

if(!ReadU32(&preTagsize,fp))  
break;  

if(!PeekU8(&type,fp))  
break;  
if(type==0x09){  
if(fseek(fp,11,SEEK_CUR)!=0)  
break;  
if(!PeekU8(&type,fp)){  
break;  
                            }  
if(type==0x17)  
                                     bNextIsKey=1;  
else
                                     bNextIsKey=0;  

                            fseek(fp,-11,SEEK_CUR);  
                   }  
         }                 

         RTMP_LogPrintf("\nSend Data Over\n");  

if(fp)  
                   fclose(fp);  

if (rtmp!=NULL){  
                   RTMP_Close(rtmp);          
                   RTMP_Free(rtmp);   
                   rtmp=NULL;  
         }  
if (packet!=NULL){  
                   RTMPPacket_Free(packet);      
                   free(packet);  
                   packet=NULL;  
         }  

         CleanupSockets();  
return 0;  
}  

//Publish using RTMP_Write()
int publish_using_write(){  
         uint32_t start_time=0;  
         uint32_t now_time=0;  
         uint32_t pre_frame_time=0;  
         uint32_t lasttime=0;  
int bNextIsKey=0;  
char* pFileBuf=NULL;  

//read from tag header
         uint32_t type=0;  
         uint32_t datalength=0;  
         uint32_t timestamp=0;  

         RTMP *rtmp=NULL;                             

FILE*fp=NULL;  
         fp=fopen("cuc_ieschool.flv","rb");  
if (!fp){  
                   RTMP_LogPrintf("Open File Error.\n");  
                   CleanupSockets();  
return -1;  
         }  

/* set log level */
//RTMP_LogLevel loglvl=RTMP_LOGDEBUG;
//RTMP_LogSetLevel(loglvl);

if (!InitSockets()){  
                  RTMP_LogPrintf("Init Socket Err\n");  
return -1;  
         }  

         rtmp=RTMP_Alloc();  
         RTMP_Init(rtmp);  
//set connection timeout,default 30s
         rtmp->Link.timeout=5;                        
if(!RTMP_SetupURL(rtmp,"rtmp://localhost/publishlive/livestream"))  
         {  
                   RTMP_Log(RTMP_LOGERROR,"SetupURL Err\n");  
                   RTMP_Free(rtmp);  
                   CleanupSockets();  
return -1;  
         }  

         RTMP_EnableWrite(rtmp);  
//1hour
         RTMP_SetBufferMS(rtmp, 3600*1000);           
if (!RTMP_Connect(rtmp,NULL)){  
                   RTMP_Log(RTMP_LOGERROR,"Connect Err\n");  
                   RTMP_Free(rtmp);  
                   CleanupSockets();  
return -1;  
         }  

if (!RTMP_ConnectStream(rtmp,0)){  
                   RTMP_Log(RTMP_LOGERROR,"ConnectStream Err\n");  
                   RTMP_Close(rtmp);  
                   RTMP_Free(rtmp);  
                   CleanupSockets();  
return -1;  
         }  

         printf("Start to send data ...\n");  

//jump over FLV Header
         fseek(fp,9,SEEK_SET);       
//jump over previousTagSizen
         fseek(fp,4,SEEK_CUR);     
         start_time=RTMP_GetTime();  
while(1)  
         {  
if((((now_time=RTMP_GetTime())-start_time)  
                              <(pre_frame_time)) && bNextIsKey){          
//wait for 1 sec if the send process is too fast
//this mechanism is not very good,need some improvement
if(pre_frame_time>lasttime){  
                                     RTMP_LogPrintf("TimeStamp:%8lu ms\n",pre_frame_time);  
                                     lasttime=pre_frame_time;  
                            }  
                            Sleep(1000);  
continue;  
                   }  

//jump over type
                   fseek(fp,1,SEEK_CUR);     
if(!ReadU24(&datalength,fp))  
break;  
if(!ReadTime(×tamp,fp))  
break;  
//jump back
                   fseek(fp,-8,SEEK_CUR);    

                   pFileBuf=(char*)malloc(11+datalength+4);  
                   memset(pFileBuf,0,11+datalength+4);  
if(fread(pFileBuf,1,11+datalength+4,fp)!=(11+datalength+4))  
break;  

                   pre_frame_time=timestamp;  

if (!RTMP_IsConnected(rtmp)){  
                            RTMP_Log(RTMP_LOGERROR,"rtmp is not connect\n");  
break;  
                   }  
if (!RTMP_Write(rtmp,pFileBuf,11+datalength+4)){  
                            RTMP_Log(RTMP_LOGERROR,"Rtmp Write Error\n");  
break;  
                   }  

                   free(pFileBuf);  
                   pFileBuf=NULL;  

if(!PeekU8(&type,fp))  
break;  
if(type==0x09){  
if(fseek(fp,11,SEEK_CUR)!=0)  
break;  
if(!PeekU8(&type,fp)){  
break;  
                            }  
if(type==0x17)  
                                     bNextIsKey=1;  
else
                                     bNextIsKey=0;  
                            fseek(fp,-11,SEEK_CUR);  
                   }  
         }  

         RTMP_LogPrintf("\nSend Data Over\n");  

if(fp)  
                   fclose(fp);  

if (rtmp!=NULL){  
                   RTMP_Close(rtmp);          
                   RTMP_Free(rtmp);  
                   rtmp=NULL;  
         }  

if(pFileBuf){  
                   free(pFileBuf);  
                   pFileBuf=NULL;  
         }  

         CleanupSockets();  
return 0;  
}  

int main(int argc, char* argv[]){  
//2 Methods:
         publish_using_packet();  
//publish_using_write();
return 0;  
}

運行結果

程序運行后,會將“cuc_ieschool.flv”文件以直播流的形式發布到“rtmp://localhost/publishlive/livestream”的URL。修改文件名稱和RTMP的URL可以實現將任意flv文件發布到任意RTMP的URL。

最簡單的基於librtmp的示例:發布H.264(H.264通過RTMP發布)

本文記錄一個基於libRTMP的發布H.264碼流的程序。該程序可以將H.264數據發布到RTMP流媒體服務器。目前這個例子還不是很穩定,下一步還有待修改。

本程序使用回調函數作為輸入,通過自定義的回調函數,可以發送本地的文件或者內存中的數據。

函數調用結構圖

本程序的函數調用結構圖如下所示。

整個程序包含3個接口函數:
RTMP264_Connect():建立RTMP連接。
RTMP264_Send():發送數據。
RTMP264_Close():關閉RTMP連接。
按照順序調用上述3個接口函數就可以完成H.264碼流的發送。
結構圖中關鍵函數的作用如下所列。
RTMP264_Connect()中包含以下函數:

InitSockets():初始化Socket
RTMP_Alloc():為結構體“RTMP”分配內存。
RTMP_Init():初始化結構體“RTMP”中的成員變量。
RTMP_SetupURL():設置輸入的RTMP連接的URL。
RTMP_EnableWrite():發布流的時候必須要使用。如果不使用則代表接收流。
RTMP_Connect():建立RTMP連接,創建一個RTMP協議規范中的NetConnection。
RTMP_ConnectStream():創建一個RTMP協議規范中的NetStream。


RTMP264_Send()中包含以下函數:

ReadFirstNaluFromBuf():從內存中讀取出第一個NAL單元。
ReadOneNaluFromBuf():從內存中讀取出一個NAL單元。
h264_decode_sps():解碼SPS,獲取視頻的寬,高,幀率信息。
SendH264Packet():發送一個NAL單元。


SendH264Packet()中包含以下函數:

SendVideoSpsPps():如果是關鍵幀,則在發送該幀之前先發送SPS和PPS。
SendPacket():組裝一個RTMPPacket,調用RTMP_SendPacket()發送出去。
RTMP_SendPacket():發送一個RTMP數據RTMPPacket。


RTMP264_Close()中包含以下函數:

RTMP_Close():關閉RTMP連接。
RTMP_Free():釋放結構體“RTMP”。
CleanupSockets():關閉Socket。

源代碼

程序提供的3個接口函數的使用方法如下。可以看出接口比較簡單。

/**
 * Simplest Librtmp Send 264
 *
 * 雷霄驊,張暉
 * leixiaohua1020@126.com
 * zhanghuicuc@gmail.com
 * 中國傳媒大學/數字電視技術
 * Communication University of China / Digital TV Technology
 * http://blog.csdn.net/leixiaohua1020
 *
 * 本程序用於將內存中的H.264數據推送至RTMP流媒體服務器。
 * This program can send local h264 stream to net server as rtmp live stream.
 */

#include <stdio.h>
#include "librtmp_send264.h"



FILE *fp_send1;  

//讀文件的回調函數
//we use this callback function to read data from buffer
int read_buffer1(unsigned char *buf, int buf_size ){  
if(!feof(fp_send1)){  
int true_size=fread(buf,1,buf_size,fp_send1);  
return true_size;  
    }else{  
return -1;  
    }  
}  

int main(int argc, char* argv[])  
{  
    fp_send1 = fopen("cuc_ieschool.h264", "rb");  

//初始化並連接到服務器
    RTMP264_Connect("rtmp://localhost/publishlive/livestream");  

//發送
    RTMP264_Send(read_buffer1);  

//斷開連接並釋放相關資源
    RTMP264_Close();  

return 0;  
}

接口函數內部的代碼比較多,不再詳細記錄。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM