Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1243401
  • 博文数量: 76
  • 博客积分: 1959
  • 博客等级: 上尉
  • 技术积分: 2689
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-19 12:07
个人简介

樽中酒不空

文章分类

全部博文(76)

文章存档

2020年(4)

2019年(1)

2017年(2)

2016年(2)

2015年(7)

2014年(11)

2013年(13)

2012年(18)

2011年(2)

2010年(16)

分类: C/C++

2013-12-11 09:58:26


一 背景:
用户需要通过flash或手机看监控视频,而目前绝大多数摄像机都是RTSP协议,所以需要做一个中转。
参考资料:
http://blog.csdn.net/firehood_/article/details/8813587
http://blog.csdn.net/firehood_/article/details/8783589
这两篇文章详细说明了mp4v2保存文件和把264文件通过RTMP直播,对这两方面感兴趣的可以直接看这两文章。本文只是把这两文章中读264转存转发改成读rtsp转存转发,多了一点live555的内容,其他基本一样,只稍调整了一点点接口部分。

二 流程:
1 live555从摄像机读音视频,为了便于讲解这里只讨论视频。
2 mp4v2保存成.mp4
3 librtmp上传视频流到nginx
4 web用户通过flash观看


三 技术讲解:
1  live555读RTSP视频,可以参考playCommon.cpp或testRTSPClient.cpp,前者功能全,后者简洁一些,不过支持多路流同时访问。如果自己写RTSP Client,环境不是很复杂,可以参考这份代码。
RTSP接收到H264视频后,不管是读写文件还是发送流,主要的问题就在SPS和PPS上面。这两个名字这里不做解释,自行google,这里只讲怎么取到这两个参数。
读live的源码,注意 playCommon.cpp中有一段:


else if (strcmp(subsession->mediumName(), "video") == 0 &&
   (strcmp(subsession->codecName(), "H264") == 0)) {
 // For H.264 video stream, we use a special sink that adds 'start codes', and (at the start) the SPS and PPS NAL units:
 fileSink = H264VideoFileSink::createNew(*env, outFileName,
 subsession->fmtp_spropparametersets(),
 fileSinkBufferSize, oneFilePerFrame);



这里调用H264VideoFileSink保存264文件,播放正常,所以我们需要研究H264VideoFileSink的源码。
只需注意H264VideoFileSink.cpp里面的afterGettingFrame函数,如下:
if (!fHaveWrittenFirstFrame) {
    // If we have PPS/SPS NAL units encoded in a "sprop parameter string", prepend these to the file:
    unsigned numSPropRecords;
    SPropRecord* sPropRecords = parseSPropParameterSets(fSPropParameterSetsStr, numSPropRecords);
    for (unsigned i = 0; i < numSPropRecords; ++i) {
      addData(start_code, 4, presentationTime);
      addData(sPropRecords[i].sPropBytes, sPropRecords[i].sPropLength, presentationTime);
    }
    delete[] sPropRecords;
    fHaveWrittenFirstFrame = True; // for next time
  }


  // Write the input data to the file, with the start code in front:
  addData(start_code, 4, presentationTime);
  
  注释的很明显了,这里再简单说一下:
  for (unsigned i = 0; i < numSPropRecords; ++i) {
      addData(start_code, 4, presentationTime);
      addData(sPropRecords[i].sPropBytes, sPropRecords[i].sPropLength, presentationTime);
    }
    这里的sPropRecords是从外面传进来的参数:subsession->fmtp_spropparametersets(),从名字上看就是sps和pps合在一起的内容。
    debug就可以发现,numSPropRecords==2,for循环两次,第一次是sps,第二次就是pps了。把这两个记住,保存264和发送RTMP时写在相应的位置,所有的工作基本就完成了。
    
2 mp4v2的api非常简单,没什么好说,唯一注意一点就是先从sps中读取视频的宽和高。可以参考后面代码。
3 librtmp,也很简单,只要注意先发关sps和pps
4 直播服务器用nginx+nginx_rtmp_module, google一下,文档很多。


四 运行环境: CentOS6.4及Ubuntu 12下运行正常。windows也可以,多平台时需要类型统一,比如UINT,BYTE,uint32_t, uint8_t ,稍稍改动一下就好。


五 rtsp部分简单代码演示:
1 把testRTSPClient.cpp代码复制出来,放在自己的代码里,RTSP接收功能就OK了。只改动一点点,以下是改动部分:


void continueAfterSETUP(RTSPClient* rtspClient, int resultCode, char* resultString) {
这里,增加 :
//暂时只处理视频
if (strcmp(scs.subsession->mediumName(), "video") == 0 &&
(strcmp(scs.subsession->codecName(), "H264") == 0)) 
{
DummySink* pVideoSink = DummySink::createNew(env, *scs.subsession, rtspClient->url());
   pVideoSink->sps = scs.subsession->fmtp_spropparametersets();


scs.subsession->sink = pVideoSink;
}
//这部分代码参考playComm.cpp, sps是string变量,为了演示方便,直接声明成public,这里把sps pps内容当成字符串传到DummySink。

//1280*760*3
#define DUMMY_SINK_RECEIVE_BUFFER_SIZE 2764800
uint8_t* buff = NULL;
struct timeval start_time;
unsigned numSPropRecords;
SPropRecord* sPropRecords = NULL;


DummySink::DummySink(UsageEnvironment& env, MediaSubsession& subsession, char const* streamId)
  : MediaSink(env),
    fSubsession(subsession) {
  fStreamId = strDup(streamId);
  fReceiveBuffer = new u_int8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE];


   buff = new u_int8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE];
   gettimeofday(&start_time, NULL);
}
DummySink::~DummySink() {
  delete[] fReceiveBuffer;
  delete[] fStreamId;
  delete []buff;
}


