forked from sipsorcery-org/sipsorcery
/
RTPHeader.cs
379 lines (332 loc) · 15.7 KB
/
RTPHeader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
//-----------------------------------------------------------------------------
// Filename: RTPHeader.cs
//
// Description: RTP Header as defined in RFC3550.
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
//
// History:
// 22 May 2005 Aaron Clauson Created, Dublin, Ireland.
// 11 Aug 2019 Aaron Clauson Added full license header.
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Linq;
using SIPSorcery.net.RTP;
using SIPSorcery.Sys;
namespace SIPSorcery.Net
{
public class RTPHeader
{
public const int MIN_HEADER_LEN = 12;
public const int RTP_VERSION = 2;
private const int ONE_BYTE_EXTENSION_PROFILE = 0xBEDE;
public int Version = RTP_VERSION; // 2 bits.
public int PaddingFlag = 0; // 1 bit.
public int HeaderExtensionFlag = 0; // 1 bit.
public int CSRCCount = 0; // 4 bits
public int MarkerBit = 0; // 1 bit.
public int PayloadType = 0; // 7 bits.
public UInt16 SequenceNumber; // 16 bits.
public uint Timestamp; // 32 bits.
public uint SyncSource; // 32 bits.
public int[] CSRCList; // 32 bits.
public UInt16 ExtensionProfile; // 16 bits.
public UInt16 ExtensionLength; // 16 bits, length of the header extensions in 32 bit words.
public byte[] ExtensionPayload;
public int PayloadSize;
public byte PaddingCount;
public DateTime ReceivedTime;
public int Length
{
get { return MIN_HEADER_LEN + (CSRCCount * 4) + ((HeaderExtensionFlag == 0) ? 0 : 4 + (ExtensionLength * 4)); }
}
public RTPHeader()
{
SequenceNumber = Crypto.GetRandomUInt16();
SyncSource = Crypto.GetRandomUInt();
Timestamp = Crypto.GetRandomUInt();
}
/// <summary>
/// Extract and load the RTP header from an RTP packet.
/// </summary>
/// <param name="packet"></param>
public RTPHeader(byte[] packet)
{
if (packet.Length < MIN_HEADER_LEN)
{
throw new ApplicationException("The packet did not contain the minimum number of bytes for an RTP header packet.");
}
UInt16 firstWord = BitConverter.ToUInt16(packet, 0);
if (BitConverter.IsLittleEndian)
{
firstWord = NetConvert.DoReverseEndian(firstWord);
SequenceNumber = NetConvert.DoReverseEndian(BitConverter.ToUInt16(packet, 2));
Timestamp = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 4));
SyncSource = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 8));
}
else
{
SequenceNumber = BitConverter.ToUInt16(packet, 2);
Timestamp = BitConverter.ToUInt32(packet, 4);
SyncSource = BitConverter.ToUInt32(packet, 8);
}
Version = firstWord >> 14;
PaddingFlag = (firstWord >> 13) & 0x1;
HeaderExtensionFlag = (firstWord >> 12) & 0x1;
CSRCCount = (firstWord >> 8) & 0xf;
MarkerBit = (firstWord >> 7) & 0x1;
PayloadType = firstWord & 0x7f;
int headerExtensionLength = 0;
int headerAndCSRCLength = 12 + 4 * CSRCCount;
if (HeaderExtensionFlag == 1 && (packet.Length >= (headerAndCSRCLength + 4)))
{
if (BitConverter.IsLittleEndian)
{
ExtensionProfile = NetConvert.DoReverseEndian(BitConverter.ToUInt16(packet, 12 + 4 * CSRCCount));
headerExtensionLength += 2;
ExtensionLength = NetConvert.DoReverseEndian(BitConverter.ToUInt16(packet, 14 + 4 * CSRCCount));
headerExtensionLength += 2 + ExtensionLength * 4;
}
else
{
ExtensionProfile = BitConverter.ToUInt16(packet, 12 + 4 * CSRCCount);
headerExtensionLength += 2;
ExtensionLength = BitConverter.ToUInt16(packet, 14 + 4 * CSRCCount);
headerExtensionLength += 2 + ExtensionLength * 4;
}
if (ExtensionLength > 0 && packet.Length >= (headerAndCSRCLength + 4 + ExtensionLength * 4))
{
ExtensionPayload = new byte[ExtensionLength * 4];
Buffer.BlockCopy(packet, headerAndCSRCLength + 4, ExtensionPayload, 0, ExtensionLength * 4);
}
}
PayloadSize = packet.Length - (headerAndCSRCLength + headerExtensionLength);
if (PaddingFlag == 1)
{
PaddingCount = packet[packet.Length - 1];
if (PaddingCount < PayloadSize)//Prevent some protocol attacks
{
PayloadSize -= PaddingCount;
}
}
}
public byte[] GetHeader(UInt16 sequenceNumber, uint timestamp, uint syncSource)
{
SequenceNumber = sequenceNumber;
Timestamp = timestamp;
SyncSource = syncSource;
return GetBytes();
}
public byte[] GetBytes()
{
byte[] header = new byte[Length];
UInt16 firstWord = Convert.ToUInt16(Version * 16384 + PaddingFlag * 8192 + HeaderExtensionFlag * 4096 + CSRCCount * 256 + MarkerBit * 128 + PayloadType);
if (BitConverter.IsLittleEndian)
{
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(firstWord)), 0, header, 0, 2);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SequenceNumber)), 0, header, 2, 2);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(Timestamp)), 0, header, 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SyncSource)), 0, header, 8, 4);
if (HeaderExtensionFlag == 1)
{
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(ExtensionProfile)), 0, header, 12 + 4 * CSRCCount, 2);
Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(ExtensionLength)), 0, header, 14 + 4 * CSRCCount, 2);
}
}
else
{
Buffer.BlockCopy(BitConverter.GetBytes(firstWord), 0, header, 0, 2);
Buffer.BlockCopy(BitConverter.GetBytes(SequenceNumber), 0, header, 2, 2);
Buffer.BlockCopy(BitConverter.GetBytes(Timestamp), 0, header, 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(SyncSource), 0, header, 8, 4);
if (HeaderExtensionFlag == 1)
{
Buffer.BlockCopy(BitConverter.GetBytes(ExtensionProfile), 0, header, 12 + 4 * CSRCCount, 2);
Buffer.BlockCopy(BitConverter.GetBytes(ExtensionLength), 0, header, 14 + 4 * CSRCCount, 2);
}
}
if (ExtensionLength > 0 && ExtensionPayload != null)
{
Buffer.BlockCopy(ExtensionPayload, 0, header, 16 + 4 * CSRCCount, ExtensionLength * 4);
}
return header;
}
private RTPHeaderExtensionData GetExtensionAtPosition(ref int position, int id, int len, RTPHeaderExtensionType type, out bool invalid)
{
RTPHeaderExtensionData ext = null;
if (ExtensionPayload != null)
{
if (id != 0)
{
if (position + len > ExtensionPayload.Length)
{
// invalid extension
invalid = true;
return null;
}
ext = new RTPHeaderExtensionData(id, ExtensionPayload.Skip(position).Take(len).ToArray(), type);
position += len;
}
else
{
position++;
}
while ((position < ExtensionPayload.Length) && (ExtensionPayload[position] == 0))
{
position++;
}
}
invalid = false;
return ext;
}
public List<RTPHeaderExtensionData> GetHeaderExtensions()
{
var extensions = new List<RTPHeaderExtensionData>();
RTPHeaderExtensionData extension = null;
var i = 0;
bool invalid = false;
if (ExtensionPayload != null)
{
while (i + 1 < ExtensionPayload.Length)
{
if (HasOneByteExtension())
{
var id = (ExtensionPayload[i] & 0xF0) >> 4;
var len = (ExtensionPayload[i] & 0x0F) + 1;
i++;
extension = GetExtensionAtPosition(ref i, id, len, RTPHeaderExtensionType.OneByte, out invalid);
}
else if (HasTwoByteExtension())
{
var id = ExtensionPayload[i++];
var len = ExtensionPayload[i++] + 1;
extension = GetExtensionAtPosition(ref i, id, len, RTPHeaderExtensionType.TwoByte, out invalid);
}
else
{
//We don't recognize this extension, ignore it
break;
}
if (!invalid && extension != null)
{
extensions.Add(extension);
}
}
}
return extensions;
}
private bool HasOneByteExtension()
{
return ExtensionProfile == ONE_BYTE_EXTENSION_PROFILE;
}
private bool HasTwoByteExtension()
{
return (ExtensionProfile & 0b1111111111110000) == 0b0001000000000000;
}
public static bool TryParse(
ReadOnlySpan<byte> buffer,
out RTPHeader header,
out int consumed)
{
header = new RTPHeader();
consumed = 0;
int offset = 0;
if (buffer.Length < MIN_HEADER_LEN)
{
return false;
}
var firstWord = BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(offset));
offset += 2;
header.SequenceNumber =BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(offset));
offset += 2;
header.Timestamp = BinaryPrimitives.ReadUInt32BigEndian(buffer.Slice(offset));
offset += 4;
header.SyncSource = BinaryPrimitives.ReadUInt32BigEndian(buffer.Slice(offset));
offset += 4;
header.Version = firstWord >> 14;
header.PaddingFlag = (firstWord >> 13) & 0x1;
header.HeaderExtensionFlag = (firstWord >> 12) & 0x1;
header.CSRCCount = (firstWord >> 8) & 0xf;
header.MarkerBit = (firstWord >> 7) & 0x1;
header.PayloadType = firstWord & 0x7f;
int headerAndCSRCLength = offset + 4 * header.CSRCCount;
if (header.HeaderExtensionFlag == 1 && (buffer.Length >= (headerAndCSRCLength + 4)))
{
header.ExtensionProfile =BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(offset));
offset += 2;
header.ExtensionLength = BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(offset));
offset += 2 + header.ExtensionLength * 4;
var extensionPayloadLength = header.ExtensionLength * 4;
if (header.ExtensionLength > 0 && buffer.Length >= extensionPayloadLength)
{
header.ExtensionPayload = new byte[extensionPayloadLength];
Buffer.BlockCopy(buffer.ToArray(), headerAndCSRCLength + 4, header.ExtensionPayload, 0, extensionPayloadLength);
}
}
header.PayloadSize = buffer.Length - offset;
if (header.PaddingFlag == 1)
{
// ReSharper disable once UseIndexFromEndExpression
header.PaddingCount = buffer[buffer.Length - 1];
if (header.PaddingCount < header.PayloadSize)//Prevent some protocol attacks
{
header.PayloadSize -= header.PaddingCount;
}
}
consumed = offset;
return header.PayloadSize>=0;
}
// DateTimeOffset.UnixEpoch only available in newer target frameworks
private static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
// inspired by https://github.com/pion/rtp/blob/master/abssendtimeextension.go
internal static byte[] AbsSendTime(DateTimeOffset now)
{
ulong unixNanoseconds = (ulong)((now - UnixEpoch).Ticks * 100L);
var seconds = unixNanoseconds / (ulong)1e9;
seconds += 0x83AA7E80UL; // offset in seconds between unix epoch and ntp epoch
var f = unixNanoseconds % (ulong)1e9;
f <<= 32;
f /= (ulong)1e9;
seconds <<= 32;
var ntp = seconds | f;
var abs = ntp >> 14;
var length = 2; // extension length (3-1)
return new[]
{
(byte)((SDPMediaAnnouncement.RTP_HEADER_EXTENSION_ID_ABS_SEND_TIME << 4) | length),
(byte)((abs & 0xff0000UL) >> 16),
(byte)((abs & 0xff00UL) >> 8),
(byte)(abs & 0xffUL)
};
}
/*
An example header extension, with three extension elements, some
padding, and including the required RTP fields, follows:
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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 0xBE | 0xDE | length=3 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ID | L=0 | data | ID | L=1 | data... |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ...data | 0 (pad) | 0 (pad) | ID | L=3 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| data |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
// https://datatracker.ietf.org/doc/html/rfc5285#section-4.2
public void AddAbsSendTimeExtension()
{
HeaderExtensionFlag = 1;
ExtensionProfile = ONE_BYTE_EXTENSION_PROFILE;
ExtensionLength = 1; // only abs-send-time for now
ExtensionPayload = AbsSendTime(DateTimeOffset.Now);
}
}
}