视频会议中或者录播中使用RTP协议接收h264视频

来源:互联网 发布:云计算软件有哪些 编辑:程序博客网 时间:2024/06/06 12:46

此程序文章献给刚进公司的需要帮助的程序员,

       说明:1 该代码在windows上运行,用vs2010编译。

                   2 该代码要能解决移植的问题。 

                   3 rtp实时传输协议可以使用udp,也可以使用tcp协议

       首先,为了减小程序的难度,说明使用的库解码库为ffmpeg,刷视频数据的方法可以使用

                  1 SDL库 ,到sdl的源代码网站中下载并编译

                  2 直接使用gdi, 并且解决翻转问题。

                  3 使用opengl或者direct3d, 或者directdraw。

     基础知识:

      A  首先RTP 包结构一般为12字节,传输层协议中UDP协议和TCP协议是可选的,都可以用,多数使用了UDP协议,如果要扫盲,请链接到基维百 

          科http://zh.wikipedia.org/wiki/%E5%AE%9E%E6%97%B6%E4%BC%A0%E8%BE%93%E5%8D%8F%E8%AE%AE,使用tcp协议的好处是和rtsp协议

          相关联的,涉及到nat转换 路由方面的知识,我后面会讲,而UDP协议在h264等视频发送的时候要注意的是分包问题,主要是MTU最大传输单元的问题,h264的

          nalu如果超过最大传输单元,必须分割发送。

      B ffmpeg1.0 已经及其优秀,包含ffmpeg库不要忘了 extern “C”extern "C"{#include #include #include #include }为了使得快速开发出一个原型,使用boost的asio库,

         可以节省一些时间。并且使用回调函数来解码和刷屏,以下是使用asio库来接收网络的包,默认使用了组播地址,也就是说假设该h264视频会传送到组播地址上,传送到

         组播地址的好处是调试方便,在局域网内接收都可以。

 

这是网络接收类的一个头文件示例,读者完全可以不使用boost库,自行写出:


[cpp] view plain copy
 print?
  1.   
[cpp] view plain copy
 print?
  1. #pragma once  
  2. #include "CodeReceive.h"  
  3.   
  4. #include <boost/asio.hpp>  
  5. #include <boost/bind.hpp>  
  6. #include <boost/thread.hpp>  
  7.   
  8. #include "DrawRGB24.h"  
  9. extern "C"  
  10. {  
  11. #include <libavcodec/avcodec.h>  
  12. #include <libavutil/mathematics.h>  
  13. #include <libavformat/avformat.h>  
  14. #include <libswscale/swscale.h>  
  15. }  
  16.   
  17. #include "h264head/h264-x264.h"  
  18.   
  19. class CodeReceive2:public CBaseReceive  
  20. {  
  21. friend DWORD WINAPI ThreadProcReceive(LPVOID param);  
  22. public:  
  23.     CodeReceive2();  
  24.     ~CodeReceive2(void);  
  25. protected:  
  26.     void CreateiocpReceiver(const boost::asio::ip::address& listen_address,  
  27.       const boost::asio::ip::address& multicast_address,  
  28.       const unsigned short port);  
  29.       
  30.     void handle_receive_from_direct(const boost::system::error_code& error,  
  31.       size_t bytes_recvd);  
  32.   
  33.   
  34.   
  35.     BOOL CreateDecode()  
  36.     {  
  37.         if(_pDecode==NULL)  
  38.         {  
  39.             _pDecode= new H264DecoderContext();  
  40.   
  41.             if(_pDecode == NULL)  
  42.                 return FALSE;  
  43.             if(!_pDecode->Initialize())  
  44.                 return FALSE;  
  45.         }  
  46.         return TRUE;  
  47.     }  
  48.     void DeleteDecode()  
  49.     {  
  50.         if(_pDecode!=NULL)  
  51.         {  
  52.             delete _pDecode;  
  53.             _pDecode = NULL;  
  54.         }  
  55.     }  
  56.   
  57.   
  58. public:  
  59.     virtual int Pix_Fmt();  
  60.     virtual int Width()  ;  
  61.     virtual int Height() ;  
  62.     virtual BOOL StartReceive(string ip,unsigned short port) ;  
  63.   
  64.     virtual void StopReceive() ;  
  65.   
  66.     //这个画法是使用了SDL画法  
  67.     virtual void SetFunction(FrameCallback func) ;  
  68.   
  69.     //这个是可以获取数据自己画,后面的版本是要用directshow vmr画法  
  70.     virtual void SetFunctionRGB24(FrameCallback_RGB24 func) ;  
  71.   
  72.     //这个是内置的画法,普通GDI画,参考OpenCV源代码,预览画像  
  73.     virtual void SetDrawhWnd(HWND hWnd0,HWND hWnd1) ;  
  74.   
  75.    // static DWORD ThreadProc_Recv(LPVOID param);  
  76.   
  77. private:  
  78.   
  79.     boost::asio::io_service io_service_;  
  80.     boost::asio::ip::udp::socket socket_;  
  81.     boost::asio::ip::udp::endpoint sender_endpoint_;  
  82.     enum { max_length = 1500 };  
  83.     char data_[max_length];  
  84.     unsigned short _multicast_port;  
  85.   
  86.     string _multicast_ip;  
  87. private:  
  88.     H264DecoderContext* _pDecode;  
  89.   
  90.     AVFrame * _pFrameRGB;  
  91.     uint8_t * _RGBBuffer;  
  92.     struct SwsContext *_img_convert_ctx;  
  93.     //同时画两个窗口  
  94.     CDrawRGB24 _Draw;  
  95.    //  HANDLE _ThreadHandle  ;  
  96.     HWND _hWnd0;  
  97.     HWND _hWnd1;  
  98.   
  99.     FrameCallback_RGB24 _functionRGB24;  
  100. };  


类的cpp文件的接收函数的关键函数

[html] view plain copy
 print?
  1. void CodeReceive2::handle_receive_from_direct(const boost::system::error_code& error,  
  2.       size_t bytes_recvd)  
  3. {  
  4.     if (!error)  
  5.     {  
  6.           
  7.         AVFrame * frame =_pDecode->DecodeFrames((const u_char*)data_,bytes_recvd);  
  8.         if(frame!=NULL)  
  9.         {  
  10.             int Width  = this->Width();//_pDecode->GetContext()->width;  
  11.             int Height = this->Height();//_pDecode->GetContext()->height;  
  12.   
  13. #if 0  //如果需要用sdl渲染画面,可以打开这个  
  14.             if(_function )  
  15.                 _function(frame,_pDecode->GetContext()->pix_fmt,  
  16.                     _pDecode->GetContext()->width,  
  17.                     _pDecode->GetContext()->height  
  18.           
  19.                     );  
  20. #endif              
  21.               
  22.             if(_RGBBuffer == NULL)  
  23.             {  
  24.                 int numBytes;  
  25.   
  26.                 numBytes=avpicture_get_size(  
  27.                     //PIX_FMT_RGB24,   
  28.                     PIX_FMT_BGR24,  
  29.                     Width,  
  30.                     Height);  
  31.                 _RGBBuffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));  
  32.   
  33.                 if(_pFrameRGB == NULL)  
  34.                     _pFrameRGB = avcodec_alloc_frame();  
  35.                 avpicture_fill((AVPicture *)_pFrameRGB, _RGBBuffer, PIX_FMT_BGR24,   Width, Height);   
  36.   
  37.                 _img_convert_ctx = sws_getContext(Width, Height,   
  38.                     _pDecode->GetContext()->pix_fmt,//PIX_FMT_YUV420P,   
  39.                     Width,   
  40.                     Height,   
  41.                     PIX_FMT_BGR24,   
  42.                     SWS_BICUBIC,   
  43.                     NULL,   
  44.                     NULL,   
  45.                     NULL);  
  46.             }  
  47.   
  48.             sws_scale(_img_convert_ctx, frame->data, frame->linesize, 0, Height, _pFrameRGB->data, _pFrameRGB->linesize);  
  49.   
  50.             if(_hWnd0!=NULL || _hWnd1!=NULL)  
  51.                 _Draw.Draw2(_hWnd0,_hWnd1,_pFrameRGB->data[0],Width,Height);  
  52.   
  53.             //Sleep(5);  
  54.             if(_functionRGB24)  
  55.             {  
  56.   
  57.                 _functionRGB24(_pFrameRGB->data[0],_pDecode->GetContext()->pix_fmt,Width,Height);  
  58.             }  
  59.       
  60.         }  
  61.       
  62.   
  63.         socket_.async_receive_from(  
  64.           boost::asio::buffer(data_, max_length), sender_endpoint_,  
  65.           boost::bind(&CodeReceive2::handle_receive_from_direct, this,  
  66.             boost::asio::placeholders::error,  
  67.             boost::asio::placeholders::bytes_transferred));  
  68.   
  69.     }  
  70.   }  


  这里有让刚做ffmpeg或者图像的程序员困惑的一些问题,比如图像为什么接收的是倒立的?RGB实际上是BGR,能不能直接刷屏yuv420等等。图像倒立的问题是直播取到的图像本身就是倒立的,还是过程中倒立了,这个问题比较难以回答,比如摄像头D70,高清的HD1等等有一个开关拨一下就正,再返回去就倒立,不过拿普通的USB摄像头,按照正常采集,经过一系列的变换,你发现图像也是倒得,如果拿一个正常录下的h264视频,有的程序员播放时发现也是倒立的,如果是倒立的,有两个方法解决,一是ffmepg的sws_scale函数可以解决这个问题,一个是gdi刷屏可以解决这个问题,有的程序员会重新memcpy以下,把图像倒过来,这样也是可以的,但如果是高清720P或者1080P的图像较大,比较费事,最好是直接在过程中就解决掉这个问题。

   用gdi刷屏时,把SrcH负过来就可以让图像正过来。

   当然,用gdi必然效率不会很好,尤其做画中画的时候或者多路图像的时候,不能用这个,windows上可以用directx和较新的dxva。

  用下面这个来倒立图像