void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes,
 struct timeval presentationTime, unsigned /*durationInMicroseconds*/) 
{


  struct timeval cur;
  gettimeofday(&cur, NULL);


  static unsigned char const start_code[4] = {0x00, 0x00, 0x00, 0x01};
  if (sPropRecords == NULL)
  {
  //这几行代码出自H264VideoFileSink.cpp,先保存成sps.264是考虑保存文件和直播的时间不一定在什么时候开始,先在本地缓存一下。
//当然保存在内存里也可以。
 FILE* pfSPS = fopen("sps.264", "wb");
 sPropRecords = parseSPropParameterSets(sps.c_str(), numSPropRecords);
 //这里的sps是个string, 就是前面continueAfterSETUP代码里的提到的。
 for (unsigned i = 0; i < numSPropRecords; ++i) 
 {
 if (pfSPS)
 {
 fwrite(start_code, 1, 4, pfSPS );
 fwrite(sPropRecords[i].sPropBytes, 1, sPropRecords[i].sPropLength, pfSPS);
 }
 }
 fclose(pfSPS);
 gettimeofday(&start_time, NULL);
  }
  int timestamp = (cur.tv_sec-start_time.tv_sec)*1000 + (cur.tv_usec - start_time.tv_usec)/1000;


  memset(buff, '0', DUMMY_SINK_RECEIVE_BUFFER_SIZE); 
  memcpy(buff, start_code, 4);
  memcpy(buff+4, fReceiveBuffer, frameSize);
  
  callback(buff, frameSize+4, timestamp);//这里自行实现一个回调函数,把视频数据回调出去。
  
  continuePlaying();
}


六:mp4v2保存成.mp4,可以参考这个文章:http://blog.csdn.net/firehood_/article/details/8813587
不过这里面有几个参数没说明怎么得到,可以自己稍加处理,比如从sps里读出宽和高,参考:http://blog.csdn.net/firehood_/article/details/8783589,
同一作者写的,如果认真看完他的文档,我这里写的都不需要看了。
  
