ReliabilityLayer.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. /// \file
  11. /// \brief \b [Internal] Datagram reliable, ordered, unordered and sequenced sends. Flow control. Message splitting, reassembly, and coalescence.
  12. ///
  13. #ifndef __RELIABILITY_LAYER_H
  14. #define __RELIABILITY_LAYER_H
  15. #include "RakMemoryOverride.h"
  16. #include "MTUSize.h"
  17. #include "DS_LinkedList.h"
  18. #include "DS_List.h"
  19. #include "SocketLayer.h"
  20. #include "PacketPriority.h"
  21. #include "DS_Queue.h"
  22. #include "BitStream.h"
  23. #include "InternalPacket.h"
  24. #include "RakNetStatistics.h"
  25. #include "DR_SHA1.h"
  26. #include "DS_OrderedList.h"
  27. #include "DS_RangeList.h"
  28. #include "DS_BPlusTree.h"
  29. #include "DS_MemoryPool.h"
  30. #include "RakNetDefines.h"
  31. #include "DS_Heap.h"
  32. #include "BitStream.h"
  33. #include "NativeFeatureIncludes.h"
  34. #include "SecureHandshake.h"
  35. #include "PluginInterface2.h"
  36. #include "Rand.h"
  37. #include "RakNetSocket2.h"
  38. #if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1
  39. #include "CCRakNetUDT.h"
  40. #define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 1
  41. #else
  42. #include "CCRakNetSlidingWindow.h"
  43. #define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 0
  44. #endif
  45. /// Number of ordered streams available. You can use up to 32 ordered streams
  46. #define NUMBER_OF_ORDERED_STREAMS 32 // 2^5
  47. #define RESEND_TREE_ORDER 32
  48. namespace RakNet {
  49. /// Forward declarations
  50. class PluginInterface2;
  51. class RakNetRandom;
  52. typedef uint64_t reliabilityHeapWeightType;
  53. // int SplitPacketIndexComp( SplitPacketIndexType const &key, InternalPacket* const &data );
  54. struct SplitPacketChannel//<SplitPacketChannel>
  55. {
  56. CCTimeType lastUpdateTime;
  57. DataStructures::List<InternalPacket*> splitPacketList;
  58. #if PREALLOCATE_LARGE_MESSAGES==1
  59. InternalPacket *returnedPacket;
  60. bool gotFirstPacket;
  61. unsigned int stride;
  62. unsigned int splitPacketsArrived;
  63. #else
  64. // This is here for progress notifications, since progress notifications return the first packet data, if available
  65. InternalPacket *firstPacket;
  66. #endif
  67. };
  68. int RAK_DLL_EXPORT SplitPacketChannelComp( SplitPacketIdType const &key, SplitPacketChannel* const &data );
  69. // Helper class
  70. struct BPSTracker
  71. {
  72. BPSTracker();
  73. ~BPSTracker();
  74. void Reset(const char *file, unsigned int line);
  75. inline void Push1(CCTimeType time, uint64_t value1) {dataQueue.Push(TimeAndValue2(time,value1),_FILE_AND_LINE_); total1+=value1; lastSec1+=value1;}
  76. // void Push2(RakNet::TimeUS time, uint64_t value1, uint64_t value2);
  77. inline uint64_t GetBPS1(CCTimeType time) {(void) time; return lastSec1;}
  78. inline uint64_t GetBPS1Threadsafe(CCTimeType time) {(void) time; return lastSec1;}
  79. // uint64_t GetBPS2(RakNetTimeUS time);
  80. // void GetBPS1And2(RakNetTimeUS time, uint64_t &out1, uint64_t &out2);
  81. uint64_t GetTotal1(void) const;
  82. // uint64_t GetTotal2(void) const;
  83. struct TimeAndValue2
  84. {
  85. TimeAndValue2();
  86. ~TimeAndValue2();
  87. TimeAndValue2(CCTimeType t, uint64_t v1);
  88. // TimeAndValue2(RakNet::TimeUS t, uint64_t v1, uint64_t v2);
  89. // uint64_t value1, value2;
  90. uint64_t value1;
  91. CCTimeType time;
  92. };
  93. uint64_t total1, lastSec1;
  94. // uint64_t total2, lastSec2;
  95. DataStructures::Queue<TimeAndValue2> dataQueue;
  96. void ClearExpired1(CCTimeType time);
  97. // void ClearExpired2(RakNet::TimeUS time);
  98. };
  99. /// Datagram reliable, ordered, unordered and sequenced sends. Flow control. Message splitting, reassembly, and coalescence.
  100. class ReliabilityLayer//<ReliabilityLayer>
  101. {
  102. public:
  103. // Constructor
  104. ReliabilityLayer();
  105. // Destructor
  106. ~ReliabilityLayer();
  107. /// Resets the layer for reuse
  108. void Reset( bool resetVariables, int MTUSize, bool _useSecurity );
  109. /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable packet
  110. /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug.
  111. /// \param[in] time Time, in MS
  112. void SetTimeoutTime( RakNet::TimeMS time );
  113. /// Returns the value passed to SetTimeoutTime. or the default if it was never called
  114. /// \param[out] the value passed to SetTimeoutTime
  115. RakNet::TimeMS GetTimeoutTime(void);
  116. /// Packets are read directly from the socket layer and skip the reliability layer because unconnected players do not use the reliability layer
  117. /// This function takes packet data after a player has been confirmed as connected.
  118. /// \param[in] buffer The socket data
  119. /// \param[in] length The length of the socket data
  120. /// \param[in] systemAddress The player that this data is from
  121. /// \param[in] messageHandlerList A list of registered plugins
  122. /// \param[in] MTUSize maximum datagram size
  123. /// \retval true Success
  124. /// \retval false Modified packet
  125. bool HandleSocketReceiveFromConnectedPlayer(
  126. const char *buffer, unsigned int length, SystemAddress &systemAddress, DataStructures::List<PluginInterface2*> &messageHandlerList, int MTUSize,
  127. RakNetSocket2 *s, RakNetRandom *rnr, CCTimeType timeRead, BitStream &updateBitStream);
  128. /// This allocates bytes and writes a user-level message to those bytes.
  129. /// \param[out] data The message
  130. /// \return Returns number of BITS put into the buffer
  131. BitSize_t Receive( unsigned char**data );
  132. /// Puts data on the send queue
  133. /// \param[in] data The data to send
  134. /// \param[in] numberOfBitsToSend The length of \a data in bits
  135. /// \param[in] priority The priority level for the send
  136. /// \param[in] reliability The reliability type for the send
  137. /// \param[in] orderingChannel 0 to 31. Specifies what channel to use, for relational ordering and sequencing of packets.
  138. /// \param[in] makeDataCopy If true \a data will be copied. Otherwise, only a pointer will be stored.
  139. /// \param[in] MTUSize maximum datagram size
  140. /// \param[in] currentTime Current time, as per RakNet::GetTimeMS()
  141. /// \param[in] receipt This number will be returned back with ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS and is only returned with the reliability types that contain RECEIPT in the name
  142. /// \return True or false for success or failure.
  143. bool Send( char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, unsigned char orderingChannel, bool makeDataCopy, int MTUSize, CCTimeType currentTime, uint32_t receipt );
  144. /// Call once per game cycle. Handles internal lists and actually does the send.
  145. /// \param[in] s the communication end point
  146. /// \param[in] systemAddress The Unique Player Identifier who shouldhave sent some packets
  147. /// \param[in] MTUSize maximum datagram size
  148. /// \param[in] time current system time
  149. /// \param[in] maxBitsPerSecond if non-zero, enforces that outgoing bandwidth does not exceed this amount
  150. /// \param[in] messageHandlerList A list of registered plugins
  151. void Update( RakNetSocket2 *s, SystemAddress &systemAddress, int MTUSize, CCTimeType time,
  152. unsigned bitsPerSecondLimit,
  153. DataStructures::List<PluginInterface2*> &messageHandlerList,
  154. RakNetRandom *rnr, BitStream &updateBitStream);
  155. /// Were you ever unable to deliver a packet despite retries?
  156. /// \return true means the connection has been lost. Otherwise not.
  157. bool IsDeadConnection( void ) const;
  158. /// Causes IsDeadConnection to return true
  159. void KillConnection(void);
  160. /// Get Statistics
  161. /// \return A pointer to a static struct, filled out with current statistical information.
  162. RakNetStatistics * GetStatistics( RakNetStatistics *rns );
  163. ///Are we waiting for any data to be sent out or be processed by the player?
  164. bool IsOutgoingDataWaiting(void);
  165. bool AreAcksWaiting(void);
  166. // Set outgoing lag and packet loss properties
  167. void ApplyNetworkSimulator( double _maxSendBPS, RakNet::TimeMS _minExtraPing, RakNet::TimeMS _extraPingVariance );
  168. /// Returns if you previously called ApplyNetworkSimulator
  169. /// \return If you previously called ApplyNetworkSimulator
  170. bool IsNetworkSimulatorActive( void );
  171. void SetSplitMessageProgressInterval(int interval);
  172. void SetUnreliableTimeout(RakNet::TimeMS timeoutMS);
  173. /// Has a lot of time passed since the last ack
  174. bool AckTimeout(RakNet::Time curTime);
  175. CCTimeType GetNextSendTime(void) const;
  176. CCTimeType GetTimeBetweenPackets(void) const;
  177. #if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1
  178. CCTimeType GetAckPing(void) const;
  179. #endif
  180. RakNet::TimeMS GetTimeLastDatagramArrived(void) const {return timeLastDatagramArrived;}
  181. // If true, will update time between packets quickly based on ping calculations
  182. //void SetDoFastThroughputReactions(bool fast);
  183. // Encoded as numMessages[unsigned int], message1BitLength[unsigned int], message1Data (aligned), ...
  184. //void GetUndeliveredMessages(RakNet::BitStream *messages, int MTUSize);
  185. private:
  186. /// Send the contents of a bitstream to the socket
  187. /// \param[in] s The socket used for sending data
  188. /// \param[in] systemAddress The address and port to send to
  189. /// \param[in] bitStream The data to send.
  190. void SendBitStream( RakNetSocket2 *s, SystemAddress &systemAddress, RakNet::BitStream *bitStream, RakNetRandom *rnr, CCTimeType currentTime);
  191. ///Parse an internalPacket and create a bitstream to represent this data
  192. /// \return Returns number of bits used
  193. BitSize_t WriteToBitStreamFromInternalPacket( RakNet::BitStream *bitStream, const InternalPacket *const internalPacket, CCTimeType curTime );
  194. /// Parse a bitstream and create an internal packet to represent this data
  195. InternalPacket* CreateInternalPacketFromBitStream( RakNet::BitStream *bitStream, CCTimeType time );
  196. /// Does what the function name says
  197. unsigned RemovePacketFromResendListAndDeleteOlderReliableSequenced( const MessageNumberType messageNumber, CCTimeType time, DataStructures::List<PluginInterface2*> &messageHandlerList, const SystemAddress &systemAddress );
  198. /// Acknowledge receipt of the packet with the specified messageNumber
  199. void SendAcknowledgementPacket( const DatagramSequenceNumberType messageNumber, CCTimeType time);
  200. /// This will return true if we should not send at this time
  201. bool IsSendThrottled( int MTUSize );
  202. /// We lost a packet
  203. void UpdateWindowFromPacketloss( CCTimeType time );
  204. /// Increase the window size
  205. void UpdateWindowFromAck( CCTimeType time );
  206. /// Parse an internalPacket and figure out how many header bits would be written. Returns that number
  207. BitSize_t GetMaxMessageHeaderLengthBits( void );
  208. BitSize_t GetMessageHeaderLengthBits( const InternalPacket *const internalPacket );
  209. /// Get the SHA1 code
  210. void GetSHA1( unsigned char * const buffer, unsigned int nbytes, char code[ SHA1_LENGTH ] );
  211. /// Check the SHA1 code
  212. bool CheckSHA1( char code[ SHA1_LENGTH ], unsigned char * const buffer, unsigned int nbytes );
  213. /// Search the specified list for sequenced packets on the specified ordering channel, optionally skipping those with splitPacketId, and delete them
  214. // void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::List<InternalPacket*>&theList, int splitPacketId = -1 );
  215. /// Search the specified list for sequenced packets with a value less than orderingIndex and delete them
  216. // void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::Queue<InternalPacket*>&theList );
  217. /// Returns true if newPacketOrderingIndex is older than the waitingForPacketOrderingIndex
  218. bool IsOlderOrderedPacket( OrderingIndexType newPacketOrderingIndex, OrderingIndexType waitingForPacketOrderingIndex );
  219. /// Split the passed packet into chunks under MTU_SIZE bytes (including headers) and save those new chunks
  220. void SplitPacket( InternalPacket *internalPacket );
  221. /// Insert a packet into the split packet list
  222. void InsertIntoSplitPacketList( InternalPacket * internalPacket, CCTimeType time );
  223. /// Take all split chunks with the specified splitPacketId and try to reconstruct a packet. If we can, allocate and return it. Otherwise return 0
  224. InternalPacket * BuildPacketFromSplitPacketList( SplitPacketIdType splitPacketId, CCTimeType time,
  225. RakNetSocket2 *s, SystemAddress &systemAddress, RakNetRandom *rnr, BitStream &updateBitStream);
  226. InternalPacket * BuildPacketFromSplitPacketList( SplitPacketChannel *splitPacketChannel, CCTimeType time );
  227. /// Delete any unreliable split packets that have long since expired
  228. //void DeleteOldUnreliableSplitPackets( CCTimeType time );
  229. /// Creates a copy of the specified internal packet with data copied from the original starting at dataByteOffset for dataByteLength bytes.
  230. /// Does not copy any split data parameters as that information is always generated does not have any reason to be copied
  231. InternalPacket * CreateInternalPacketCopy( InternalPacket *original, int dataByteOffset, int dataByteLength, CCTimeType time );
  232. /// Get the specified ordering list
  233. // DataStructures::LinkedList<InternalPacket*> *GetOrderingListAtOrderingStream( unsigned char orderingChannel );
  234. /// Add the internal packet to the ordering list in order based on order index
  235. // void AddToOrderingList( InternalPacket * internalPacket );
  236. /// Inserts a packet into the resend list in order
  237. void InsertPacketIntoResendList( InternalPacket *internalPacket, CCTimeType time, bool firstResend, bool modifyUnacknowledgedBytes );
  238. /// Memory handling
  239. void FreeMemory( bool freeAllImmediately );
  240. /// Memory handling
  241. void FreeThreadSafeMemory( void );
  242. // Initialize the variables
  243. void InitializeVariables( void );
  244. /// Given the current time, is this time so old that we should consider it a timeout?
  245. bool IsExpiredTime(unsigned int input, CCTimeType currentTime) const;
  246. // Make it so we don't do resends within a minimum threshold of time
  247. void UpdateNextActionTime(void);
  248. /// Does this packet number represent a packet that was skipped (out of order?)
  249. //unsigned int IsReceivedPacketHole(unsigned int input, RakNet::TimeMS currentTime) const;
  250. /// Skip an element in the received packets list
  251. //unsigned int MakeReceivedPacketHole(unsigned int input) const;
  252. /// How many elements are waiting to be resent?
  253. unsigned int GetResendListDataSize(void) const;
  254. /// Update all memory which is not threadsafe
  255. void UpdateThreadedMemory(void);
  256. void CalculateHistogramAckSize(void);
  257. // Used ONLY for RELIABLE_ORDERED
  258. // RELIABLE_SEQUENCED just returns the newest one
  259. // DataStructures::List<DataStructures::LinkedList<InternalPacket*>*> orderingList;
  260. DataStructures::Queue<InternalPacket*> outputQueue;
  261. int splitMessageProgressInterval;
  262. CCTimeType unreliableTimeout;
  263. struct MessageNumberNode
  264. {
  265. DatagramSequenceNumberType messageNumber;
  266. MessageNumberNode *next;
  267. };
  268. struct DatagramHistoryNode
  269. {
  270. DatagramHistoryNode() {}
  271. DatagramHistoryNode(MessageNumberNode *_head, CCTimeType ts
  272. ) :
  273. head(_head), timeSent(ts)
  274. {}
  275. MessageNumberNode *head;
  276. CCTimeType timeSent;
  277. };
  278. // Queue length is programmatically restricted to DATAGRAM_MESSAGE_ID_ARRAY_LENGTH
  279. // This is essentially an O(1) lookup to get a DatagramHistoryNode given an index
  280. // datagramHistory holds a linked list of MessageNumberNode. Each MessageNumberNode refers to one element in resendList which can be cleared on an ack.
  281. DataStructures::Queue<DatagramHistoryNode> datagramHistory;
  282. DataStructures::MemoryPool<MessageNumberNode> datagramHistoryMessagePool;
  283. struct UnreliableWithAckReceiptNode
  284. {
  285. UnreliableWithAckReceiptNode() {}
  286. UnreliableWithAckReceiptNode(DatagramSequenceNumberType _datagramNumber, uint32_t _sendReceiptSerial, RakNet::TimeUS _nextActionTime) :
  287. datagramNumber(_datagramNumber), sendReceiptSerial(_sendReceiptSerial), nextActionTime(_nextActionTime)
  288. {}
  289. DatagramSequenceNumberType datagramNumber;
  290. uint32_t sendReceiptSerial;
  291. RakNet::TimeUS nextActionTime;
  292. };
  293. DataStructures::List<UnreliableWithAckReceiptNode> unreliableWithAckReceiptHistory;
  294. void RemoveFromDatagramHistory(DatagramSequenceNumberType index);
  295. MessageNumberNode* GetMessageNumberNodeByDatagramIndex(DatagramSequenceNumberType index, CCTimeType *timeSent);
  296. void AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, CCTimeType timeSent);
  297. MessageNumberNode* AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, DatagramSequenceNumberType messageNumber, CCTimeType timeSent);
  298. MessageNumberNode* AddSubsequentToDatagramHistory(MessageNumberNode *messageNumberNode, DatagramSequenceNumberType messageNumber);
  299. DatagramSequenceNumberType datagramHistoryPopCount;
  300. DataStructures::MemoryPool<InternalPacket> internalPacketPool;
  301. // DataStructures::BPlusTree<DatagramSequenceNumberType, InternalPacket*, RESEND_TREE_ORDER> resendTree;
  302. InternalPacket *resendBuffer[RESEND_BUFFER_ARRAY_LENGTH];
  303. InternalPacket *resendLinkedListHead;
  304. InternalPacket *unreliableLinkedListHead;
  305. void RemoveFromUnreliableLinkedList(InternalPacket *internalPacket);
  306. void AddToUnreliableLinkedList(InternalPacket *internalPacket);
  307. // unsigned int numPacketsOnResendBuffer;
  308. //unsigned int blockWindowIncreaseUntilTime;
  309. // DataStructures::RangeList<DatagramSequenceNumberType> acknowlegements;
  310. // Resend list is a tree of packets we need to resend
  311. // Set to the current time when the resend queue is no longer empty
  312. // Set to zero when it becomes empty
  313. // Set to the current time if it is not zero, and we get incoming data
  314. // If the current time - timeResendQueueNonEmpty is greater than a threshold, we are disconnected
  315. // CCTimeType timeResendQueueNonEmpty;
  316. RakNet::TimeMS timeLastDatagramArrived;
  317. // If we backoff due to packetloss, don't remeasure until all waiting resends have gone out or else we overcount
  318. // bool packetlossThisSample;
  319. // int backoffThisSample;
  320. // unsigned packetlossThisSampleResendCount;
  321. // CCTimeType lastPacketlossTime;
  322. //DataStructures::Queue<InternalPacket*> sendPacketSet[ NUMBER_OF_PRIORITIES ];
  323. DataStructures::Heap<reliabilityHeapWeightType, InternalPacket*, false> outgoingPacketBuffer;
  324. reliabilityHeapWeightType outgoingPacketBufferNextWeights[NUMBER_OF_PRIORITIES];
  325. void InitHeapWeights(void);
  326. reliabilityHeapWeightType GetNextWeight(int priorityLevel);
  327. // unsigned int messageInSendBuffer[NUMBER_OF_PRIORITIES];
  328. // double bytesInSendBuffer[NUMBER_OF_PRIORITIES];
  329. DataStructures::OrderedList<SplitPacketIdType, SplitPacketChannel*, SplitPacketChannelComp> splitPacketChannelList;
  330. MessageNumberType sendReliableMessageNumberIndex;
  331. MessageNumberType internalOrderIndex;
  332. //unsigned int windowSize;
  333. //RakNet::BitStream updateBitStream;
  334. bool deadConnection, cheater;
  335. SplitPacketIdType splitPacketId;
  336. RakNet::TimeMS timeoutTime; // How long to wait in MS before timing someone out
  337. //int MAX_AVERAGE_PACKETS_PER_SECOND; // Name says it all
  338. // int RECEIVED_PACKET_LOG_LENGTH, requestedReceivedPacketLogLength; // How big the receivedPackets array is
  339. // unsigned int *receivedPackets;
  340. RakNetStatistics statistics;
  341. // Algorithm for blending ordered and sequenced on the same channel:
  342. // 1. Each ordered message transmits OrderingIndexType orderedWriteIndex. There are NUMBER_OF_ORDERED_STREAMS independent values of these. The value
  343. // starts at 0. Every time an ordered message is sent, the value increments by 1
  344. // 2. Each sequenced message contains the current value of orderedWriteIndex for that channel, and additionally OrderingIndexType sequencedWriteIndex.
  345. // sequencedWriteIndex resets to 0 every time orderedWriteIndex increments. It increments by 1 every time a sequenced message is sent.
  346. // 3. The receiver maintains the next expected value for the orderedWriteIndex, stored in orderedReadIndex.
  347. // 4. As messages arrive:
  348. // If a message has the current ordering index, and is sequenced, and is < the current highest sequence value, discard
  349. // If a message has the current ordering index, and is sequenced, and is >= the current highest sequence value, return immediately
  350. // If a message has a greater ordering index, and is sequenced or ordered, buffer it
  351. // If a message has the current ordering index, and is ordered, buffer, then push off messages from buffer
  352. // 5. Pushing off messages from buffer:
  353. // Messages in buffer are put in a minheap. The value of each node is calculated such that messages are returned:
  354. // A. (lowest ordering index, lowest sequence index)
  355. // B. (lowest ordering index, no sequence index)
  356. // Messages are pushed off until the heap is empty, or the next message to be returned does not preserve the ordered index
  357. // For an empty heap, the heap weight should start at the lowest value based on the next expected ordering index, to avoid variable overflow
  358. // Sender increments this by 1 for every ordered message sent
  359. OrderingIndexType orderedWriteIndex[NUMBER_OF_ORDERED_STREAMS];
  360. // Sender increments by 1 for every sequenced message sent. Resets to 0 when an ordered message is sent
  361. OrderingIndexType sequencedWriteIndex[NUMBER_OF_ORDERED_STREAMS];
  362. // Next expected index for ordered messages.
  363. OrderingIndexType orderedReadIndex[NUMBER_OF_ORDERED_STREAMS];
  364. // Highest value received for sequencedWriteIndex for the current value of orderedReadIndex on the same channel.
  365. OrderingIndexType highestSequencedReadIndex[NUMBER_OF_ORDERED_STREAMS];
  366. DataStructures::Heap<reliabilityHeapWeightType, InternalPacket*, false> orderingHeaps[NUMBER_OF_ORDERED_STREAMS];
  367. OrderingIndexType heapIndexOffsets[NUMBER_OF_ORDERED_STREAMS];
  368. // CCTimeType histogramStart;
  369. // unsigned histogramBitsSent;
  370. /// Memory-efficient receivedPackets algorithm:
  371. /// receivedPacketsBaseIndex is the packet number we are expecting
  372. /// Everything under receivedPacketsBaseIndex is a packet we already got
  373. /// Everything over receivedPacketsBaseIndex is stored in hasReceivedPacketQueue
  374. /// It stores the time to stop waiting for a particular packet number, where the packet number is receivedPacketsBaseIndex + the index into the queue
  375. /// If 0, we got got that packet. Otherwise, the time to give up waiting for that packet.
  376. /// If we get a packet number where (receivedPacketsBaseIndex-packetNumber) is less than half the range of receivedPacketsBaseIndex then it is a duplicate
  377. /// Otherwise, it is a duplicate packet (and ignore it).
  378. // DataStructures::Queue<CCTimeType> hasReceivedPacketQueue;
  379. DataStructures::Queue<bool> hasReceivedPacketQueue;
  380. DatagramSequenceNumberType receivedPacketsBaseIndex;
  381. bool resetReceivedPackets;
  382. CCTimeType lastUpdateTime;
  383. CCTimeType timeBetweenPackets, nextSendTime;
  384. #if INCLUDE_TIMESTAMP_WITH_DATAGRAMS==1
  385. CCTimeType ackPing;
  386. #endif
  387. // CCTimeType ackPingSamples[ACK_PING_SAMPLES_SIZE]; // Must be range of unsigned char to wrap ackPingIndex properly
  388. CCTimeType ackPingSum;
  389. unsigned char ackPingIndex;
  390. //CCTimeType nextLowestPingReset;
  391. RemoteSystemTimeType remoteSystemTime;
  392. // bool continuousSend;
  393. // CCTimeType lastTimeBetweenPacketsIncrease,lastTimeBetweenPacketsDecrease;
  394. // Limit changes in throughput to once per ping - otherwise even if lag starts we don't know about it
  395. // In the meantime the connection is flooded and overrun.
  396. CCTimeType nextAllowedThroughputSample;
  397. bool bandwidthExceededStatistic;
  398. // If Update::maxBitsPerSecond > 0, then throughputCapCountdown is used as a timer to prevent sends for some amount of time after each send, depending on
  399. // the amount of data sent
  400. long long throughputCapCountdown;
  401. unsigned receivePacketCount;
  402. #ifdef _DEBUG
  403. struct DataAndTime//<InternalPacket>
  404. {
  405. RakNetSocket2 *s;
  406. char data[ MAXIMUM_MTU_SIZE ];
  407. unsigned int length;
  408. RakNet::TimeMS sendTime;
  409. // SystemAddress systemAddress;
  410. unsigned short remotePortRakNetWasStartedOn_PS3;
  411. unsigned int extraSocketOptions;
  412. };
  413. DataStructures::Queue<DataAndTime*> delayList;
  414. // Internet simulator
  415. double packetloss;
  416. RakNet::TimeMS minExtraPing, extraPingVariance;
  417. #endif
  418. CCTimeType elapsedTimeSinceLastUpdate;
  419. CCTimeType nextAckTimeToSend;
  420. #if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1
  421. RakNet::CCRakNetSlidingWindow congestionManager;
  422. #else
  423. RakNet::CCRakNetUDT congestionManager;
  424. #endif
  425. uint32_t unacknowledgedBytes;
  426. bool ResendBufferOverflow(void) const;
  427. void ValidateResendList(void) const;
  428. void ResetPacketsAndDatagrams(void);
  429. void PushPacket(CCTimeType time, InternalPacket *internalPacket, bool isReliable);
  430. void PushDatagram(void);
  431. bool TagMostRecentPushAsSecondOfPacketPair(void);
  432. void ClearPacketsAndDatagrams(void);
  433. void MoveToListHead(InternalPacket *internalPacket);
  434. void RemoveFromList(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes);
  435. void AddToListTail(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes);
  436. void PopListHead(bool modifyUnacknowledgedBytes);
  437. bool IsResendQueueEmpty(void) const;
  438. void SortSplitPacketList(DataStructures::List<InternalPacket*> &data, unsigned int leftEdge, unsigned int rightEdge) const;
  439. void SendACKs(RakNetSocket2 *s, SystemAddress &systemAddress, CCTimeType time, RakNetRandom *rnr, BitStream &updateBitStream);
  440. DataStructures::List<InternalPacket*> packetsToSendThisUpdate;
  441. DataStructures::List<bool> packetsToDeallocThisUpdate;
  442. // boundary is in packetsToSendThisUpdate, inclusive
  443. DataStructures::List<unsigned int> packetsToSendThisUpdateDatagramBoundaries;
  444. DataStructures::List<bool> datagramsToSendThisUpdateIsPair;
  445. DataStructures::List<unsigned int> datagramSizesInBytes;
  446. BitSize_t datagramSizeSoFar;
  447. BitSize_t allDatagramSizesSoFar;
  448. double totalUserDataBytesAcked;
  449. CCTimeType timeOfLastContinualSend;
  450. CCTimeType timeToNextUnreliableCull;
  451. // This doesn't need to be a member, but I do it to avoid reallocations
  452. DataStructures::RangeList<DatagramSequenceNumberType> incomingAcks;
  453. // Every 16 datagrams, we make sure the 17th datagram goes out the same update tick, and is the same size as the 16th
  454. int countdownToNextPacketPair;
  455. InternalPacket* AllocateFromInternalPacketPool(void);
  456. void ReleaseToInternalPacketPool(InternalPacket *ip);
  457. DataStructures::RangeList<DatagramSequenceNumberType> acknowlegements;
  458. DataStructures::RangeList<DatagramSequenceNumberType> NAKs;
  459. bool remoteSystemNeedsBAndAS;
  460. unsigned int GetMaxDatagramSizeExcludingMessageHeaderBytes(void);
  461. BitSize_t GetMaxDatagramSizeExcludingMessageHeaderBits(void);
  462. // ourOffset refers to a section within externallyAllocatedPtr. Do not deallocate externallyAllocatedPtr until all references are lost
  463. void AllocInternalPacketData(InternalPacket *internalPacket, InternalPacketRefCountedData **refCounter, unsigned char *externallyAllocatedPtr, unsigned char *ourOffset);
  464. // Set the data pointer to externallyAllocatedPtr, do not allocate
  465. void AllocInternalPacketData(InternalPacket *internalPacket, unsigned char *externallyAllocatedPtr);
  466. // Allocate new
  467. void AllocInternalPacketData(InternalPacket *internalPacket, unsigned int numBytes, bool allowStack, const char *file, unsigned int line);
  468. void FreeInternalPacketData(InternalPacket *internalPacket, const char *file, unsigned int line);
  469. DataStructures::MemoryPool<InternalPacketRefCountedData> refCountedDataPool;
  470. BPSTracker bpsMetrics[RNS_PER_SECOND_METRICS_COUNT];
  471. CCTimeType lastBpsClear;
  472. #if LIBCAT_SECURITY==1
  473. public:
  474. cat::AuthenticatedEncryption* GetAuthenticatedEncryption(void) { return &auth_enc; }
  475. protected:
  476. cat::AuthenticatedEncryption auth_enc;
  477. bool useSecurity;
  478. #endif // LIBCAT_SECURITY
  479. };
  480. } // namespace RakNet
  481. #endif
粤ICP备19079148号