1. 程式人生 > >Dump Rtmp Stream To FLV File (從Rtmp流儲存為FLV檔案)

Dump Rtmp Stream To FLV File (從Rtmp流儲存為FLV檔案)

 

 

一、準備工作

  搭建本地rtmp服務:

  https://www.cnblogs.com/doudouyoutang/p/6602430.html

  獲取使用到的庫,openssl 和 librtmp

  參考:

  https://www.jianshu.com/p/b38656443e71
  https://github.com/x2on/OpenSSL-for-iPhone

  也可以從我的工程中直接拿

 

二、程式碼編寫

  利用librtmp中的RTMP_Read函式,直接讀取到的就是FLV流,然後寫入檔案,就可以正常播放了。

  

void RtmpStreamDumper::startDump()
{
    int readBytes = 0;
    bool bLiveStream = true;
    int bufsize = 1024*1024*10;
    long countbufsize = 0;
    char *buf  = (char*)calloc(sizeof(char), bufsize);
    char *path = (char*)calloc(sizeof(char), this->rtmp_rsource_url.size() + 1);
    strcpy(path, this->rtmp_rsource_url.c_str());
    
    RTMP_LogPrintf("Start Dump To %s", this->dump_flv_path.c_str());

    
    RTMP *rtmp = RTMP_Alloc();
    RTMP_Init(rtmp);
    rtmp->Link.timeout=10;
    
    if(!RTMP_SetupURL(rtmp, path))
    {
        RTMP_Log(RTMP_LOGERROR,"SetupURL Err\n");
        RTMP_Free(rtmp);
        return;
    }
    
    if (bLiveStream){
        rtmp->Link.lFlags|=RTMP_LF_LIVE;
    }

    RTMP_SetBufferMS(rtmp, 3600*1000);

    if(!RTMP_Connect(rtmp,NULL)){
        RTMP_Log(RTMP_LOGERROR,"Connect Err\n");
        RTMP_Free(rtmp);
        return ;
    }
    
    if(!RTMP_ConnectStream(rtmp,0)){
        RTMP_Log(RTMP_LOGERROR,"ConnectStream Err\n");
        RTMP_Close(rtmp);
        RTMP_Free(rtmp);
        return ;
    }
    
    while((readBytes = RTMP_Read(rtmp,buf,bufsize))){
        this->dumpBytesToFlv((const unsigned char *)buf, readBytes);
        countbufsize += readBytes;
        RTMP_LogPrintf("Receive: %5dByte, Total: %5.2fkB\n",readBytes,countbufsize*1.0/1024);
    }

    if(buf){
        free(buf);
    }
    
    if(rtmp){
        RTMP_Close(rtmp);
        RTMP_Free(rtmp);
        rtmp=NULL;
    }

}

 

三、執行效果

  

 

四、已經封裝為可執行檔案

  

    std::cout<<"use example :RtmpDumper [rtmp_live_url] [flv_save_path(default to excute folder)]"<<std::endl;
    std::string url((argc > 1)?argv[1]:"");
    std::string path((argc > 2)?argv[2]:"");
    RtmpStreamDumper *dp = new RtmpStreamDumper(url, path);
    dp->startDump();
    return 0;

  

使用方法

RtmpDumper rtmp://localhost:1935/myapp/room

  

五、程式碼

https://github.com/liqiushui/RtmpDumpAsFlv.git