-
Notifications
You must be signed in to change notification settings - Fork 0
/
RtpListener.cs
595 lines (482 loc) · 20.8 KB
/
RtpListener.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using System.Net;
namespace Vs.Provider.RtpLib.MSR.LST.Net.Rtp
{
/// <summary>
/// Listens for packets from the network and distributes them to the appropriate RtpStream
/// </summary>
internal class RtpListener: IDisposable
{
public interface IRtpSession
{
RtpStream GetStream(uint ssrc, IPAddress ip);
void LogEvent(string source, string msg, EventLogEntryType et, int id);
void RaiseInvalidPacketEvent(string msg);
int DropPacketsPercent{get;}
Random Rnd{get;}
SdesData Sdes{get;}
System.Net.IPEndPoint RtpEndPoint{get;}
}
#region Statics
// The growth of the buffer pool is limited to ~= 95MB of data active at one time
//
// 64 packets (PoolInitialSize) Doubled (PoolGrowthFactor) 10 times (PoolMaxGrows)
// 64 * 2 * 10 = 65,536 buffers * ~1.5 K per buffer ~= 95MB of data.
/// <summary>
/// Initial number of pre-allocated buffers for receiving data
/// </summary>
private const int PoolInitialSize = 64;
/// <summary>
/// Multiplier - amount of buffers to grow the pools by when the pool is empty
/// </summary>
private const int PoolGrowthFactor = 2;
/// <summary>
/// How many times do we want the pools to grow by GrowthFactor before we consider
/// the situation to be out of control (unbounded)
/// </summary>
private const int PoolMaxGrows = 10;
#endregion Statics
#region Members
/// <summary>
/// Reference back to the RtpSession that created this Listener
/// See IRtpSession for the methods used
/// </summary>
private IRtpSession rtpSession = null;
/// <summary>
/// Queue that holds a pool of BufferChunks for receiving data off the wire
/// </summary>
private Stack bufferPool = Stack.Synchronized(new Stack(PoolInitialSize));
/// <summary>
/// How many packets has this listener allocated
/// </summary>
private int packets = PoolInitialSize;
/// <summary>
/// Number of times we have grown the bufferPool
/// </summary>
private int poolGrows = 0;
/// <summary>
/// Queue that holds all RtpPackets that have been received but not yet forwarded to the
/// RtpStreams for processing
/// </summary>
private Queue receivedPackets = Queue.Synchronized(new Queue());
/// <summary>
/// Receives packets off the network and stores them for sorting and distribution
/// </summary>
private Thread threadReceivePackets;
/// <summary>
/// Sorts the packets which have been received from the network and forwards them on to the
/// appropriate RtpStream for processing
/// </summary>
private Thread threadDistributePackets;
/// <summary>
/// A socket that listens for incoming multicast Rtp packets.
/// </summary>
private INetworkListener rtpNetworkListener = null;
/// <summary>
/// Signals the Distribution thread it has work to do
/// </summary>
private AutoResetEvent newPacket = new AutoResetEvent(false);
/// <summary>
/// Local performance counter object
/// </summary>
private RtpListenerPC pc;
/// <summary>
/// Lock to make sure performance counters are valid during use
/// </summary>
private object pcLock = new object();
/// <summary>
/// The number of packets the RtpListener has received off the wire
/// </summary>
private uint pcPackets;
/// <summary>
/// The number of packets the RtpListener has received for an unassociated stream
/// </summary>
private uint pcStreamlessPackets;
#if FaultInjection
/// <summary>
/// Keep track of how many bytes we purposefully dropped
/// </summary>
private int pcDroppedDataBytes;
/// <summary>
/// Keep track of how many packets we purposefully dropped
/// </summary>
private int pcDroppedDataPackets;
/// <summary>
/// Keep track of how many bytes we purposefully dropped
/// </summary>
private int pcDroppedFecBytes;
/// <summary>
/// Keep track of how many packets we purposefully dropped
/// </summary>
private int pcDroppedFecPackets;
#endif
public delegate void ReturnBufferHandler(BufferChunk buffer);
private ReturnBufferHandler returnBufferHandler;
public delegate BufferChunk GetBufferHandler();
private GetBufferHandler getBufferHandler;
#endregion Members
#region Constructors
public RtpListener(RtpSession rtpSession)
{
this.rtpSession = rtpSession;
returnBufferHandler = new ReturnBufferHandler(ReturnBuffer);
getBufferHandler = new GetBufferHandler(GetBuffer);
InitializeBufferPool();
InitializePerformanceCounters();
InitializeNetwork();
InitializeThreads();
}
public void Dispose()
{
GC.SuppressFinalize(this);
try
{
DisposePerformanceCounters();
DisposeThreads();
DisposeNetwork();
DisposeBufferPool();
}
catch(Exception e)
{
LogEvent("Error Disposing RtpListener" +
Environment.NewLine + e.ToString(),
EventLogEntryType.Error, (int)RtpEL.ID.Error);
}
}
~RtpListener()
{
Dispose();
}
#endregion
#region Public
public ReturnBufferHandler ReturnBufferCallback
{
get{return returnBufferHandler;}
}
public GetBufferHandler GetBufferCallback
{
get{return getBufferHandler;}
}
/// <summary>
/// Updates performance counters
/// </summary>
/// <param name="ms">An approximate delay in milli-seconds since the last update</param>
public void UpdatePerformanceCounters(int ms)
{
lock(pcLock)
{
if(pc != null)
{
int p = packets;
int q = bufferPool.Count;
pc[RtpListenerPC.ID.BufferPoolSize] = p;
pc[RtpListenerPC.ID.BuffersFree] = q;
pc[RtpListenerPC.ID.BuffersInUse] = p - q;
#if FaultInjection
int fecB = pcDroppedFecBytes;
int fecP = pcDroppedFecPackets;
int dataB = pcDroppedDataBytes;
int dataP = pcDroppedDataPackets;
pc[RtpListenerPC.ID.DroppedBytes] = fecB + dataB;
pc[RtpListenerPC.ID.DroppedPackets] = fecP + dataP;
pc[RtpListenerPC.ID.DroppedDataBytes] = dataB;
pc[RtpListenerPC.ID.DroppedDataPackets] = dataP;
pc[RtpListenerPC.ID.DroppedFecBytes] = fecB;
pc[RtpListenerPC.ID.DroppedFecPackets] = fecP;
#endif
pc[RtpListenerPC.ID.GrowthFactor] = PoolGrowthFactor;
pc[RtpListenerPC.ID.InitialBuffers] = PoolInitialSize;
pc[RtpListenerPC.ID.GrowthCount] = poolGrows;
pc[RtpListenerPC.ID.Packets] = pcPackets;
pc[RtpListenerPC.ID.StreamlessPackets] = pcStreamlessPackets;
}
}
}
#endregion Public
#region Private
#region BufferPool
/// <summary>
/// Grow the buffer pool
///
/// Called when all the previously allocated packets are in use. Unless we are handling a
/// huge frame (~= 95MB), it indicates a problem - like packets that aren't being returned
/// to the pool and so we put a limit on the growth.
/// </summary>
private void GrowBufferPool()
{
// Only allow one thread at a time to grow the pool (Receive or Distribute)
lock(bufferPool)
{
if(poolGrows < PoolMaxGrows)
{
// Check to see if the pool really needs to grow
// (in case two threads were waiting at the lock)
if(bufferPool.Count < packets / 4)
{
poolGrows++;
int packetsToAdd = (packets * PoolGrowthFactor) - packets;
for (int i = 0; i < packetsToAdd; i++)
{
ReturnBuffer(new BufferChunk(Rtp.MAX_PACKET_SIZE));
}
packets *= PoolGrowthFactor;
}
}
else
{
LogEvent("Trying to grow the buffer pool after PoolMaxGrows has been reached",
EventLogEntryType.Warning, (int)RtpEL.ID.UnboundedGrowth);
// Maybe enough packets have trickled in to continue
if(bufferPool.Count == 0)
{
throw new PoolExhaustedException("The RtpListener buffer pool was growing " +
"unbounded. We have stopped the receiving / distributing threads in order " +
"to prevent it from consuming all the RAM");
}
}
}
}
/// <summary>
/// Returns a BufferChunk from the pool, or grows the pool if need be
/// </summary>
/// <returns></returns>
private BufferChunk GetBuffer()
{
// NOTE: multi-threaded gambling:
// After a "risk assesment" of doing this with a lock, we opted for the performance
// of doing this "lockless" and letting us catch the exception, should it occur.
try
{
// *Attempt* to avoid InvalidOperationException, if possible
if( bufferPool.Count == 0 )
{
GrowBufferPool();
}
return (BufferChunk)bufferPool.Pop();
}
catch (InvalidOperationException)
{
GrowBufferPool();
return GetBuffer(); // Recursive Call
}
}
/// <summary>
/// This method is called to return buffers to the bufferPool
/// </summary>
/// <param name="buffer"></param>
private void ReturnBuffer(BufferChunk buffer)
{
buffer.Reset();
bufferPool.Push(buffer);
}
#endregion BufferPool
#region Initialize / Dispose
private void InitializeNetwork()
{
rtpNetworkListener = new UdpListener(rtpSession.RtpEndPoint, RtpSession.DefaultNetworkTimeout);
}
private void DisposeNetwork()
{
rtpNetworkListener.Dispose();
rtpNetworkListener = null;
}
private void InitializeBufferPool()
{
for (int i = 0; i < packets; i++)
{
ReturnBuffer(new BufferChunk(Rtp.MAX_PACKET_SIZE));
}
}
private void DisposeBufferPool()
{
bufferPool.Clear();
bufferPool = null;
}
private void InitializeThreads()
{
threadDistributePackets = new Thread(new ThreadStart(DistributePackets));
threadDistributePackets.IsBackground = true;
threadDistributePackets.Name = "RtpListener Distribute Packets";
threadDistributePackets.Start();
threadReceivePackets = new Thread(new ThreadStart(ReceivePackets));
threadReceivePackets.IsBackground = true;
threadReceivePackets.Name = "RtpListener Receive Packets";
threadReceivePackets.Start();
}
private void DisposeThreads()
{
threadDistributePackets.Abort();
threadDistributePackets = null;
threadReceivePackets.Abort();
threadReceivePackets = null;
}
private void InitializePerformanceCounters()
{
lock(pcLock)
{
pc = new RtpListenerPC(rtpSession.Sdes.CName + " - " + rtpSession.RtpEndPoint.ToString());
}
}
private void DisposePerformanceCounters()
{
lock(pcLock)
{
if(pc != null)
{
pc.Dispose();
pc = null;
}
}
}
#endregion Initialize / Dispose
#region Thread Methods
private void ReceivePackets()
{
BufferChunk bc = null;
while(true)
{
try
{
bc = GetBuffer();
EndPoint ep;
rtpNetworkListener.ReceiveFrom(bc, out ep);
receivedPackets.Enqueue(new object[] {bc, ep});
newPacket.Set();
unchecked{pcPackets++;}
}
catch(ThreadAbortException){}
catch(PoolExhaustedException e)
{
LogEvent(e.ToString(), EventLogEntryType.Error, (int)RtpEL.ID.UnboundedGrowth);
return; // Exit the thread gracefully
}
catch (System.Net.Sockets.SocketException e)
{
ReturnBuffer(bc);
// Something other than - No data received before timeout
if (e.ErrorCode != 10060)
{
Object[] args = new Object[]{this, new RtpEvents.HiddenSocketExceptionEventArgs((RtpSession)rtpSession, e)};
EventThrower.QueueUserWorkItem( new RtpEvents.RaiseEvent(RtpEvents.RaiseHiddenSocketExceptionEvent), args );
LogEvent(e.ToString(), EventLogEntryType.Error, (int)RtpEL.ID.Error);
}
}
catch(Exception e)
{
ReturnBuffer(bc);
LogEvent(e.ToString(), EventLogEntryType.Error, (int)RtpEL.ID.Error);
}
}
}
/// <summary>
/// DistributePackets is responsible for receiving all incoming packets on the Rtp Listener,
/// casting them into RtpPackets, creating new RtpStreams if one doesn't exist for the RtpPacket's SSRC,
/// then calling RtpStream.newPacket(rtpPacket) to place the RtpPacket into the RtpStream's Queue for processing.
/// </summary>
private void DistributePackets()
{
while (newPacket.WaitOne())
{
while(receivedPackets.Count > 0)
{
object[] ao = (object[])receivedPackets.Dequeue();
BufferChunk bc = (BufferChunk)ao[0];
IPEndPoint ep = (IPEndPoint)ao[1];
try
{
//Turn the raw UDP packet data into an Rtp packet
RtpPacketBase packet = new RtpPacketBase(bc);
// For now, we support 2 types of packets - RtpPacket and RtpPacketFec. If
// the number of packet types grows, we may need to push the casting onto
// the streams, since they know what type of packets they expect. For now
// we will handle the casting here. JVE 6/17/2004
if(packet.PayloadType == PayloadType.FEC)
{
packet = new RtpPacketFec(packet);
}
else
{
packet = new RtpPacket(packet);
}
#region Fault Injection
#if FaultInjection
if(rtpSession.DropPacketsPercent > 0 )
{
if (rtpSession.Rnd.Next(1,100) <= rtpSession.DropPacketsPercent)
{
if(packet.PayloadType == PayloadType.FEC)
{
RtpPacketFec fecPacket = (RtpPacketFec)packet;
string msg = string.Format(
"Dropping fec packet: {0}, FecIndex: {1}, DataRangeMin: {2}",
fecPacket.Sequence, fecPacket.FecIndex, fecPacket.DataRangeMin);
Trace.WriteLine(msg);
pcDroppedFecPackets++;
pcDroppedFecBytes += packet.PayloadSize;
}
else
{
RtpPacket dataPacket = (RtpPacket)packet;
string msg = string.Format(
"Dropping data packet: {0}, FecIndex: {1}, FrameIndex: {2}, TS: {3}",
dataPacket.Sequence, dataPacket.FecIndex, dataPacket.FrameIndex, dataPacket.TimeStamp);
Trace.WriteLine(msg);
pcDroppedDataPackets++;
pcDroppedDataBytes += packet.PayloadSize;
}
ReturnBuffer(bc);
continue;
}
}
#endif
#endregion Fault Injection
// Get the stream if it exists
RtpStream stream = rtpSession.GetStream(packet.SSRC, ep.Address);
if (stream != null)
{
stream.ProcessPacket(packet);
}
else
{
// Otherwise return the packet to the pool
ReturnBuffer(bc);
unchecked{pcStreamlessPackets++;}
}
}
catch(ThreadAbortException){}
catch (InvalidRtpPacketException e)
{
HandleInvalidPacket(bc, ep, e.ToString());
ReturnBuffer(bc);
}
catch(PoolExhaustedException e)
{
LogEvent(e.ToString(), EventLogEntryType.Error, (int)RtpEL.ID.UnboundedGrowth);
return; // Exit the thread gracefully
}
catch(Exception e)
{
ReturnBuffer(bc);
LogEvent(e.ToString(), EventLogEntryType.Error, (int)RtpEL.ID.Error);
}
}
}
}
#endregion Thread Methods
#region Logging
private void LogEvent(string msg, EventLogEntryType et, int id)
{
rtpSession.LogEvent("RtpListener", msg, et, id);
}
#endregion Logging
private void HandleInvalidPacket(BufferChunk packet, IPEndPoint src, string exception)
{
rtpSession.RaiseInvalidPacketEvent(string.Format("First byte: {0}, Source IP: {1}, " +
"Exception: {2}", packet.NextByte(), src, exception));
}
#endregion Private
}
}