bool h264_decode_sps(BYTE * buf,unsigned int nLen,int &width,int &height)  
{  
    UINT StartBit=0;   
    int forbidden_zero_bit=u(1,buf,StartBit);  
    int nal_ref_idc=u(2,buf,StartBit);  
    int nal_unit_type=u(5,buf,StartBit);  
    if(nal_unit_type==7)  
    {  
        int profile_idc=u(8,buf,StartBit);  
        int constraint_set0_flag=u(1,buf,StartBit);//(buf[1] & 0x80)>>7;  
        int constraint_set1_flag=u(1,buf,StartBit);//(buf[1] & 0x40)>>6;  
        int constraint_set2_flag=u(1,buf,StartBit);//(buf[1] & 0x20)>>5;  
        int constraint_set3_flag=u(1,buf,StartBit);//(buf[1] & 0x10)>>4;  
        int reserved_zero_4bits=u(4,buf,StartBit);  
        int level_idc=u(8,buf,StartBit);  
  
        int seq_parameter_set_id=Ue(buf,nLen,StartBit);  
  
        if( profile_idc == 100 || profile_idc == 110 ||  
            profile_idc == 122 || profile_idc == 144 )  
        {  
            int chroma_format_idc=Ue(buf,nLen,StartBit);  
            if( chroma_format_idc == 3 )  
                int residual_colour_transform_flag=u(1,buf,StartBit);  
            int bit_depth_luma_minus8=Ue(buf,nLen,StartBit);  
            int bit_depth_chroma_minus8=Ue(buf,nLen,StartBit);  
            int qpprime_y_zero_transform_bypass_flag=u(1,buf,StartBit);  
            int seq_scaling_matrix_present_flag=u(1,buf,StartBit);  
  
            int seq_scaling_list_present_flag[8];  
            if( seq_scaling_matrix_present_flag )  
            {  
                for( int i = 0; i < 8; i++ ) {  
                    seq_scaling_list_present_flag[i]=u(1,buf,StartBit);  
                }  
            }  
        }  
        int log2_max_frame_num_minus4=Ue(buf,nLen,StartBit);  
        int pic_order_cnt_type=Ue(buf,nLen,StartBit);  
        if( pic_order_cnt_type == 0 )  
            int log2_max_pic_order_cnt_lsb_minus4=Ue(buf,nLen,StartBit);  
        else if( pic_order_cnt_type == 1 )  
        {  
            int delta_pic_order_always_zero_flag=u(1,buf,StartBit);  
            int offset_for_non_ref_pic=Se(buf,nLen,StartBit);  
            int offset_for_top_to_bottom_field=Se(buf,nLen,StartBit);  
            int num_ref_frames_in_pic_order_cnt_cycle=Ue(buf,nLen,StartBit);  
  
            int *offset_for_ref_frame=new int[num_ref_frames_in_pic_order_cnt_cycle];  
            for( int i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++ )  
                offset_for_ref_frame[i]=Se(buf,nLen,StartBit);  
            delete [] offset_for_ref_frame;  
        }  
        int num_ref_frames=Ue(buf,nLen,StartBit);  
        int gaps_in_frame_num_value_allowed_flag=u(1,buf,StartBit);  
        int pic_width_in_mbs_minus1=Ue(buf,nLen,StartBit);  
        int pic_height_in_map_units_minus1=Ue(buf,nLen,StartBit);  
  
        width=(pic_width_in_mbs_minus1+1)*16;  
        height=(pic_height_in_map_units_minus1+1)*16;  
  
        return true;  
    }  
    else  
        return false;  
}  


顺便考考大家,知道这个函数的参数BYTE * buf,unsigned int nLen从哪里来的吗?
对了,就是刚才保存的sps.264,fopen,fread,读出来,MP4Encoder这里有个函数PraseMetadata,帮着分析sps pps。
大致如下:
MP4ENC_Metadata mp4meta;
PraseMetadata(buf, nLen, mp4meta);
int width = 0,height = 0;  
if (!h264_decode_sps(mp4meta.Sps, mp4meta.nSpsLen, width, height))
return -1;
Handle = CreateMP4File(outFile, width, height);
Write264Metadata(&mp4meta);
然后每次回调回来:
WriteH264Data(data, len);


自己加个时间判断,比如每几分钟保存一个文件,自己看着处理。回调的时间戳这里没有用上,是发送RTMP时用的。


