asyncPacketStream.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _ASYNCPACKETSTREAM_H_
  23. #define _ASYNCPACKETSTREAM_H_
  24. #ifndef _ASYNCBUFFEREDSTREAM_H_
  25. #include "platform/async/asyncBufferedStream.h"
  26. #endif
  27. #ifndef _RAWDATA_H_
  28. #include "core/util/rawData.h"
  29. #endif
  30. #ifndef _THREADPOOLASYNCIO_H_
  31. #include "platform/threads/threadPoolAsyncIO.h"
  32. #endif
  33. //#define DEBUG_SPEW
  34. /// @file
  35. /// Input stream filter definitions for turning linear streams into
  36. /// streams that yield data in discrete packets using background
  37. /// reads.
  38. //--------------------------------------------------------------------------
  39. // Async stream packets.
  40. //--------------------------------------------------------------------------
  41. /// Stream packet read by an asynchronous packet stream.
  42. template< typename T >
  43. class AsyncPacket : public RawDataT< T >
  44. {
  45. public:
  46. typedef RawDataT< T > Parent;
  47. AsyncPacket()
  48. : mIndex( 0 ), mSizeActual( 0 ), mIsLast( false ) {}
  49. AsyncPacket( T* data, U32 size, bool ownMemory = false )
  50. : Parent( data, size, ownMemory ),
  51. mIndex( 0 ), mSizeActual( 0 ), mIsLast( false ) {}
  52. /// Running number in stream.
  53. U32 mIndex;
  54. /// Number of items that have actually been read into the packet.
  55. /// This may be less than "size" for end-of-stream packets in non-looping
  56. /// streams.
  57. ///
  58. /// @note Extraneous space at the end of the packet will be cleared using
  59. /// constructArray() calls.
  60. U32 mSizeActual;
  61. /// If true this is the last packet in the stream.
  62. bool mIsLast;
  63. };
  64. //--------------------------------------------------------------------------
  65. // Async packet streams.
  66. //--------------------------------------------------------------------------
  67. /// A packet stream turns a continuous stream of elements into a
  68. /// stream of discrete packets of elements.
  69. ///
  70. /// All packets are of the exact same size even if, for end-of-stream
  71. /// packets, they actually contain less data than their actual size.
  72. /// Extraneous space is cleared.
  73. ///
  74. /// @note For looping streams, the stream must implement the
  75. /// IResettable interface.
  76. template< typename Stream, class Packet = AsyncPacket< typename TypeTraits< Stream >::BaseType::ElementType > >
  77. class AsyncPacketBufferedInputStream : public AsyncBufferedInputStream< Packet*, Stream >
  78. {
  79. public:
  80. typedef AsyncBufferedInputStream< Packet*, Stream > Parent;
  81. typedef Packet PacketType;
  82. typedef typename TypeTraits< Stream >::BaseType StreamType;
  83. protected:
  84. class PacketReadItem;
  85. friend class PacketReadItem; // _onArrival
  86. /// Asynchronous work item for reading a packet from the source stream.
  87. class PacketReadItem : public AsyncReadItem< typename Parent::SourceElementType, StreamType >
  88. {
  89. public:
  90. typedef AsyncReadItem< typename AsyncPacketBufferedInputStream< Stream, Packet >::SourceElementType, StreamType > Parent;
  91. PacketReadItem( const ThreadSafeRef< AsyncPacketBufferedInputStream< Stream, Packet > >& asyncStream,
  92. PacketType* packet,
  93. U32 numElements,
  94. ThreadPool::Context* context = NULL )
  95. : Parent( asyncStream->getSourceStream(), numElements, 0, *packet, false, 0, context ),
  96. mAsyncStream( asyncStream ),
  97. mPacket( packet ) {}
  98. protected:
  99. typedef ThreadSafeRef< AsyncPacketBufferedInputStream< Stream, Packet > > AsyncPacketStreamPtr;
  100. /// The issueing async state.
  101. AsyncPacketStreamPtr mAsyncStream;
  102. /// The packet that receives the data.
  103. PacketType* mPacket;
  104. // WorkItem
  105. virtual void execute()
  106. {
  107. Parent::execute();
  108. mPacket->mSizeActual += this->mNumElementsRead;
  109. #ifdef DEBUG_SPEW
  110. Platform::outputDebugString( "[AsyncPacketStream] read %i elements into packet #%i with size %i",
  111. this->mNumElementsRead, mPacket->mIndex, mPacket->size );
  112. #endif
  113. // Handle extraneous space at end of packet.
  114. if( this->cancellationPoint() ) return;
  115. U32 numExtraElements = mPacket->size - this->mNumElementsRead;
  116. if( numExtraElements )
  117. {
  118. if( mAsyncStream->mIsLooping
  119. && dynamic_cast< IResettable* >( &Deref( this->getStream() ) ) )
  120. {
  121. #ifdef DEBUG_SPEW
  122. Platform::outputDebugString( "[AsyncPacketStream] resetting stream and reading %i more elements", numExtraElements );
  123. #endif
  124. // Wrap around and start re-reading from beginning of stream.
  125. dynamic_cast< IResettable* >( &Deref( this->getStream() ) )->reset();
  126. this->mOffsetInBuffer += this->mNumElementsRead;
  127. this->mOffsetInStream = 0;
  128. this->mNumElements = numExtraElements;
  129. this->_prep();
  130. Parent::execute();
  131. mPacket->mSizeActual += this->mNumElementsRead;
  132. }
  133. else
  134. constructArray( &mPacket->data[ this->mNumElementsRead ], numExtraElements );
  135. }
  136. // Buffer the packet.
  137. if( this->cancellationPoint() ) return;
  138. mAsyncStream->_onArrival( mPacket );
  139. }
  140. virtual void onCancelled()
  141. {
  142. Parent::onCancelled();
  143. destructSingle< PacketType* >( mPacket );
  144. mAsyncStream = NULL;
  145. }
  146. };
  147. typedef ThreadSafeRef< PacketReadItem > PacketReadItemRef;
  148. /// Number of elements to read per packet.
  149. U32 mPacketSize;
  150. /// Running number of next stream packet.
  151. U32 mNextPacketIndex;
  152. /// Total number of elements in the source stream.
  153. U32 mNumTotalSourceElements;
  154. /// Create a new stream packet of the given size.
  155. virtual PacketType* _newPacket( U32 packetSize ) { return constructSingle< PacketType* >( packetSize ); }
  156. /// Request the next packet from the underlying stream.
  157. virtual void _requestNext();
  158. /// Create a new work item that reads "numElements" into "packet".
  159. virtual void _newReadItem( PacketReadItemRef& outRef,
  160. PacketType* packet,
  161. U32 numElements )
  162. {
  163. outRef = new PacketReadItem( this, packet, numElements, this->mThreadContext );
  164. }
  165. public:
  166. /// Construct a new packet stream reading from "stream".
  167. ///
  168. /// @note If looping is used and "stream" is not read from the beginning, "stream" should
  169. /// implement IPositionable<U32> or ISizeable<U32> so the async stream can tell how many elements
  170. /// there actually are in the stream after resetting.
  171. ///
  172. /// @param stream The source stream from which to read the actual data elements.
  173. /// @param packetSize Size of stream packets returned by the stream in number of elements.
  174. /// @param numSourceElementsToRead Number of elements to read from "stream".
  175. /// @param numReadAhead Number of packets to read and buffer in advance.
  176. /// @param isLooping If true, the packet stream will loop infinitely over the source stream.
  177. /// @param pool The ThreadPool to use for asynchronous packet reads.
  178. /// @param context The ThreadContext to place asynchronous packet reads in.
  179. AsyncPacketBufferedInputStream( const Stream& stream,
  180. U32 packetSize,
  181. U32 numSourceElementsToRead = 0,
  182. U32 numReadAhead = Parent::DEFAULT_STREAM_LOOKAHEAD,
  183. bool isLooping = false,
  184. ThreadPool* pool = &ThreadPool::GLOBAL(),
  185. ThreadContext* context = ThreadContext::ROOT_CONTEXT() );
  186. /// @return the size of stream packets returned by this stream in number of elements.
  187. U32 getPacketSize() const { return mPacketSize; }
  188. };
  189. template< typename Stream, class Packet >
  190. AsyncPacketBufferedInputStream< Stream, Packet >::AsyncPacketBufferedInputStream
  191. ( const Stream& stream,
  192. U32 packetSize,
  193. U32 numSourceElementsToRead,
  194. U32 numReadAhead,
  195. bool isLooping,
  196. ThreadPool* threadPool,
  197. ThreadContext* threadContext )
  198. : Parent( stream, numSourceElementsToRead, numReadAhead, isLooping, threadPool, threadContext ),
  199. mPacketSize( packetSize ),
  200. mNextPacketIndex( 0 ),
  201. mNumTotalSourceElements( numSourceElementsToRead )
  202. {
  203. AssertFatal( mPacketSize > 0,
  204. "AsyncPacketStream::AsyncPacketStream() - packet size cannot be zero" );
  205. // Determine total number of elements in stream, if possible.
  206. IPositionable< U32 >* positionable = dynamic_cast< IPositionable< U32 >* >( &Deref( stream ) );
  207. if( positionable )
  208. mNumTotalSourceElements += positionable->getPosition();
  209. else
  210. {
  211. ISizeable< U32 >* sizeable = dynamic_cast< ISizeable< U32 >* >( &Deref( stream ) );
  212. if( sizeable )
  213. mNumTotalSourceElements = sizeable->getSize();
  214. }
  215. #ifdef DEBUG_SPEW
  216. Platform::outputDebugString( "[AsyncPacketStream] %i remaining, %i total (%i packets)",
  217. this->mNumRemainingSourceElements, mNumTotalSourceElements,
  218. ( this->mNumRemainingSourceElements / mPacketSize ) + ( this->mNumRemainingSourceElements % mPacketSize ? 1 : 0 ) );
  219. #endif
  220. }
  221. template< typename Stream, class Packet >
  222. void AsyncPacketBufferedInputStream< Stream, Packet >::_requestNext()
  223. {
  224. Stream& stream = this->getSourceStream();
  225. bool isEOS = !this->mNumRemainingSourceElements;
  226. if( isEOS && this->mIsLooping )
  227. {
  228. StreamType* s = &Deref( stream );
  229. IResettable* resettable = dynamic_cast< IResettable* >( s );
  230. if( resettable )
  231. {
  232. IPositionable< U32 >* positionable = dynamic_cast< IPositionable< U32 >* >( &Deref( stream ) );
  233. U32 pos = 0;
  234. if(positionable)
  235. pos = positionable->getPosition();
  236. resettable->reset();
  237. isEOS = false;
  238. this->mNumRemainingSourceElements = mNumTotalSourceElements;
  239. if( positionable )
  240. {
  241. positionable->setPosition(pos);
  242. U32 dur = stream->getDuration();
  243. if(dur != 0) //avoiding division by zero? not needed, probably
  244. this->mNumRemainingSourceElements -= (U32)(mNumTotalSourceElements*(F32)pos/dur);
  245. }
  246. }
  247. }
  248. else if( isEOS )
  249. return;
  250. //TODO: scale priority depending on feed status
  251. // Allocate a packet.
  252. U32 numElements = mPacketSize;
  253. PacketType* packet = _newPacket( numElements );
  254. packet->mIndex = mNextPacketIndex;
  255. mNextPacketIndex ++;
  256. // Queue a stream packet work item.
  257. if( numElements >= this->mNumRemainingSourceElements )
  258. {
  259. if( !this->mIsLooping )
  260. {
  261. this->mNumRemainingSourceElements = 0;
  262. packet->mIsLast = true;
  263. }
  264. else
  265. this->mNumRemainingSourceElements = ( this->mNumTotalSourceElements - numElements + this->mNumRemainingSourceElements );
  266. }
  267. else
  268. this->mNumRemainingSourceElements -= numElements;
  269. #ifdef DEBUG_SPEW
  270. Platform::outputDebugString( "[AsyncPacketStream] packet %i, %i remaining, %i total",
  271. packet->mIndex, this->mNumRemainingSourceElements, mNumTotalSourceElements );
  272. #endif
  273. ThreadSafeRef< PacketReadItem > workItem;
  274. _newReadItem( workItem, packet, numElements );
  275. this->mThreadPool->queueWorkItem( workItem );
  276. }
  277. #undef DEBUG_SPEW
  278. #endif // !_ASYNCPACKETSTREAM_H_