[cpp] view plain copy
 print?
  1. m_lpBmpInfo->bmiHeader.biHeight=   -SrcH;  


[cpp] view plain copy
 print?
  1. void CDrawRGB24::Draw2(HWND hWnd, HWND hWnd2,unsigned char * buffer, int SrcW, int SrcH)  
  2. {  
  3.     HDC hDCDst1 = NULL;  
  4.     HDC hDCDst2 = NULL;  
  5.     RECT destRect1;  
  6.     RECT destRect2;  
  7.     if(hWnd!=NULL)  
  8.     {  
  9.         hDCDst1 = GetDC(hWnd);  
  10.         GetClientRect(hWnd,&destRect1);  
  11.     }  
  12.     if(hWnd2!=NULL)  
  13.     {  
  14.         hDCDst2 = GetDC(hWnd2);  
  15.         GetClientRect(hWnd2,&destRect2);  
  16.     }  
  17.   
  18.     if(!m_bInit)  
  19.     {  
  20.         m_bInit = true;  
  21.         m_lpBmpInfo=new BITMAPINFO;  
  22.         m_lpBmpInfo->bmiHeader.biSize  = sizeof(BITMAPINFOHEADER);  
  23.         m_lpBmpInfo->bmiHeader.biWidth =   SrcW;  
  24.         m_lpBmpInfo->bmiHeader.biHeight=   -SrcH;  
  25.         m_lpBmpInfo->bmiHeader.biPlanes= 1;  
  26.         m_lpBmpInfo->bmiHeader.biBitCount      = 24;  
  27.         m_lpBmpInfo->bmiHeader.biCompression   = 0;  
  28.         m_lpBmpInfo->bmiHeader.biSizeImage     = 0;  
  29.         m_lpBmpInfo->bmiHeader.biXPelsPerMeter = 0;  
  30.         m_lpBmpInfo->bmiHeader.biYPelsPerMeter = 0;  
  31.         m_lpBmpInfo->bmiHeader.biClrUsed=0;  
  32.         m_lpBmpInfo->bmiHeader.biClrImportant  = 0;  
  33.   
  34.         //CDC * dc =  CDC::FromHandle(hDCDst);  
  35.         //m_pMemDC = new CMemDC(*dc,DestRect);  
  36.     }  
  37.   
  38.     if(hDCDst1!=NULL)  
  39.     {  
  40.         int DstWidth  = destRect1.right-destRect1.left;  
  41.         int DstHeight = destRect1.bottom- destRect1.top;  
  42.         SetStretchBltMode(hDCDst1,STRETCH_HALFTONE);  
  43.         ::StretchDIBits(  
  44.             //m_pMemDC->GetDC().GetSafeHdc(),  
  45.             hDCDst1,  
  46.             0, 0, DstWidth, DstHeight,  
  47.             0, 0, SrcW, SrcH,  
  48.             buffer, m_lpBmpInfo, DIB_RGB_COLORS, SRCCOPY );  
  49.         ReleaseDC(hWnd,hDCDst1);  
  50.     }  
  51.     if(hDCDst2!=NULL)  
  52.     {  
  53.         int DstWidth  = destRect2.right-destRect2.left;  
  54.         int DstHeight = destRect2.bottom- destRect2.top;  
  55.         SetStretchBltMode(hDCDst2,STRETCH_HALFTONE);  
  56.         ::StretchDIBits(  
  57.             //m_pMemDC->GetDC().GetSafeHdc(),  
  58.             hDCDst2,  
  59.             0, 0, DstWidth, DstHeight,  
  60.             0, 0, SrcW, SrcH,  
  61.             buffer, m_lpBmpInfo, DIB_RGB_COLORS, SRCCOPY );  
  62.         ReleaseDC(hWnd2,hDCDst2);  
  63.     }  
  64.   
  65. }  