七 RTMP发送
参考上面提到的第二个链接,里面是读一个264文件,然后发送成RTMP流。这里稍稍改一下,把实时的数据发出去。其实原来都一样的,在live保存文件的时候
已经说过,文件开头保存了sps和pps,然后依次是0x00, 0x00, 0x00, 0x01+视频数据,这些直接fwrite到文件里就是.264。参考的文章就是发送这个.264。
注意一下,发送文件和发送实时数据流的唯一区别就是:文件的头保存着sps信息,而直播流需要读缓存里的(一般rtsp会每隔一段时间再发,用这个也行,而且比保存的更准确)。
那接下来就很简单了,先修改一下SendH264File这个函数:


  
bool CRTMPStream::SendH264File(const char *pFileName)  
{  
    if(pFileName == NULL)  
    {  
        return FALSE;  
    }  
    FILE *fp = fopen(pFileName, "rb");    
    if(!fp)    
    {    
        printf("ERROR:open file %s failed!",pFileName);  
    }    
    fseek(fp, 0, SEEK_SET);  
    m_nFileBufSize = fread(m_pFileBuf, sizeof(unsigned char), FILEBUFSIZE, fp);  
    if(m_nFileBufSize >= FILEBUFSIZE)  
    {  
        printf("warning : File size is larger than BUFSIZE\n");  
    }  
    fclose(fp);    
  
    RTMPMetadata metaData;  
    memset(&metaData,0,sizeof(RTMPMetadata));  
  
    NaluUnit naluUnit;  
    // 读取SPS帧  
    ReadOneNaluFromBuf(naluUnit);  
    metaData.nSpsLen = naluUnit.size;  
    memcpy(metaData.Sps,naluUnit.data,naluUnit.size);  
  
    // 读取PPS帧  
    ReadOneNaluFromBuf(naluUnit);  
    metaData.nPpsLen = naluUnit.size;  
    memcpy(metaData.Pps,naluUnit.data,naluUnit.size);  
  
    // 解码SPS,获取视频图像宽、高信息  
    int width = 0,height = 0;  
    h264_decode_sps(metaData.Sps,metaData.nSpsLen,width,height);  
    metaData.nWidth = width;  
    metaData.nHeight = height;  
    metaData.nFrameRate = 25;  
     
    // 发送MetaData  
    return SendMetadata(&metaData); 
    //以下本文注释掉,改从直播视频里发 
  
    /*unsigned int tick = 0;  
    while(ReadOneNaluFromBuf(naluUnit))  
    {  
        bool bKeyframe  = (naluUnit.type == 0x05) ? TRUE : FALSE;  
        // 发送H264数据帧  
        SendH264Packet(naluUnit.data,naluUnit.size,bKeyframe,tick);  
        msleep(40);  
        tick +=40;  
    }  
  
    return TRUE;  */
}  






然后,发送回调出来的数据:


SendH264Packet(data+4, size-4, bKeyframe, nTimeStamp); 
上面1,2,4这三个函数,是回调出来的,第三个bKeyframe可以自己算出来:
int type = data[4]&0x1f;
bool bKeyframe  = (type == 0x05) ? true : false; 




取data[4]的原因,是因为前面有0x00, 0x00, 0x00, 0x01,+4和-4同样道理。




因为参考的链接有完整的rtmp和mp4v2完整的源码,这里就不多说了。live相关的源码,上面那些做测试用也够了。
有问题随时交流。
阅读(20549) | 评论(1) | 转发(2) |
给主人留下些什么吧!~~

sxcong2014-11-05 11:43:34

关于timestamp, http://blog.csdn.net/firehood_/article/details/8783589 这个例子是这样的:
SendH264Packet(naluUnit.data,naluUnit.size,bKeyframe,tick);  
        msleep(40);  
        tick +=40;

如果你是实时采集的话,还可以这样:


开始时间 :
struct timeval start_time;
gettimeofday(&start_time, NULL);
当前时间:
struct timeval cur;
  gettimeofday(&cur, NULL);

int timestamp = (c

回复 | 举报