麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁(yè) > 編程 > C# > 正文

使用C#實(shí)現(xiàn)RTP數(shù)據(jù)包傳輸 參照RFC3550

2020-01-24 03:27:24
字體:
供稿:網(wǎng)友

閑暇時(shí)折騰IP網(wǎng)絡(luò)視頻監(jiān)控系統(tǒng),需要支持視頻幀數(shù)據(jù)包在網(wǎng)絡(luò)內(nèi)的傳輸。
未采用H.264或MPEG4等編碼壓縮方式,直接使用Bitmap圖片。
由于對(duì)幀的準(zhǔn)確到達(dá)要求不好,所以采用UDP傳輸。如果發(fā)生網(wǎng)絡(luò)丟包現(xiàn)象則直接將幀丟棄。
為了記錄數(shù)據(jù)包的傳輸順序和幀的時(shí)間戳,所以研究了下RFC3550協(xié)議,采用RTP包封裝視頻幀。
并未全面深究,所以未使用SSRC和CSRC,因?yàn)椴淮_切了解其用意。不過目前的實(shí)現(xiàn)情況已經(jīng)足夠了。

復(fù)制代碼 代碼如下:

/// <summary>
   /// RTP(RFC3550)協(xié)議數(shù)據(jù)包
   /// </summary>
   /// <remarks>
   /// The RTP header has the following format:
   ///  0                   1                   2                   3
   ///  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
   /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   /// |V=2|P|X| CC    |M| PT          | sequence number               |
   /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   /// | timestamp                                                     |
   /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   /// | synchronization source (SSRC) identifier                      |
   /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
   /// | contributing source (CSRC) identifiers                        |
   /// | ....                                                          |
   /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   /// </remarks>
   public class RtpPacket
   {
     /// <summary>
     /// version (V): 2 bits
     /// RTP版本標(biāo)識(shí),當(dāng)前規(guī)范定義值為2.
     /// This field identifies the version of RTP. The version defined by this specification is two (2).
     /// (The value 1 is used by the first draft version of RTP and the value 0 is used by the protocol
     /// initially implemented in the /vat" audio tool.)
     /// </summary>
     public int Version { get { return 2; } }

     /// <summary>
     /// padding (P):1 bit
     /// 如果設(shè)定padding,在報(bào)文的末端就會(huì)包含一個(gè)或者多個(gè)padding 字節(jié),這不屬于payload。
     /// 最后一個(gè)字節(jié)的padding 有一個(gè)計(jì)數(shù)器,標(biāo)識(shí)需要忽略多少個(gè)padding 字節(jié)(包括自己)。
     /// 一些加密算法可能需要固定塊長(zhǎng)度的padding,或者是為了在更低層數(shù)據(jù)單元中攜帶一些RTP 報(bào)文。
     /// If the padding bit is set, the packet contains one or more additional padding octets at the
     /// end which are not part of the payload. The last octet of the padding contains a count of
     /// how many padding octets should be ignored, including itself. Padding may be needed by
     /// some encryption algorithms with fixed block sizes or for carrying several RTP packets in a
     /// lower-layer protocol data unit.
     /// </summary>
     public int Padding { get { return 0; } }

     /// <summary>
     /// extension (X):1 bit
     /// 如果設(shè)定了extension 位,定長(zhǎng)頭字段后面會(huì)有一個(gè)頭擴(kuò)展。
     /// If the extension bit is set, the fixed header must be followed by exactly one header extensio.
     /// </summary>
     public int Extension { get { return 0; } }

     /// <summary>
     /// CSRC count (CC):4 bits
     /// CSRC count 標(biāo)識(shí)了定長(zhǎng)頭字段中包含的CSRC identifier 的數(shù)量。
     /// The CSRC count contains the number of CSRC identifiers that follow the fixed header.
     /// </summary>
     public int CC { get { return 0; } }

     /// <summary>
     /// marker (M):1 bit
     /// marker 是由一個(gè)profile 定義的。用來允許標(biāo)識(shí)在像報(bào)文流中界定幀界等的事件。
     /// 一個(gè)profile 可能定義了附加的標(biāo)識(shí)位或者通過修改payload type 域中的位數(shù)量來指定沒有標(biāo)識(shí)位.
     /// The interpretation of the marker is defined by a profile. It is intended to allow significant
     /// events such as frame boundaries to be marked in the packet stream. A profile may define
     /// additional marker bits or specify that there is no marker bit by changing the number of bits
     /// in the payload type field.
     /// </summary>
     public int Marker { get { return 0; } }

     /// <summary>
     /// payload type (PT):7 bits
     /// 這個(gè)字段定一個(gè)RTPpayload 的格式和在應(yīng)用中定義解釋。
     /// profile 可能指定一個(gè)從payload type 碼字到payload format 的默認(rèn)靜態(tài)映射。
     /// 也可以通過non-RTP 方法來定義附加的payload type 碼字(見第3 章)。
     /// 在 RFC 3551[1]中定義了一系列的默認(rèn)音視頻映射。
     /// 一個(gè)RTP 源有可能在會(huì)話中改變payload type,但是這個(gè)域在復(fù)用獨(dú)立的媒體時(shí)是不同的。(見5.2 節(jié))。
     /// 接收者必須忽略它不識(shí)別的payload type。
     /// This field identifies the format of the RTP payload and determines its interpretation by the
     /// application. A profile may specify a default static mapping of payload type codes to payload
     /// formats. Additional payload type codes may be defined dynamically through non-RTP means
     /// (see Section 3). A set of default mappings for audio and video is specified in the companion
     /// RFC 3551 [1]. An RTP source may change the payload type during a session, but this field
     /// should not be used for multiplexing separate media streams (see Section 5.2).
     /// A receiver must ignore packets with payload types that it does not understand.
     /// </summary>
     public RtpPayloadType PayloadType { get; private set; }

     /// <summary>
     /// sequence number:16 bits
     /// 每發(fā)送一個(gè)RTP 數(shù)據(jù)報(bào)文序列號(hào)值加一,接收者也可用來檢測(cè)丟失的包或者重建報(bào)文序列。
     /// 初始的值是隨機(jī)的,這樣就使得known-plaintext 攻擊更加困難, 即使源并沒有加密(見9。1),
     /// 因?yàn)橐ㄟ^的translator 會(huì)做這些事情。關(guān)于選擇隨機(jī)數(shù)方面的技術(shù)見[17]。
     /// The sequence number increments by one for each RTP data packet sent, and may be used
     /// by the receiver to detect packet loss and to restore packet sequence. The initial value of the
     /// sequence number should be random (unpredictable) to make known-plaintext attacks on
     /// encryption more dificult, even if the source itself does not encrypt according to the method
     /// in Section 9.1, because the packets may flow through a translator that does. Techniques for
     /// choosing unpredictable numbers are discussed in [17].
     /// </summary>
     public int SequenceNumber { get; private set; }

     /// <summary>
     /// timestamp:32 bits
     /// timestamp 反映的是RTP 數(shù)據(jù)報(bào)文中的第一個(gè)字段的采樣時(shí)刻的時(shí)間瞬時(shí)值。
     /// 采樣時(shí)間值必須是從恒定的和線性的時(shí)間中得到以便于同步和jitter 計(jì)算(見第6.4.1 節(jié))。
     /// 必須保證同步和測(cè)量保溫jitter 到來所需要的時(shí)間精度(一幀一個(gè)tick 一般情況下是不夠的)。
     /// 時(shí)鐘頻率是與payload 所攜帶的數(shù)據(jù)格式有關(guān)的,在profile 中靜態(tài)的定義或是在定義格式的payload format 中,
     /// 或通過non-RTP 方法所定義的payload format 中動(dòng)態(tài)的定義。如果RTP 報(bào)文周期的生成,就采用虛擬的(nominal)
     /// 采樣時(shí)鐘而不是從系統(tǒng)時(shí)鐘讀數(shù)。例如,在固定比特率的音頻中,timestamp 時(shí)鐘會(huì)在每個(gè)采樣周期時(shí)加一。
     /// 如果音頻應(yīng)用中從輸入設(shè)備中讀入160 個(gè)采樣周期的塊,the timestamp 就會(huì)每一塊增加160,
     /// 而不管塊是否傳輸了或是丟棄了。
     /// 對(duì)于序列號(hào)來說,timestamp 初始值是隨機(jī)的。只要它們是同時(shí)(邏輯上)同時(shí)生成的,
     /// 這些連續(xù)的的 RTP 報(bào)文就會(huì)有相同的timestamp,
     /// 例如,同屬一個(gè)視頻幀。正像在MPEG 中內(nèi)插視頻幀一樣,
     /// 連續(xù)的但不是按順序發(fā)送的RTP 報(bào)文可能含有相同的timestamp。
     /// The timestamp reflects the sampling instant of the first octet in the RTP data packet. The
     /// sampling instant must be derived from a clock that increments monotonically and linearly
     /// in time to allow synchronization and jitter calculations (see Section 6.4.1). The resolution
     /// of the clock must be suficient for the desired synchronization accuracy and for measuring
     /// packet arrival jitter (one tick per video frame is typically not suficient). The clock frequency
     /// is dependent on the format of data carried as payload and is specified statically in the profile
     /// or payload format specification that defines the format, or may be specified dynamically for
     /// payload formats defined through non-RTP means. If RTP packets are generated periodically,
     /// the nominal sampling instant as determined from the sampling clock is to be used, not a
     /// reading of the system clock. As an example, for fixed-rate audio the timestamp clock would
     /// likely increment by one for each sampling period. If an audio application reads blocks covering
     /// 160 sampling periods from the input device, the timestamp would be increased by 160 for
     /// each such block, regardless of whether the block is transmitted in a packet or dropped as silent.
     /// </summary>
     public long Timestamp { get; private set; }

     /// <summary>
     /// SSRC:32 bits
     /// SSRC 域識(shí)別同步源。為了防止在一個(gè)會(huì)話中有相同的同步源有相同的SSRC identifier,
     /// 這個(gè)identifier 必須隨機(jī)選取。
     /// 生成隨機(jī) identifier 的算法見目錄A.6 。雖然選擇相同的identifier 概率很小,
     /// 但是所有的RTP implementation 必須檢測(cè)和解決沖突。
     /// 第8 章描述了沖突的概率和解決機(jī)制和RTP 級(jí)的檢測(cè)機(jī)制,根據(jù)唯一的 SSRCidentifier 前向循環(huán)。
     /// 如果有源改變了它的源傳輸?shù)刂罚?BR>     /// 就必須為它選擇一個(gè)新的SSRCidentifier 來避免被識(shí)別為循環(huán)過的源(見第8.2 節(jié))。
     /// The SSRC field identifies the synchronization source. This identifier should be chosen
     /// randomly, with the intent that no two synchronization sources within the same RTP session
     /// will have the same SSRC identifier. An example algorithm for generating a random identifier
     /// is presented in Appendix A.6. Although the probability of multiple sources choosing the same
     /// identifier is low, all RTP implementations must be prepared to detect and resolve collisions.
     /// Section 8 describes the probability of collision along with a mechanism for resolving collisions
     /// and detecting RTP-level forwarding loops based on the uniqueness of the SSRC identifier. If
     /// a source changes its source transport address, it must also choose a new SSRC identifier to
     /// avoid being interpreted as a looped source (see Section 8.2).
     /// </summary>
     public int SSRC { get { return 0; } }

     /// <summary>
     /// 每一個(gè)RTP包中都有前12個(gè)字節(jié)定長(zhǎng)的頭字段
     /// The first twelve octets are present in every RTP packet
     /// </summary>
     public const int HeaderSize = 12;
     /// <summary>
     /// RTP消息頭
     /// </summary>
     private byte[] _header;
     /// <summary>
     /// RTP消息頭
     /// </summary>
     public byte[] Header { get { return _header; } }

     /// <summary>
     /// RTP有效載荷長(zhǎng)度
     /// </summary>
     private int _payloadSize;
     /// <summary>
     /// RTP有效載荷長(zhǎng)度
     /// </summary>
     public int PayloadSize { get { return _payloadSize; } }

     /// <summary>
     /// RTP有效載荷
     /// </summary>
     private byte[] _payload;
     /// <summary>
     /// RTP有效載荷
     /// </summary>
     public byte[] Payload { get { return _payload; } }

     /// <summary>
     /// RTP消息總長(zhǎng)度,包括Header和Payload
     /// </summary>
     public int Length { get { return HeaderSize + PayloadSize; } }

     /// <summary>
     /// RTP(RFC3550)協(xié)議數(shù)據(jù)包
     /// </summary>
     /// <param name="playloadType">數(shù)據(jù)報(bào)文有效載荷類型</param>
     /// <param name="sequenceNumber">數(shù)據(jù)報(bào)文序列號(hào)值</param>
     /// <param name="timestamp">數(shù)據(jù)報(bào)文采樣時(shí)刻</param>
     /// <param name="data">數(shù)據(jù)</param>
     /// <param name="dataSize">數(shù)據(jù)長(zhǎng)度</param>
     public RtpPacket(
       RtpPayloadType playloadType,
       int sequenceNumber,
       long timestamp,
       byte[] data,
       int dataSize)
     {
       // fill changing header fields
       SequenceNumber = sequenceNumber;
       Timestamp = timestamp;
       PayloadType = playloadType;

       // build the header bistream
       _header = new byte[HeaderSize];

       // fill the header array of byte with RTP header fields
       _header[0] = (byte)((Version << 6) | (Padding << 5) | (Extension << 4) | CC);
       _header[1] = (byte)((Marker << 7) | (int)PayloadType);
       _header[2] = (byte)(SequenceNumber >> 8);
       _header[3] = (byte)(SequenceNumber);
       for (int i = 0; i < 4; i++)
       {
         _header[7 - i] = (byte)(Timestamp >> (8 * i));
       }
       for (int i = 0; i < 4; i++)
       {
         _header[11 - i] = (byte)(SSRC >> (8 * i));
       }

       // fill the payload bitstream
       _payload = new byte[dataSize];
       _payloadSize = dataSize;

       // fill payload array of byte from data (given in parameter of the constructor)
       Array.Copy(data, 0, _payload, 0, dataSize);
     }

     /// <summary>
     /// RTP(RFC3550)協(xié)議數(shù)據(jù)包
     /// </summary>
     /// <param name="playloadType">數(shù)據(jù)報(bào)文有效載荷類型</param>
     /// <param name="sequenceNumber">數(shù)據(jù)報(bào)文序列號(hào)值</param>
     /// <param name="timestamp">數(shù)據(jù)報(bào)文采樣時(shí)刻</param>
     /// <param name="frame">圖片</param>
     public RtpPacket(
       RtpPayloadType playloadType,
       int sequenceNumber,
       long timestamp,
       Image frame)
     {
       // fill changing header fields
       SequenceNumber = sequenceNumber;
       Timestamp = timestamp;
       PayloadType = playloadType;

       // build the header bistream
       _header = new byte[HeaderSize];

       // fill the header array of byte with RTP header fields
       _header[0] = (byte)((Version << 6) | (Padding << 5) | (Extension << 4) | CC);
       _header[1] = (byte)((Marker << 7) | (int)PayloadType);
       _header[2] = (byte)(SequenceNumber >> 8);
       _header[3] = (byte)(SequenceNumber);
       for (int i = 0; i < 4; i++)
       {
         _header[7 - i] = (byte)(Timestamp >> (8 * i));
       }
       for (int i = 0; i < 4; i++)
       {
         _header[11 - i] = (byte)(SSRC >> (8 * i));
       }

       // fill the payload bitstream
       using (MemoryStream ms = new MemoryStream())
       {
         frame.Save(ms, ImageFormat.Jpeg);
         _payload = ms.ToArray();
         _payloadSize = _payload.Length;
       }
     }

     /// <summary>
     /// RTP(RFC3550)協(xié)議數(shù)據(jù)包
     /// </summary>
     /// <param name="packet">數(shù)據(jù)包</param>
     /// <param name="packetSize">數(shù)據(jù)包長(zhǎng)度</param>
     public RtpPacket(byte[] packet, int packetSize)
     {
       //check if total packet size is lower than the header size
       if (packetSize >= HeaderSize)
       {
         //get the header bitsream
         _header = new byte[HeaderSize];
         for (int i = 0; i < HeaderSize; i++)
         {
           _header[i] = packet[i];
         }

         //get the payload bitstream
         _payloadSize = packetSize - HeaderSize;
         _payload = new byte[_payloadSize];
         for (int i = HeaderSize; i < packetSize; i++)
         {
           _payload[i - HeaderSize] = packet[i];
         }

         //interpret the changing fields of the header
         PayloadType = (RtpPayloadType)(_header[1] & 127);
         SequenceNumber = UnsignedInt(_header[3]) + 256 * UnsignedInt(_header[2]);
         Timestamp = UnsignedInt(_header[7])
           + 256 * UnsignedInt(_header[6])
           + 65536 * UnsignedInt(_header[5])
           + 16777216 * UnsignedInt(_header[4]);
       }
     }

     /// <summary>
     /// 將消息轉(zhuǎn)換成byte數(shù)組
     /// </summary>
     /// <returns>消息byte數(shù)組</returns>
     public byte[] ToArray()
     {
       byte[] packet = new byte[Length];

       Array.Copy(_header, 0, packet, 0, HeaderSize);
       Array.Copy(_payload, 0, packet, HeaderSize, PayloadSize);

       return packet;
     }

     /// <summary>
     /// 將消息體轉(zhuǎn)換成圖片
     /// </summary>
     /// <returns>圖片</returns>
     public Bitmap ToBitmap()
     {
       return new Bitmap(new MemoryStream(_payload));
     }

     /// <summary>
     /// 將消息體轉(zhuǎn)換成圖片
     /// </summary>
     /// <returns>圖片</returns>
     public Image ToImage()
     {
       return Image.FromStream(new MemoryStream(_payload));
     }

     /// <summary>
     /// 將圖片轉(zhuǎn)換成消息
     /// </summary>
     /// <param name="playloadType">數(shù)據(jù)報(bào)文有效載荷類型</param>
     /// <param name="sequenceNumber">數(shù)據(jù)報(bào)文序列號(hào)值</param>
     /// <param name="timestamp">數(shù)據(jù)報(bào)文采樣時(shí)刻</param>
     /// <param name="frame">圖片幀</param>
     /// <returns>
     /// RTP消息
     /// </returns>
     public static RtpPacket FromImage(
       RtpPayloadType playloadType,
       int sequenceNumber,
       long timestamp,
       Image frame)
     {
       return new RtpPacket(playloadType, sequenceNumber, timestamp, frame);
     }

     /// <summary>
     /// return the unsigned value of 8-bit integer nb
     /// </summary>
     /// <param name="nb"></param>
     /// <returns></returns>
     private static int UnsignedInt(int nb)
     {
       if (nb >= 0)
         return (nb);
       else
         return (256 + nb);
     }
   }

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 亚洲精品一区二区三区在线看 | 午夜视频国产 | 欧美日韩经典在线 | 久久97视频| 国产毛片aaa一区二区三区视频 | 香蕉视频h | 一色屋任你操 | 日本a∨精品中文字幕在线 欧美1—12sexvideos | 欧美 日韩 国产 在线 | 欧洲伊人网 | 中文字幕 亚洲一区 | 久久免费视频7 | 色啪综合 | 12av毛片 | 草草久久久 | 一本色道久久99精品综合蜜臀 | av亚洲在线观看 | 成人免费看毛片 | 中国嫩模一级毛片 | 色视频在线| 亚洲午夜在线视频 | 中文字幕爱爱视频 | 成人毛片视频在线观看 | 在线a毛片免费视频观看 | 精品国产视频一区二区三区 | 一区国产视频 | 精品国产一区二区三区成人影院 | 欧美精品毛片 | 欧美一级黄 | 在线天堂中文在线资源网 | 亚洲第一激情网 | 狼人狠狠干| 亚洲国产精品高潮呻吟久久 | 中文字幕精品一区久久久久 | 欧美乱码精品一区 | 亚洲免费网站 | www.17c亚洲蜜桃| 蜜桃久久一区二区三区 | 毛片免费在线 | 国产一精品久久99无吗一高潮 | 国产精品欧美久久久久一区二区 |