整个的过程是收包,拿到包头时间戳等信息,去掉包头12字节,拿到h264 nalu数据,用ffmpeg解码,时间戳问题主要集中在音频和视频同步的上面,而pts和dts是同步最重要的信息,解码过程为:

   

[cpp] view plain copy
 print?
  1. AVFrame* H264DecoderContext::DecodeFrames(const u_char * src, unsigned & srcLen)  
  2. {  
  3.   
  4.   RTPFrame srcRTP(src, srcLen);  
  5.   if (!_rxH264Frame->SetFromRTPFrame(srcRTP, flags)) {  
  6.       _rxH264Frame->BeginNewFrame();  
  7.       //sprintf(dst,"%s\n","setfromrtpframe is not ok!");  
  8.       flags = (_gotAGoodFrame ? requestIFrame : 0);  
  9.       _gotAGoodFrame = false;  
  10.       return NULL;  
  11.   }  
  12.   
  13.   if (srcRTP.GetMarker()==0)  
  14.   {  
  15.         return NULL;  
  16.   }   
  17.   
  18.   if (_rxH264Frame->GetFrameSize()==0)  
  19.   {  
  20.       _rxH264Frame->BeginNewFrame();  
  21.       _skippedFrameCounter++;  
  22.       flags = (_gotAGoodFrame ? requestIFrame : 0);  
  23.       _gotAGoodFrame = false;  
  24.       return NULL;  
  25.   }  
  26.   // look and see if we have read an I frame.  
  27.   if (_gotIFrame == 0)  
  28.   {  
  29.     _gotIFrame = 1;  
  30.   }  
  31.    
  32.   
  33.   int gotPicture = 0;  
  34.  // uint32_t bytesUsed = 0;  
  35.   
  36.   // int bytesDecoded = avcodec_decode_video(_context,_outputFrame,&gotPicture,_rxH264Frame->GetFramePtr(),_rxH264Frame->GetFrameSize());  
  37.   
  38.   int bytesDecoded = FFMPEGLibraryInstance.AvcodecDecodeVideo(_context, _outputFrame, &gotPicture, _rxH264Frame->GetFramePtr(), _rxH264Frame->GetFrameSize());  
  39.   _rxH264Frame->BeginNewFrame();  
  40.   if (!gotPicture)   
  41.   {  
  42.       _skippedFrameCounter++;  
  43.       flags = (_gotAGoodFrame ? requestIFrame : 0);  
  44.   
  45.       _gotAGoodFrame = false;  
  46.       return NULL;  
  47.   }  
  48.   
  49.  //得到了一帧  
  50.   // w  = _context->width;  
  51.   // h  = _context->height;  
  52.   flags = 1;  
  53.   _frameCounter++;  
  54.   _gotAGoodFrame = true;  
  55.   
  56.   
  57.   return _outputFrame;  
[cpp] view plain copy
 print?
  1. }  

  代码暂时只是为了演示,并不完整,不过基本过程是非常清楚的。过程中其实还需要处理一个比较傲重要的问题就是分辨率改变的问题,音视频同步的问题,播放过快或者过慢的问题,如果要测试发送的视频是否正确,可以使用vlc来接收测试。

  这是第一篇基础,后面再准备比较完整的示例和用d3d,sdl刷屏,并且加入音频的解码,属于第二篇。

  未完待续。。。。。。





http://blog.csdn.net/qianbo_0423/article/details/8195035

0 0
原创粉丝点击