RTP打包发送H.264——纯代码,直接上

http://blog.csdn.net/bytxl/article/details/50463925

H264.h头文件内容:

[cpp] view plain copy
 
  1. #include <stdio.h>    
  2. #include <stdlib.h>    
  3. #include <conio.h>    
  4. #include <string.h>    
  5. #include <winsock2.h>    
  6. #pragma comment( lib, "ws2_32.lib" )      
  7.     
  8. #define PACKET_BUFFER_END      (unsigned int)0x00000000    
  9.     
  10. #define MAX_RTP_PKT_LENGTH     1400    
  11.     
  12. #define DEST_IP                "192.168.0.25"    
  13. #define DEST_PORT               1234    
  14.     
  15. #define H264                    96    
  16.     
  17. /******************************************************************  
  18. RTP_FIXED_HEADER  
  19. 0                   1                   2                   3  
  20. 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1  
  21. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  22. |V=2|P|X|  CC   |M|     PT      |       sequence number         |  
  23. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  24. |                           timestamp                           |  
  25. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  26. |           synchronization source (SSRC) identifier            |  
  27. +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+  
  28. |            contributing source (CSRC) identifiers             |  
  29. |                             ....                              |  
  30. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  
  31.   
  32. ******************************************************************/    
  33. typedef struct     
  34. {    
  35.     /* byte 0 */    
  36.     unsigned char csrc_len:4; /* CC expect 0 */    
  37.     unsigned char extension:1;/* X  expect 1, see RTP_OP below */    
  38.     unsigned char padding:1;  /* P  expect 0 */    
  39.     unsigned char version:2;  /* V  expect 2 */    
  40.     /* byte 1 */    
  41.     unsigned char payload:7; /* PT  RTP_PAYLOAD_RTSP */    
  42.     unsigned char marker:1;  /* M   expect 1 */    
  43.     /* byte 2,3 */    
  44.     unsigned short seq_no;   /*sequence number*/    
  45.     /* byte 4-7 */    
  46.     unsigned  long timestamp;    
  47.     /* byte 8-11 */    
  48.     unsigned long ssrc; /* stream number is used here. */    
  49. } RTP_FIXED_HEADER;/*12 bytes*/    
  50.     
  51. /******************************************************************  
  52. NALU_HEADER  
  53. +---------------+  
  54. |0|1|2|3|4|5|6|7|  
  55. +-+-+-+-+-+-+-+-+  
  56. |F|NRI|  Type   |  
  57. +---------------+  
  58. ******************************************************************/    
  59. typedef struct {    
  60.     //byte 0    
  61.     unsigned char TYPE:5;    
  62.     unsigned char NRI:2;    
  63.     unsigned char F:1;    
  64. } NALU_HEADER; /* 1 byte */    
  65.     
  66.     
  67. /******************************************************************  
  68. FU_INDICATOR  
  69. +---------------+  
  70. |0|1|2|3|4|5|6|7|  
  71. +-+-+-+-+-+-+-+-+  
  72. |F|NRI|  Type   |  
  73. +---------------+  
  74. ******************************************************************/    
  75. typedef struct {    
  76.     //byte 0    
  77.     unsigned char TYPE:5;    
  78.     unsigned char NRI:2;     
  79.     unsigned char F:1;             
  80. } FU_INDICATOR; /*1 byte */    
  81.     
  82.     
  83. /******************************************************************  
  84. FU_HEADER  
  85. +---------------+  
  86. |0|1|2|3|4|5|6|7|  
  87. +-+-+-+-+-+-+-+-+  
  88. |S|E|R|  Type   |  
  89. +---------------+  
  90. ******************************************************************/    
  91. typedef struct {    
  92.     //byte 0    
  93.     unsigned char TYPE:5;    
  94.     unsigned char R:1;    
  95.     unsigned char E:1;    
  96.     unsigned char S:1;        
  97. } FU_HEADER; /* 1 byte */    



RTPSend.cpp文件内容:

[cpp] view plain copy
 
  1. #include <stdio.h>    
  2. #include <stdlib.h>    
  3. #include <string.h>    
  4. #include <memory.h>    
  5. #include "h264.h"    
  6.     
  7. #define  UDP_MAX_SIZE 1400    
  8.     
  9. typedef struct    
  10. {    
  11.     int startcodeprefix_len;      //! 4 for parameter sets and first slice in picture, 3 for everything else (suggested)    
  12.     unsigned len;                 //! Length of the NAL unit (Excluding the start code, which does not belong to the NALU)    
  13.     unsigned max_size;            //! Nal Unit Buffer size    
  14.     int forbidden_bit;            //! should be always FALSE    
  15.     int nal_reference_idc;        //! NALU_PRIORITY_xxxx    
  16.     int nal_unit_type;            //! NALU_TYPE_xxxx        
  17.     char *buf;                    //! contains the first byte followed by the EBSP    
  18.     unsigned short lost_packets;  //! true, if packet loss is detected    
  19. } NALU_t;    
  20.     
  21. FILE *bits = NULL;                //!< the bit stream file    
  22. static int FindStartCode2(unsigned char *Buf);//查找开始字符0x000001    
  23. static int FindStartCode3(unsigned char *Buf);//查找开始字符0x00000001    
  24.     
  25.     
  26. static int info2=0, info3=0;    
  27. RTP_FIXED_HEADER *rtp_hdr;    
  28.     
  29. NALU_HEADER     *nalu_hdr;    
  30. FU_INDICATOR    *fu_ind;    
  31. FU_HEADER       *fu_hdr;    
  32.     
  33. BOOL InitWinsock()    
  34. {    
  35.     int Error;    
  36.     WORD VersionRequested;    
  37.     WSADATA WsaData;    
  38.     VersionRequested=MAKEWORD(2,2);    
  39.     Error=WSAStartup(VersionRequested,&WsaData); //启动WinSock2    
  40.     if(Error!=0)    
  41.     {    
  42.         return FALSE;    
  43.     }    
  44.     else    
  45.     {    
  46.         if(LOBYTE(WsaData.wVersion)!=2||HIBYTE(WsaData.wHighVersion)!=2)    
  47.         {    
  48.             WSACleanup();    
  49.             return FALSE;    
  50.         }    
  51.     
  52.     }    
  53.     return TRUE;    
  54. }    
  55.     
  56. //为NALU_t结构体分配内存空间    
  57. NALU_t *AllocNALU(int buffersize)    
  58. {    
  59.     NALU_t *n;    
  60.     
  61.     if ((n = (NALU_t*)calloc (1, sizeof (NALU_t))) == NULL)    
  62.     {    
  63.         printf("AllocNALU: n");    
  64.         exit(0);    
  65.     }    
  66.     
  67.     n->max_size=buffersize;    
  68.     
  69.     if ((n->buf = (char*)calloc (buffersize, sizeof (char))) == NULL)    
  70.     {    
  71.         free (n);    
  72.         printf ("AllocNALU: n->buf");    
  73.         exit(0);    
  74.     }    
  75.     
  76.     return n;    
  77. }    
  78.     
  79. //释放    
  80. void FreeNALU(NALU_t *n)    
  81. {    
  82.     if (n)    
  83.     {    
  84.         if (n->buf)    
  85.         {    
  86.             free(n->buf);    
  87.             n->buf=NULL;    
  88.         }    
  89.         free (n);    
  90.     }    
  91. }    
  92.     
  93. void OpenBitstreamFile (char *fn)    
  94. {    
  95.     if (NULL == (bits=fopen(fn, "rb")))    
  96.     {    
  97.         printf("open file error ");    
  98.         exit(0);    
  99.     }    
  100. }    
  101.     
  102. //这个函数输入为一个NAL结构体,主要功能为得到一个完整的NALU并保存在NALU_t的buf中,    
  103. //获取他的长度,填充F,IDC,TYPE位。    
  104. //并且返回两个开始字符之间间隔的字节数,即包含有前缀的NALU的长度    
  105. int GetAnnexbNALU (NALU_t *nalu)    
  106. {    
  107.     int pos = 0;    
  108.     int StartCodeFound, rewind;    
  109.     unsigned char *Buf;    
  110.     
  111.     if ((Buf = (unsigned char*)calloc (nalu->max_size , sizeof(char))) == NULL)     
  112.         printf ("GetAnnexbNALU: Could not allocate Buf memory ");    
  113.     
  114.     nalu->startcodeprefix_len=3;//初始化码流序列的开始字符为3个字节    
  115.     
  116.     if (3 != fread (Buf, 1, 3, bits))//从码流中读3个字节    
  117.     {    
  118.         free(Buf);    
  119.         return 0;    
  120.     }    
  121.     info2 = FindStartCode2 (Buf);//判断是否为0x000001     
  122.     if(info2 != 1)     
  123.     {    
  124.         //如果不是,再读一个字节    
  125.         if(1 != fread(Buf+3, 1, 1, bits))//读一个字节    
  126.         {    
  127.             free(Buf);    
  128.             return 0;    
  129.         }    
  130.         info3 = FindStartCode3 (Buf);//判断是否为0x00000001    
  131.         if (info3 != 1)//如果不是,返回-1    
  132.         {     
  133.             free(Buf);    
  134.             return -1;    
  135.         }    
  136.         else     
  137.         {    
  138.             //如果是0x00000001,得到开始前缀为4个字节    
  139.             pos = 4;    
  140.             nalu->startcodeprefix_len = 4;    
  141.         }    
  142.     }    
  143.     else    
  144.     {    
  145.         //如果是0x000001,得到开始前缀为3个字节    
  146.         nalu->startcodeprefix_len = 3;    
  147.         pos = 3;    
  148.     }    
  149.     //查找下一个开始字符的标志位    
  150.     StartCodeFound = 0;    
  151.     info2 = 0;    
  152.     info3 = 0;    
  153.     
  154.     while (!StartCodeFound)    
  155.     {    
  156.         if (feof (bits))//判断是否到了文件尾    
  157.         {    
  158.             nalu->len = (pos-1)-nalu->startcodeprefix_len;    
  159.             memcpy (nalu->buf, &Buf[nalu->startcodeprefix_len], nalu->len);         
  160.             nalu->forbidden_bit = nalu->buf[0] & 0x80; //1 bit    
  161.             nalu->nal_reference_idc = nalu->buf[0] & 0x60; // 2 bit    
  162.             nalu->nal_unit_type = (nalu->buf[0]) & 0x1f;// 5 bit    
  163.             free(Buf);    
  164.             return pos-1;    
  165.         }    
  166.         Buf[pos++] = fgetc (bits);//读一个字节到BUF中    
  167.         info3 = FindStartCode3(&Buf[pos-4]);//判断是否为0x00000001    
  168.         if(info3 != 1)    
  169.             info2 = FindStartCode2(&Buf[pos-3]);//判断是否为0x000001    
  170.         StartCodeFound = (info2 == 1 || info3 == 1);    
  171.     }    
  172.     
  173.     // Here, we have found another start code (and read length of startcode bytes more than we should    
  174.     // have.  Hence, go back in the file    
  175.     rewind = (info3 == 1)? -4 : -3;    
  176.     
  177.     if (0 != fseek (bits, rewind, SEEK_CUR))//把文件指针指向前一个NALU的末尾    
  178.     {    
  179.         free(Buf);    
  180.         printf("GetAnnexbNALU: Cannot fseek in the bit stream file");    
  181.     }    
  182.     
  183.     // Here the Start code, the complete NALU, and the next start code is in the Buf.      
  184.     // The size of Buf is pos, pos+rewind are the number of bytes excluding the next    
  185.     // start code, and (pos+rewind)-startcodeprefix_len is the size of the NALU excluding the start code    
  186.     
  187.     nalu->len = (pos+rewind)-nalu->startcodeprefix_len;    
  188.     memcpy (nalu->buf, &Buf[nalu->startcodeprefix_len], nalu->len);//拷贝一个完整NALU,不拷贝起始前缀0x000001或0x00000001    
  189.     nalu->forbidden_bit = nalu->buf[0] & 0x80;        //1 bit    
  190.     nalu->nal_reference_idc = nalu->buf[0] & 0x60;    //2 bit    
  191.     nalu->nal_unit_type = (nalu->buf[0]) & 0x1f;  //5 bit    
  192.     free(Buf);    
  193.     
  194.     return (pos+rewind);//返回两个开始字符之间间隔的字节数,即包含有前缀的NALU的长度    
  195. }    
  196.     
  197. static int FindStartCode2 (unsigned char *Buf)    
  198. {    
  199.     if(Buf[0]!=0 || Buf[1]!=0 || Buf[2] !=1) return 0; //判断是否为0x000001,如果是返回1    
  200.     else return 1;    
  201. }    
  202.     
  203. static int FindStartCode3 (unsigned char *Buf)    
  204. {    
  205.     if(Buf[0]!=0 || Buf[1]!=0 || Buf[2] !=0 || Buf[3] !=1) return 0;//判断是否为0x00000001,如果是返回1    
  206.     else return 1;    
  207. }    
  208.     
  209. int rtpnum = 0;    
  210.     
  211. //输出NALU长度和TYPE    
  212. void dump(NALU_t *n)    
  213. {    
  214.     if (!n)return;    
  215.     printf("%3d, len: %6d  ",rtpnum++, n->len);    
  216.     printf("nal_unit_type: %x ", n->nal_unit_type);    
  217. }    
  218.     
  219. int main(int argc, char* argv[])    
  220. {    
  221.     OpenBitstreamFile("E:\测试数据\tv480x320.264");    
  222.     NALU_t *n;    
  223.     char* nalu_payload;      
  224.     char sendbuf[1500];    
  225.     
  226.     unsigned short seq_num =0;    
  227.     int bytes=0;    
  228.     InitWinsock(); //初始化套接字库    
  229.     SOCKET    socket1;    
  230.     struct sockaddr_in server;    
  231.     int len =sizeof(server);    
  232.     float framerate=15;    
  233.     unsigned int timestamp_increse=0,ts_current=0;    
  234.     timestamp_increse=(unsigned int)(90000.0 / framerate); //+0.5);    
  235.     
  236.     server.sin_family=AF_INET;    
  237.     server.sin_port=htons(DEST_PORT);              
  238.     server.sin_addr.s_addr=inet_addr(DEST_IP);     
  239.     socket1=socket(AF_INET,SOCK_DGRAM,0);    
  240.     connect(socket1, (const sockaddr *)&server, len) ;//申请UDP套接字    
  241.     n = AllocNALU(8000000);//为结构体nalu_t及其成员buf分配空间。返回值为指向nalu_t存储空间的指针    
  242.         
  243.     while(!feof(bits))     
  244.     {    
  245.         GetAnnexbNALU(n);//每执行一次,文件的指针指向本次找到的NALU的末尾,下一个位置即为下个NALU的起始码0x000001    
  246.         dump(n);//输出NALU长度和TYPE    
  247.     
  248.         memset(sendbuf,0,1500);//清空sendbuf;此时会将上次的时间戳清空,因此需要ts_current来保存上次的时间戳值    
  249.             
  250.         //rtp固定包头,为12字节,该句将sendbuf[0]的地址赋给rtp_hdr,以后对rtp_hdr的写入操作将直接写入sendbuf。    
  251.         rtp_hdr =(RTP_FIXED_HEADER*)&sendbuf[0];     
  252.             
  253.         //设置RTP HEADER,    
  254.         rtp_hdr->version = 2;   //版本号,此版本固定为2    
  255.         rtp_hdr->marker  = 0;   //标志位,由具体协议规定其值。    
  256.         rtp_hdr->payload = H264;//负载类型号,    
  257.         rtp_hdr->ssrc    = htonl(10);//随机指定为10,并且在本RTP会话中全局唯一    
  258.     
  259.         //当一个NALU小于1400字节的时候,采用一个单RTP包发送    
  260.         if(n->len<=UDP_MAX_SIZE){    
  261.             //设置rtp M 位;    
  262.             rtp_hdr->marker=1;    
  263.             rtp_hdr->seq_no = htons(seq_num ++); //序列号,每发送一个RTP包增1    
  264.     
  265.             //设置NALU HEADER,并将这个HEADER填入sendbuf[12]    
  266.             nalu_hdr =(NALU_HEADER*)&sendbuf[12]; //将sendbuf[12]的地址赋给nalu_hdr,之后对nalu_hdr的写入就将写入sendbuf中;    
  267.             nalu_hdr->F=n->forbidden_bit;    
  268.             nalu_hdr->NRI=n->nal_reference_idc>>5;//有效数据在n->nal_reference_idc的第6,7位,需要右移5位才能将其值赋给nalu_hdr->NRI。    
  269.             nalu_hdr->TYPE=n->nal_unit_type;    
  270.     
  271.             nalu_payload=&sendbuf[13];//同理将sendbuf[13]赋给nalu_payload    
  272.             memcpy(nalu_payload,n->buf+1,n->len-1);//去掉nalu头的nalu剩余内容写入sendbuf[13]开始的字符串。    
  273.     
  274.             ts_current=ts_current+timestamp_increse;    
  275.             rtp_hdr->timestamp=htonl(ts_current);    
  276.             bytes=n->len + 12 ;  //获得sendbuf的长度,为nalu的长度(包含NALU头但除去起始前缀)加上rtp_header的固定长度12字节    
  277.             send(socket1,sendbuf,bytes,0);//发送RTP包    
  278.             //Sleep(100);    
  279.         }else{    
  280.             int packetNum = n->len/UDP_MAX_SIZE;    
  281.             if (n->len%UDP_MAX_SIZE != 0)    
  282.                 packetNum ++;    
  283.     
  284.             int lastPackSize = n->len - (packetNum-1)*UDP_MAX_SIZE;    
  285.             int packetIndex = 1 ;    
  286.         
  287.             ts_current=ts_current+timestamp_increse;    
  288.     
  289.             rtp_hdr->timestamp=htonl(ts_current);    
  290.     
  291.             //发送第一个的FU,S=1,E=0,R=0    
  292.     
  293.             rtp_hdr->seq_no = htons(seq_num ++); //序列号,每发送一个RTP包增1    
  294.             //设置rtp M 位;    
  295.             rtp_hdr->marker=0;    
  296.             //设置FU INDICATOR,并将这个HEADER填入sendbuf[12]    
  297.             fu_ind =(FU_INDICATOR*)&sendbuf[12]; //将sendbuf[12]的地址赋给fu_ind,之后对fu_ind的写入就将写入sendbuf中;    
  298.             fu_ind->F=n->forbidden_bit;    
  299.             fu_ind->NRI=n->nal_reference_idc>>5;    
  300.             fu_ind->TYPE=28;    
  301.     
  302.             //设置FU HEADER,并将这个HEADER填入sendbuf[13]    
  303.             fu_hdr =(FU_HEADER*)&sendbuf[13];    
  304.             fu_hdr->S=1;    
  305.             fu_hdr->E=0;    
  306.             fu_hdr->R=0;    
  307.             fu_hdr->TYPE=n->nal_unit_type;    
  308.     
  309.             nalu_payload=&sendbuf[14];//同理将sendbuf[14]赋给nalu_payload    
  310.             memcpy(nalu_payload,n->buf+1,UDP_MAX_SIZE);//去掉NALU头    
  311.             bytes=UDP_MAX_SIZE+14;//获得sendbuf的长度,为nalu的长度(除去起始前缀和NALU头)加上rtp_header,fu_ind,fu_hdr的固定长度14字节    
  312.             send( socket1, sendbuf, bytes, 0 );//发送RTP包    
  313.     
  314.             //发送中间的FU,S=0,E=0,R=0    
  315.             for(packetIndex=2;packetIndex<packetNum;packetIndex++)    
  316.             {    
  317.                 rtp_hdr->seq_no = htons(seq_num ++); //序列号,每发送一个RTP包增1    
  318.              
  319.                 //设置rtp M 位;    
  320.                 rtp_hdr->marker=0;    
  321.                 //设置FU INDICATOR,并将这个HEADER填入sendbuf[12]    
  322.                 fu_ind =(FU_INDICATOR*)&sendbuf[12]; //将sendbuf[12]的地址赋给fu_ind,之后对fu_ind的写入就将写入sendbuf中;    
  323.                 fu_ind->F=n->forbidden_bit;    
  324.                 fu_ind->NRI=n->nal_reference_idc>>5;    
  325.                 fu_ind->TYPE=28;    
  326.     
  327.                 //设置FU HEADER,并将这个HEADER填入sendbuf[13]    
  328.                 fu_hdr =(FU_HEADER*)&sendbuf[13];    
  329.                 fu_hdr->S=0;    
  330.                 fu_hdr->E=0;    
  331.                 fu_hdr->R=0;    
  332.                 fu_hdr->TYPE=n->nal_unit_type;    
  333.     
  334.                 nalu_payload=&sendbuf[14];//同理将sendbuf[14]的地址赋给nalu_payload    
  335.                 memcpy(nalu_payload,n->buf+(packetIndex-1)*UDP_MAX_SIZE+1,UDP_MAX_SIZE);//去掉起始前缀的nalu剩余内容写入sendbuf[14]开始的字符串。    
  336.                 bytes=UDP_MAX_SIZE+14;//获得sendbuf的长度,为nalu的长度(除去原NALU头)加上rtp_header,fu_ind,fu_hdr的固定长度14字节    
  337.                 send( socket1, sendbuf, bytes, 0 );//发送rtp包                 
  338.             }    
  339.     
  340.             //发送最后一个的FU,S=0,E=1,R=0    
  341.             
  342.             rtp_hdr->seq_no = htons(seq_num ++);    
  343.             //设置rtp M 位;当前传输的是最后一个分片时该位置1           
  344.             rtp_hdr->marker=1;    
  345.             //设置FU INDICATOR,并将这个HEADER填入sendbuf[12]    
  346.             fu_ind =(FU_INDICATOR*)&sendbuf[12]; //将sendbuf[12]的地址赋给fu_ind,之后对fu_ind的写入就将写入sendbuf中;    
  347.             fu_ind->F=n->forbidden_bit;    
  348.             fu_ind->NRI=n->nal_reference_idc>>5;    
  349.             fu_ind->TYPE=28;    
  350.     
  351.             //设置FU HEADER,并将这个HEADER填入sendbuf[13]    
  352.             fu_hdr =(FU_HEADER*)&sendbuf[13];    
  353.             fu_hdr->S=0;    
  354.             fu_hdr->E=1;    
  355.             fu_hdr->R=0;    
  356.             fu_hdr->TYPE=n->nal_unit_type;    
  357.     
  358.             nalu_payload=&sendbuf[14];//同理将sendbuf[14]的地址赋给nalu_payload    
  359.             memcpy(nalu_payload,n->buf+(packetIndex-1)*UDP_MAX_SIZE+1,lastPackSize-1);//将nalu最后剩余的-1(去掉了一个字节的NALU头)字节内容写入sendbuf[14]开始的字符串。    
  360.             bytes=lastPackSize-1+14;//获得sendbuf的长度,为剩余nalu的长度l-1加上rtp_header,FU_INDICATOR,FU_HEADER三个包头共14字节    
  361.             send( socket1, sendbuf, bytes, 0 );//发送rtp包         
  362.         }    
  363.     
  364.         //Sleep(33);    
  365.     }    
  366.     
  367.     FreeNALU(n);    
  368.     return 0;    
  369. }    


将以下文本保存为rtpPara.sdp文件

m=video 1234 RTP/AVP 96
a=rtpmap:96 H264
a=framerate:30
c=IN IP4 192.168.0.25

用VLC打开该文件,然后运行编译好的发送程序。

注意头文件和sdp文件的IP都要与实验机器的IP吻合。

该代码在NALDecoder程序基础上修改了一个内存bug而已。感谢前人的开源。

http://blog.csdn.net/wangjiannuaa/article/details/6694831

原文地址:https://www.cnblogs.com/stnlcd/p/7267672.html