-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathClientSession.cpp
1168 lines (1020 loc) · 43.3 KB
/
ClientSession.cpp
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* @APPLE_LICENSE_HEADER_START@
*
* Copyright (c) 1999-2008 Apple Inc. All Rights Reserved.
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*
*/
/*
File: ClientSession.cpp
Contains: .
*/
#include <arpa/inet.h>
//#include <stdlib.h>
#include "ClientSession.h"
#include "OSMemory.h"
#include "SafeStdLib.h"
#include "OSHeaders.h"
#include "OS.h"
#include "RTPPacket.h"
#include "RTCPPacket.h"
#include "RTCPRRPacket.h"
#include "RTCPAckPacketFmt.h"
#include "RTCPNADUPacketFmt.h"
//These two parameters governs how the client determines whether an incoming RTP packet is within the range of the sequence number or not.
enum {
kMaxDropOut = 3000, //The sequence number can be kMaxDropOut ahead of the reference.
kMaxMisorder = 100, //The sequence number can be kMaxMisorder behind of the reference.
kMaxUDPPacketSize = 1450
};
#define CLIENT_SESSION_DEBUG 0
static const SInt64 kMaxWaitTimeInMsec = 5000;
static const SInt64 kIdleTimeoutInMsec = 20000; // Time out in 20 seconds if nothing's doing
static const SInt16 kSanitySeqNumDifference = 3000; //how large a difference can two sequence number be and still be considered to be in range
UInt32 ClientSession::sActiveConnections = 0;
UInt32 ClientSession::sPlayingConnections = 0;
UInt32 ClientSession::sTotalConnectionAttempts = 0;
UInt32 ClientSession::sBytesReceived = 0;
UInt32 ClientSession::sPacketsReceived = 0;
char* ConvertBytesToCHexString( void* inValue, const UInt32 inValueLen)
{
static const char* kHEXChars={ "0123456789ABCDEF" };
UInt8* theDataPtr = (UInt8*) inValue;
UInt32 len = inValueLen *2;
char *theString = NEW char[len+1];
char *resultStr = theString;
if (theString != NULL)
{
UInt8 temp;
UInt32 count = 0;
for (count = 0; count < inValueLen; count++)
{
temp = *theDataPtr++;
*theString++ = kHEXChars[temp >> 4];
*theString++ = kHEXChars[temp & 0xF];
}
*theString = 0;
}
return resultStr;
}
ClientSession::ClientSession( UInt32 inAddr, UInt16 inPort, char* inURL,
ClientType inClientType,
UInt32 inDurationInSec, UInt32 inStartPlayTimeInSec,
UInt32 inRTCPIntervalInMS, UInt32 inOptionsIntervalInSec,
UInt32 inHTTPCookie, Bool16 inAppendJunkData, UInt32 inReadInterval,
UInt32 inSockRcvBufSize, Float32 inLateTolerance, char* inMetaInfoFields,
Float32 inSpeed, UInt32 verboseLevel, char* inPacketRangePlayHeader, UInt32 inOverbufferWindowSizeInK,
Bool16 sendOptions, Bool16 requestRandomData, SInt32 randomDataSize, Bool16 enable3GPP,
UInt32 GBW, UInt32 MBW, UInt32 MTD, Bool16 enableForcePlayoutDelay, UInt32 playoutDelay,
UInt32 bandwidth, UInt32 bufferSpace, UInt32 delayTime, UInt32 startPlayDelay,
char *controlID, char *name, char *password)
: fSocket(NULL),
fClient(NULL),
fTimeoutTask(this, kIdleTimeoutInMsec),
fDurationInSec(inDurationInSec - inStartPlayTimeInSec),
fStartPlayTimeInSec(inStartPlayTimeInSec),
fRTCPIntervalInMs(inRTCPIntervalInMS),
fOptionsIntervalInSec(inOptionsIntervalInSec),
fOptions(sendOptions),
fOptionsRequestRandomData(requestRandomData),
fOptionsRandomDataSize(randomDataSize),
fTransactionStartTimeMilli(0),
fState(kSendingDescribe),
fDeathReason(kDiedNormally),
fNumSetups(0),
fUDPSocketArray(NULL),
fPlayTime(0),
fTotalPlayTime(0),
fLastRTCPTime(0),
fTeardownImmediately(false),
fAppendJunk(inAppendJunkData),
fReadInterval(inReadInterval),
fSockRcvBufSize(inSockRcvBufSize),
fSpeed(inSpeed),
fPacketRangePlayHeader(inPacketRangePlayHeader),
fGuarenteedBitRate(GBW),
fMaxBitRate(MBW),
fMaxTransferDelay(MTD),
fEnableForcePlayoutDelay(enableForcePlayoutDelay),
fPlayoutDelay(playoutDelay),
fBandwidth(bandwidth),
fBufferSpace(bufferSpace),
fDelayTime(delayTime),
fStartPlayDelay(startPlayDelay),
fEnable3GPP(enable3GPP),
//fStats(NULL),
fOverbufferWindowSizeInK(inOverbufferWindowSizeInK),
fCurRTCPTrack(0),
fNumPacketsReceived(0),
fNumBytesReceived(0),
fVerboseLevel(verboseLevel),
fPlayerSimulator(verboseLevel)
{
this->SetTaskName("RTSPClientLib:ClientSession");
StrPtrLen theURL(inURL);
if (true == sendOptions)
fState = kSendingOptions;
#if CLIENT_SESSION_DEBUG
fVerboseLevel = kUInt32_Max; //maximum possible unsigned int value in 2's complement
#endif
if ( fVerboseLevel >= 2)
{
in_addr inAddrStruct;
inAddrStruct.s_addr = inAddr;
qtss_printf("Connecting to: %s, port %d\n", inet_ntoa(inAddrStruct), inPort);
}
//
// Construct the appropriate ClientSocket type depending on what type of client we are supposed to be
switch (inClientType)
{
case kRTSPUDPClientType:
{
fControlType = kRawRTSPControlType;
fTransportType = kUDPTransportType;
fSocket = NEW TCPClientSocket(Socket::kNonBlockingSocketType);
break;
}
case kRTSPTCPClientType:
{
fControlType = kRawRTSPControlType;
fTransportType = kTCPTransportType;
fSocket = NEW TCPClientSocket(Socket::kNonBlockingSocketType);
break;
}
case kRTSPHTTPClientType:
{
fControlType = kRTSPHTTPControlType;
fTransportType = kTCPTransportType;
fSocket = NEW HTTPClientSocket(theURL, inHTTPCookie, Socket::kNonBlockingSocketType);
break;
}
case kRTSPHTTPDropPostClientType:
{
fControlType = kRTSPHTTPDropPostControlType;
fTransportType = kTCPTransportType;
fSocket = NEW HTTPClientSocket(theURL, inHTTPCookie, Socket::kNonBlockingSocketType);
break;
}
case kRTSPReliableUDPClientType:
{
fControlType = kRawRTSPControlType;
fTransportType = kReliableUDPTransportType;
fSocket = NEW TCPClientSocket(Socket::kNonBlockingSocketType);
break;
}
default:
{
qtss_printf("ClientSession: Attempt to create unsupported client type.\n");
::exit(-1);
}
}
fSocket->Set(inAddr, inPort);
//
// Construct the client object using this socket.
fClient = NEW RTSPClient(fSocket);
fClient->SetVerboseLevel(fVerboseLevel);
fClient->Set(theURL);
fClient->SetSetupParams(inLateTolerance, inMetaInfoFields);
fClient->SetBandwidth(fBandwidth);
if(controlID != NULL)
fClient->SetControlID(controlID);
if (enable3GPP)
{
fClient->Set3GPPLinkChars(fGuarenteedBitRate, fMaxBitRate, fMaxTransferDelay);
fClient->Set3GPPRateAdaptation(fBufferSpace, fDelayTime);
}
//user name and password
if (name != NULL && password != NULL)
{
fClient->SetName(name);
fClient->SetPassword(password);
}
//
// Start the connection process going
this->Signal(Task::kStartEvent);
}
ClientSession::~ClientSession()
{
if (fUDPSocketArray != NULL)
{
for (UInt32 x = 0; x < fSDPParser.GetNumStreams() * 2; x++)
{
OS_Error theErr = OS_NoErr;
while (theErr == OS_NoErr)
{
UInt32 theRemoteAddr = 0;
UInt32 theLength = 0;
UInt16 theRemotePort = 0;
char thePacketBuf[2048];
// Get a packet from one of the UDP sockets.
theErr = fUDPSocketArray[x]->RecvFrom(&theRemoteAddr, &theRemotePort,
&thePacketBuf[0], 2048,
&theLength);
}
delete fUDPSocketArray[x];
}
}
delete [] fUDPSocketArray;
delete fClient;
delete fSocket;
//delete fStats;
}
SInt64 ClientSession::Run()
{
EventFlags theEvents = this->GetEvents();
if (theEvents & Task::kStartEvent)
{
sActiveConnections++;
sTotalConnectionAttempts++;
//Sometimes the clientSession can be told to stop before it has a chance to start the connection
if (theEvents & ClientSession::kTeardownEvent)
fTeardownImmediately = true;
else
{
Assert(theEvents == Task::kStartEvent);
// Determine a random connection interval, and go away until that time comes around.
// Next time the event received would be Task::kIdleEvent, and the initial state is kSendingDescribe
return ((UInt32) ::rand()) % kMaxWaitTimeInMsec + 1;
}
}
//
if (theEvents & Task::kTimeoutEvent)
{
if(fState == kDone)
return 0;
if ( fVerboseLevel >= 2)
qtss_printf("Session timing out.\n");
fDeathReason = kSessionTimedout;
fState = kDone;
return 0;
}
//
// If we've been told to TEARDOWN, do so.
if (theEvents & ClientSession::kTeardownEvent)
{
if ( fVerboseLevel >= 2)
qtss_printf("Session tearing down immediately.\n");
fTeardownImmediately = true;
}
// We have been told to delete ourselves. Do so... NOW!!!!!!!!!!!!!!!
if (theEvents & Task::kKillEvent)
{
if ( fVerboseLevel >= 2)
qtss_printf("Session killed.\n");
sActiveConnections--;
return -1;
}
// Refresh the timeout. There is some legit activity going on...
fTimeoutTask.RefreshTimeout();
OS_Error theErr = OS_NoErr;
while ((theErr == OS_NoErr) && (fState != kDone))
{
//
// Do the appropriate thing depending on our current state
switch (fState)
{
case kSendingOptions:
{
if (true == fOptionsRequestRandomData)
theErr = fClient->SendOptionsWithRandomDataRequest(fOptionsRandomDataSize);
else
theErr = fClient->SendOptions();
if ( fVerboseLevel >= 3)
qtss_printf("Sent OPTIONS. Result = %"_U32BITARG_". Response code = %"_U32BITARG_"\n", theErr, fClient->GetStatus());
if (0 == fTransactionStartTimeMilli)
fTransactionStartTimeMilli = OS::Milliseconds();
if (theErr == OS_NoErr)
{
// Check that the OPTIONS response is a 200 OK. If not, bail
if (fClient->GetStatus() != 200)
{
theErr = ENOTCONN; // Exit the state machine
break;
}
else
{
if ( fVerboseLevel >= 3)
{
qtss_printf("--- Options transaction time ms = %qd ---\n", (SInt64) ( OS::Milliseconds() - fTransactionStartTimeMilli) );
SInt32 receivedLength = (SInt32) fClient->GetContentLength();
if (receivedLength != 0)
qtss_printf("--- Options Request Random Data Received requested = %"_S32BITARG_" received = %"_S32BITARG_" ---\n", fOptionsRandomDataSize, receivedLength);
StrPtrLenDel theBody(ConvertBytesToCHexString(fClient->GetContentBody(), receivedLength));
theBody.PrintStr("\n");
}
fState = kSendingDescribe;
}
}
break;
}
case kSendingDescribe:
{
theErr = fClient->SendDescribe(fAppendJunk);
if ( fVerboseLevel >= 3)
qtss_printf("Sent DESCRIBE. Result = %"_U32BITARG_". Response code = %"_U32BITARG_"\n", theErr, fClient->GetStatus());
if (theErr == OS_NoErr)
{
// Check that the DESCRIBE response is a 200 OK. If not, bail
if (fClient->GetStatus() != 200)
{
theErr = ENOTCONN; // Exit the state machine
break;
}
else
{
//
// We've sent a describe and gotten a response from the server.
// Parse the response and look for track information.
fSDPParser.Parse(fClient->GetContentBody(), fClient->GetContentLength());
//
// The SDP must have been misformatted.
if (fSDPParser.GetNumStreams() == 0)
fDeathReason = kBadSDP;
//
// We have valid SDP. If this is a UDP connection, construct a UDP
// socket array to act as incoming sockets.
if ((fTransportType == kUDPTransportType) || (fTransportType == kReliableUDPTransportType))
this->SetupUDPSockets();
//
// Setup client stats
//delete fStats;
//fStats = NEW TrackStats[fSDPParser.GetNumStreams()];
fStats.resize(fSDPParser.GetNumStreams());
//::memset(fStats, 0, sizeof(TrackStats) * fSDPParser.GetNumStreams());
}
fPlayerSimulator.Setup(fSDPParser.GetNumStreams(), fDelayTime, fStartPlayDelay);
fState = kSendingSetup;
}
break;
}
case kSendingSetup:
{
// The SETUP request is different depending on whether we are interleaving or not
if (fTransportType == kUDPTransportType)
{
theErr = fClient->SendUDPSetup(fSDPParser.GetStreamInfo(fNumSetups)->fTrackID,
fUDPSocketArray[fNumSetups*2]->GetLocalPort());
}
else if (fTransportType == kTCPTransportType)
{
fSocket->SetRcvSockBufSize(fSockRcvBufSize); // Make the rcv buf really big
theErr = fClient->SendTCPSetup(fSDPParser.GetStreamInfo(fNumSetups)->fTrackID,fNumSetups * 2, (fNumSetups * 2) +1);
}
else if (fTransportType == kReliableUDPTransportType)
{
theErr = fClient->SendReliableUDPSetup(fSDPParser.GetStreamInfo(fNumSetups)->fTrackID,
fUDPSocketArray[fNumSetups*2]->GetLocalPort());
}
if ( fVerboseLevel >= 3)
qtss_printf("Sent SETUP #%"_U32BITARG_". Result = %"_U32BITARG_". Response code = %"_U32BITARG_"\n",
fNumSetups, theErr, fClient->GetStatus());
//
// If this SETUP request / response is complete, check for errors, and if
// it succeeded, move onto the next SETUP. If we're done setting up all tracks,
// move onto PLAY.
if (theErr == OS_NoErr)
{
if (fClient->GetStatus() != 200)
{
theErr = ENOTCONN; // Exit the state machine
break;
}
else
{
// Record the server port for RTCPs.
fStats[fNumSetups].fDestRTCPPort = fClient->GetServerPort() + 1;
//obtain the sampling rate of this stream
StringParser parser = StringParser(&fSDPParser.GetStreamInfo(fNumSetups)->fPayloadName);
parser.GetThru(NULL, '/');
UInt32 samplingRate = parser.ConsumeInteger(NULL);
Assert(samplingRate != 0);
//Generates the client SSRC
SInt64 ms = OS::Microseconds();
UInt32 ssrc = static_cast<UInt32>((ms >> 32) ^ ms) + ::rand();
fStats[fNumSetups].fClientSSRC = ssrc + fNumSetups;
fPlayerSimulator.SetupTrack(fNumSetups, samplingRate, fBufferSpace);
fNumSetups++;
if (fNumSetups == fSDPParser.GetNumStreams())
fState = kSendingPlay;
}
}
break;
}
case kSendingPlay:
{
if (fPacketRangePlayHeader != NULL)
theErr = fClient->SendPacketRangePlay(fPacketRangePlayHeader, fSpeed);
else
theErr = fClient->SendPlay(fStartPlayTimeInSec, fSpeed);
if ( fVerboseLevel >= 3)
qtss_printf("Sent PLAY. Result = %"_U32BITARG_". Response code = %"_U32BITARG_"\n", theErr, fClient->GetStatus());
//
// If this PLAY request / response is complete, then we are done with setting
// up all the client crap. Now all we have to do is receive the data until it's
// time to send the TEARDOWN
if (theErr == OS_NoErr)
{
if (fClient->GetStatus() != 200)
{
theErr = ENOTCONN; // Exit the state machine
break;
}
// Mark down the SSRC for each track, if possible.
for (UInt32 ssrcCount = 0; ssrcCount < fSDPParser.GetNumStreams(); ssrcCount++)
fStats[ssrcCount].fServerSSRC = fClient->GetSSRCByTrack(fSDPParser.GetStreamInfo(ssrcCount)->fTrackID);
fState = kPlaying;
sPlayingConnections++;
//
// Start our duration timer. Use this to figure out when to send a teardown
fPlayTime = fLastRTCPTime = OS::Milliseconds();
if(fVerboseLevel >= 1)
{
for (UInt32 i = 0; i < fSDPParser.GetNumStreams(); i++)
{
QTSS_RTPPayloadType type = fSDPParser.GetStreamInfo(i)->fPayloadType;
qtss_printf("Receiving track %"_U32BITARG_", trackID=%"_U32BITARG_", %s at time %"_S64BITARG_"\n",
i, fSDPParser.GetStreamInfo(i)->fTrackID,
type == qtssVideoPayloadType ? "video" : type == qtssAudioPayloadType ? "audio" : "unknown",
OS::Milliseconds());
}
}
}
break;
}
case kPlaying:
{
// Should we send a teardown? We should if either we've been told to teardown, or if our time has run out
SInt64 curTime = OS::Milliseconds();
fTotalPlayTime = curTime - fPlayTime;
if (((curTime - fPlayTime) > fDurationInSec * 1000) || (fTeardownImmediately))
{
sPlayingConnections--;
fState = kSendingTeardown;
break;
}
//Send RTCP if necessary; if we are using TCP for media transport, than 1 set of RTCP total is enough
Bool16 sendRTCP = ((curTime - fLastRTCPTime) > fRTCPIntervalInMs) && (fTransportType != kTCPTransportType);
sendRTCP |= (fPlayTime == fLastRTCPTime); //send the first RTCP ASAP.
if (sendRTCP)
{
//(void) fClient->SendSetParameter(); // test for keep alives and error responses
//(void) fClient->SendOptions(); // test for keep alives and error responses
for ( ; fCurRTCPTrack < fSDPParser.GetNumStreams(); fCurRTCPTrack++)
{
OS_Error err = this->SendRTCPPackets(fCurRTCPTrack);
if (fTransportType == kTCPTransportType && err != OS_NoErr)
{
theErr = err; //if error happens on a TCP RTCP socket, then bail
break;
}
}
if (theErr != OS_NoErr)
break;
//Done sending the RTCP's
fCurRTCPTrack = 0;
fLastRTCPTime = (curTime == fLastRTCPTime) ? curTime + 1 : curTime;
//Drop the POST portion of the HTTP connection after every send
if (fControlType == kRTSPHTTPDropPostControlType)
((HTTPClientSocket*)fSocket)->ClosePost();
}
//Now read the media data
theErr = this->ReadMediaData();
if ((theErr == EINPROGRESS) || (theErr == EAGAIN) || (theErr == OS_NoErr))
theErr = OS_NoErr; //ignore control flow errors here
else
{
sPlayingConnections--;
break;
}
curTime = OS::Milliseconds();
SInt64 nextRTCPTime = fLastRTCPTime + fRTCPIntervalInMs;
//return curTime < nextRTCPTime ? nextRTCPTime - curTime : fReadInterval;
return curTime < nextRTCPTime ? MIN(nextRTCPTime - curTime, fReadInterval) : 1;
}
case kSendingTeardown:
{
theErr = fClient->SendTeardown();
if ( fVerboseLevel >= 3)
qtss_printf("Sending TEARDOWN. Result = %"_U32BITARG_". Response code = %"_U32BITARG_"\n", theErr, fClient->GetStatus());
// Once the TEARDOWN is complete, we are done, so mark ourselves as dead, and wait
// for the owner of this object to delete us
if (theErr == OS_NoErr)
fState = kDone;
break;
}
}
}
if ((theErr == EINPROGRESS) || (theErr == EAGAIN))
{
//
// Request an async event
fSocket->GetSocket()->SetTask(this);
fSocket->GetSocket()->RequestEvent(fSocket->GetEventMask());
}
else if (theErr != OS_NoErr)
{
//
// We encountered some fatal error with the socket. Record this as a connection failure
if (fState == kSendingTeardown)
fDeathReason = kTeardownFailed;
else if (fState == kPlaying)
fDeathReason = kDiedWhilePlaying;
else if (fClient->GetStatus() != 200)
fDeathReason = kRequestFailed;
else
fDeathReason = kConnectionFailed;
fState = kDone;
}
if ( fVerboseLevel >= 2)
if (fState == kDone)
qtss_printf("Client connection complete. Death reason = %"_U32BITARG_"\n", fDeathReason);
return 0;
}
void ClientSession::SetupUDPSockets()
{
static UInt16 sCurrentRTPPortToUse = 6970;
static const UInt16 kMinRTPPort = 6970;
static const UInt16 kMaxRTPPort = 36970;
OS_Error theErr = OS_NoErr;
//
// Create a UDP socket pair (RTP, RTCP) for each stream
fUDPSocketArray = NEW UDPSocket*[fSDPParser.GetNumStreams() * 2];
for (UInt32 x = 0; x < fSDPParser.GetNumStreams() * 2; x++)
{
fUDPSocketArray[x] = NEW UDPSocket(this, Socket::kNonBlockingSocketType);
theErr = fUDPSocketArray[x]->Open();
if (theErr != OS_NoErr)
{
qtss_printf("ClientSession: Failed to open a UDP socket.\n");
::exit(-1);
}
}
for (UInt32 y = 0; y < fSDPParser.GetNumStreams(); y++)
{
for (UInt32 portCheck = 0; true; portCheck++)
{
theErr = fUDPSocketArray[y * 2]->Bind(INADDR_ANY, sCurrentRTPPortToUse);
if (theErr == OS_NoErr)
theErr = fUDPSocketArray[(y*2)+1]->Bind(INADDR_ANY, sCurrentRTPPortToUse + 1);
sCurrentRTPPortToUse += 2;
if (sCurrentRTPPortToUse > 30000)
sCurrentRTPPortToUse = 6970;
if (theErr == OS_NoErr)
{
// This is a good pair. Set the rcv buf on the RTP socket to be really big
fUDPSocketArray[y * 2]->SetSocketRcvBufSize(fSockRcvBufSize);
break;
}
if (sCurrentRTPPortToUse == kMaxRTPPort)
sCurrentRTPPortToUse = kMinRTPPort;
if (portCheck == 5000)
{
// Make sure we don't loop forever trying to bind a UDP socket. If we can't
// after a certain point, just bail...
qtss_printf("ClientSession: Failed to bind a UDP socket.\n");
::exit(-1);
}
}
}
if ( fVerboseLevel >= 3)
qtss_printf("Opened UDP sockets for %"_U32BITARG_" streams\n", fSDPParser.GetNumStreams());
}
//Will keep reading until all the packets buffered up has been read.
OS_Error ClientSession::ReadMediaData()
{
// For iterating over the array of UDP sockets
UInt32 theUDPSockIndex = 0;
OS_Error theErr = OS_NoErr;
while (true)
{
//
// If the media data is being interleaved, get it from the control connection
UInt32 theTrackID = 0;
UInt32 theLength = 0;
Bool16 isRTCP = false;
char* thePacket = NULL;
if (fTransportType == kTCPTransportType)
{
thePacket = NULL;
theErr = fClient->GetMediaPacket(&theTrackID, &isRTCP, &thePacket, &theLength);
if (thePacket == NULL)
break;
}
else
{
static const UInt32 kMaxPacketSize = 2048;
UInt32 theRemoteAddr = 0;
UInt16 theRemotePort = 0;
char thePacketBuf[kMaxPacketSize];
// Get a packet from one of the UDP sockets.
theErr = fUDPSocketArray[theUDPSockIndex]->RecvFrom(&theRemoteAddr, &theRemotePort,
&thePacketBuf[0], kMaxPacketSize,
&theLength);
if ((theErr != OS_NoErr) || (theLength == 0))
{
//Finished processing all the UDP packets that have been buffered up by the lower layer.
if ((fTransportType == kReliableUDPTransportType) && (!(theUDPSockIndex & 1)))
{
UInt32 trackIndex = TrackID2TrackIndex(fSDPParser.GetStreamInfo(theUDPSockIndex / 2)->fTrackID);
SendAckPackets(trackIndex);
/*
for (UInt32 trackIndex = 0; trackIndex < fSDPParser.GetNumStreams(); trackIndex++)
{
if (fSDPParser.GetStreamInfo(trackIndex)->fTrackID == fSDPParser.GetStreamInfo(theUDPSockIndex / 2)->fTrackID)
{
SendAckPackets(trackIndex);
//if (fStats[trackCount].fHighestSeqNumValid)
// If we are supposed to be sending acks, and we just finished
// receiving all packets for this track that are available at this time,
// send an ACK packet
//this->AckPackets(trackCount, 0, false);
}
}
*/
}
theUDPSockIndex++;
if (theUDPSockIndex == fSDPParser.GetNumStreams() * 2)
break;
continue;
}
theTrackID = fSDPParser.GetStreamInfo(theUDPSockIndex / 2)->fTrackID;
isRTCP = (theUDPSockIndex & 1);
thePacket = &thePacketBuf[0];
}
//
// We have a valid packet. Invoke the packet handler function
if (isRTCP)
this->ProcessRTCPPacket(thePacket, theLength, theTrackID);
else
this->ProcessRTPPacket(thePacket, theLength, theTrackID);
}
return theErr;
}
void ClientSession::ProcessRTPPacket(char* inPacket, UInt32 inLength, UInt32 inTrackID)
{
UInt32 trackIndex = TrackID2TrackIndex(inTrackID);
if (trackIndex == kUInt32_Max)
{ if(fVerboseLevel >= 3)
qtss_printf("ClientSession::ProcessRTPPacket fatal packet processing error. unknown track\n");
return;
}
TrackStats &trackStats = fStats[trackIndex];
if(fVerboseLevel >= 3)
{
SInt64 curTime = OS::Milliseconds();
qtss_printf("Processing incoming packets at time %"_S64BITARG_"\n", curTime);
}
//first validate the header and check the SSRC
Bool16 badPacket = false;
RTPPacket rtpPacket = RTPPacket(inPacket, inLength);
if (!rtpPacket.HeaderIsValid())
badPacket = true;
else
{
if (trackStats.fServerSSRC != 0)
{
if (rtpPacket.GetSSRC() != trackStats.fServerSSRC)
badPacket = true;
}
else //obtain the SSRC from the first packet if it's not available
trackStats.fServerSSRC = rtpPacket.GetSSRC();
}
if(badPacket)
{
trackStats.fNumMalformedPackets++;
if (fVerboseLevel >= 1)
qtss_printf("TrackID=%"_U32BITARG_", len=%"_U32BITARG_"; malformed packet\n", inTrackID, inLength);
return;
}
//Now check the sequence number
UInt32 packetSeqNum = kUInt32_Max;
if (trackStats.fHighestSeqNum == kUInt32_Max) //this is the first sequence number received
packetSeqNum = trackStats.fBaseSeqNum = trackStats.fHighestSeqNum = static_cast<UInt32>(rtpPacket.GetSeqNum());
else
packetSeqNum = CalcSeqNum(trackStats.fHighestSeqNum, rtpPacket.GetSeqNum());
if (packetSeqNum == kUInt32_Max) //sequence number is out of range
{
trackStats.fNumOutOfBoundPackets++;
if (fVerboseLevel >= 2)
qtss_printf("TrackID=%"_U32BITARG_", len=%"_U32BITARG_", seq=%u"", ref(32)=%"_U32BITARG_"; out of bound packet\n",
inTrackID, inLength, rtpPacket.GetSeqNum(), trackStats.fHighestSeqNum);
}
else
{
//the packet is good -- update statisics
Bool16 packetIsOutOfOrder = false;
if (trackStats.fHighestSeqNum <= packetSeqNum)
trackStats.fHighestSeqNum = packetSeqNum;
else
packetIsOutOfOrder = true;
fNumPacketsReceived++;
sPacketsReceived++;
trackStats.fNumPacketsReceived++;
fNumBytesReceived += inLength;
sBytesReceived += inLength;
trackStats.fNumBytesReceived += inLength;
//record this sequence number so that it can be acked later on
if (fTransportType == kReliableUDPTransportType)
trackStats.fPacketsToAck.push_back(packetSeqNum);
if (fVerboseLevel >= 3)
qtss_printf("TrackID=%"_U32BITARG_", len=%"_U32BITARG_", seq(32)=%"_U32BITARG_", ref(32)=%"_U32BITARG_"; good packet\n",
inTrackID, inLength, packetSeqNum, trackStats.fHighestSeqNum);
//RTP-Meta-Info
RTPMetaInfoPacket::FieldID* theMetaInfoFields = fClient->GetFieldIDArrayByTrack(inTrackID);
if (theMetaInfoFields != NULL)
{
//
// This packet is an RTP-Meta-Info packet. Parse it out and print out the results
RTPMetaInfoPacket theMetaInfoPacket;
Bool16 packetOK = theMetaInfoPacket.ParsePacket((UInt8*)inPacket, inLength, theMetaInfoFields);
if (!packetOK)
{
if( fVerboseLevel >= 2)
qtss_printf("Received invalid RTP-Meta-Info packet\n");
}
else if( fVerboseLevel >= 2)
{
qtss_printf("---\n");
qtss_printf("TrackID: %"_U32BITARG_"\n", inTrackID);
qtss_printf("Packet transmit time: %"_64BITARG_"d\n", theMetaInfoPacket.GetTransmitTime());
qtss_printf("Frame type: %u\n", theMetaInfoPacket.GetFrameType());
qtss_printf("Packet number: %"_64BITARG_"u\n", theMetaInfoPacket.GetPacketNumber());
qtss_printf("Packet position: %"_64BITARG_"u\n", theMetaInfoPacket.GetPacketPosition());
qtss_printf("Media data length: %"_U32BITARG_"\n", theMetaInfoPacket.GetMediaDataLen());
}
}
if (fEnable3GPP)
{
UInt32 timeStamp = rtpPacket.GetTimeStamp();
Bool16 packetIsDuplicate = fPlayerSimulator.ProcessRTPPacket(trackIndex, inLength, rtpPacket.GetBody().Len, packetSeqNum, timeStamp);
if(packetIsOutOfOrder && !packetIsDuplicate)
trackStats.fNumOutOfOrderPackets++;
}
}
}
void ClientSession::ProcessRTCPPacket(char* inPacket, UInt32 inLength, UInt32 inTrackID)
{
UInt32 trackIndex = TrackID2TrackIndex(inTrackID);
if (trackIndex == kUInt32_Max)
{
if (fVerboseLevel >= 3)
qtss_printf("ClientSession::ProcessRTCPPacket fatal packet processing error. unknown track\n");
return;
}
TrackStats &trackStats = fStats[trackIndex];
SInt64 curTime = OS::Milliseconds();
if(fVerboseLevel >= 2)
qtss_printf("Processing incoming RTCP packets on track %"_U32BITARG_" at time %"_S64BITARG_"\n", trackIndex, curTime);
//first validate the header and check the SSRC
RTCPSenderReportPacket packet;
Bool16 badPacket = !packet.ParseReport(reinterpret_cast<UInt8 *>(inPacket), inLength);
if (!badPacket)
{
if (trackStats.fServerSSRC != 0)
{
if (packet.GetPacketSSRC() != trackStats.fServerSSRC)
badPacket = true;
}
else //obtain the SSRC from the first packet if it's not available
trackStats.fServerSSRC = packet.GetPacketSSRC();
}
if(badPacket)
{
if (fVerboseLevel >= 1)
qtss_printf("TrackID=%"_U32BITARG_", len=%"_U32BITARG_"; malformed RTCP packet\n", inTrackID, inLength);
return;
}
//Now obtains the NTP timestamp and the current time -- we'll need it for the LSR field of the receiver report
trackStats.fLastSenderReportNTPTime = packet.GetNTPTimeStamp();
trackStats.fLastSenderReportLocalTime = curTime;
}
void ClientSession::SendAckPackets(UInt32 inTrackIndex)
{
TrackStats &trackStats = fStats[inTrackIndex];
if (trackStats.fPacketsToAck.empty())
return;
trackStats.fNumAcks++;
if(fVerboseLevel >= 3)
{
SInt64 curTime = OS::Milliseconds();
qtss_printf("Sending %"_U32BITARG_" acks at time %"_S64BITARG_" on track %"_U32BITARG_"\n",
trackStats.fPacketsToAck.size(), curTime, inTrackIndex);
}
char sendBuffer[kMaxUDPPacketSize];
//First send an empty Receivor Report
RTCPRRPacket RRPacket = RTCPRRPacket(sendBuffer, kMaxUDPPacketSize);
RRPacket.SetSSRC(trackStats.fClientSSRC);
StrPtrLen buffer = RRPacket.GetBufferRemaining();
//Now send the Ack packets
RTCPAckPacketFmt ackPacket = RTCPAckPacketFmt(buffer);
ackPacket.SetSSRC(trackStats.fClientSSRC);
ackPacket.SetAcks(trackStats.fPacketsToAck, trackStats.fServerSSRC);
trackStats.fPacketsToAck.clear();
UInt32 packetLength = RRPacket.GetPacketLen() + ackPacket.GetPacketLen();
// Send the packet
Assert(trackStats.fDestRTCPPort != 0);
fUDPSocketArray[(inTrackIndex*2)+1]->SendTo(fSocket->GetHostAddr(), trackStats.fDestRTCPPort, sendBuffer, packetLength);
}
OS_Error ClientSession::SendRTCPPackets(UInt32 trackIndex)
{
TrackStats &trackStats = fStats[trackIndex];
char buffer[kMaxUDPPacketSize];
//::memset(buffer, 0, kMaxUDPPacketSize);
//First send the RTCP Receiver Report packet
RTCPRRPacket RRPacket = RTCPRRPacket(buffer, kMaxUDPPacketSize);
RRPacket.SetSSRC(trackStats.fClientSSRC);
UInt8 fracLost = 0;
SInt32 cumLostPackets = 0;
UInt32 lsr = 0;
UInt32 dlsr = 0;
SInt64 curTime = OS::Milliseconds();
if (trackStats.fHighestSeqNum != kUInt32_Max)
{
CalcRTCPRRPacketsLost(trackIndex, fracLost, cumLostPackets);
//Now get the middle 32 bits of the NTP time stamp and send it as the LSR
lsr = static_cast<UInt32>(trackStats.fLastSenderReportNTPTime >> 16);
//Get the time difference expressed as units of 1/65536 seconds
if (trackStats.fLastSenderReportLocalTime != 0)
dlsr = static_cast<UInt32>(OS::TimeMilli_To_Fixed64Secs(curTime - trackStats.fLastSenderReportLocalTime) >> 16);
RRPacket.AddReportBlock(trackStats.fServerSSRC, fracLost, cumLostPackets, trackStats.fHighestSeqNum, lsr, dlsr);
}
StrPtrLen remainingBuf = RRPacket.GetBufferRemaining();
UInt32 *theWriter = reinterpret_cast<UInt32 *>(remainingBuf.Ptr);
// RECEIVER REPORT
/*
*(theWriter++) = htonl(0x81c90007); // 1 src RR packet
*(theWriter++) = htonl(0);
*(theWriter++) = htonl(0);
*(theWriter++) = htonl(0);
*(theWriter++) = htonl(trackStats.fHighestSeqNum == kUInt32_Max ? 0 : trackStats.fHighestSeqNum); //EHSN
*(theWriter++) = 0; // don't do jitter yet.
*(theWriter++) = 0; // don't do last SR timestamp
*(theWriter++) = 0; // don't do delay since last SR
*/
//The implementation should be sending an SDES to conform to the standard...but its not done.
if(fTransportType == kRTSPReliableUDPClientType)