6/12/2011

使用live555 streaming media建立RTSP串流伺服器

Live555 Streaming Media是一套優秀的開放程式碼函示庫,擁有完整的RTSP/RTP實作,除了支援RTP over UDP外,尚支援RTP over RTSP以及RTP/RTSP over HTTP,可用於傳輸多種主流的影音壓縮格式如:H.264、MPEG4、MP3....等。知名的播放軟體VLC的串流功能就是基於此函式庫開發。
利用它我們只要短短幾行程式碼即可建立自己的串流伺服器。

範例程式碼如下:

#include <liveMedia.hh>
#include <BasicUsageEnvironment.hh>

static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
                           char const* streamName, char const* inputFileName);


int main(int argc, char** argv)
{
    UsageEnvironment* env;

    TaskScheduler* scheduler = BasicTaskScheduler::createNew();
    env = BasicUsageEnvironment::createNew(*scheduler);

    // 1. Create the RTSP server:
    RTSPServer* rtspServer = RTSPServer::createNew(*env, 8554, NULL);
    if (rtspServer == NULL) {
        *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n";
        exit(1);
    }

    // 2. Add a H.264 video elementary stream to RTSP server
    {
        char const* streamName = "h264";
        char const* inputFileName = "test.h264";

        ServerMediaSession* sms = ServerMediaSession::createNew(*env,
                                                                streamName,
                                                                streamName,
                                                                "H.264 video");
        sms->addSubsession(H264VideoFileServerMediaSubsession::createNew(*env,
                                                                         inputFileName,
                                                                         False));
        rtspServer->addServerMediaSession(sms);

        announceStream(rtspServer, sms, streamName, inputFileName);
    }

    // 3. Kick-off the server
    env->taskScheduler().doEventLoop(); /* Never return */

    /* Unreachable */

    return 0;
}

static void  announceStream(RTSPServer* rtspServer, ServerMediaSession* sms,
                            char const* streamName, char const* inputFileName)
{
    char* url = rtspServer->rtspURL(sms);
    UsageEnvironment& env = rtspServer->envir();

    env << "\n\"" << streamName << "\" stream, from the file \""
        << inputFileName << "\"\n";
    env << "Play this stream using the URL \"" << url << "\"\n";

    delete[] url;
}
由範例可知,live555的使用方式十分簡單易懂,函式庫編譯連結後的執行檔也非常小巧,比較遺憾的是因為它目前沒有提供與外部編碼器(encoder)連結的功能以致無法擷取即時影音做即時串流,僅能播放預錄的影音檔,這部份的功能有賴函式庫使用者者自行撰寫。這是與GStreamer提供的RTSP server相比較為美中不足的地方,但是對一般使用者來說應該綽綽有餘了。

No comments:

Post a Comment