ThrottledStream.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace MediaBrowser.Server.Implementations.HttpServer
  6. {
  7. /// <summary>
  8. /// Class for streaming data with throttling support.
  9. /// </summary>
  10. public class ThrottledStream : Stream
  11. {
  12. /// <summary>
  13. /// A constant used to specify an infinite number of bytes that can be transferred per second.
  14. /// </summary>
  15. public const long Infinite = 0;
  16. public Func<long, long, long> ThrottleCallback { get; set; }
  17. #region Private members
  18. /// <summary>
  19. /// The base stream.
  20. /// </summary>
  21. private readonly Stream _baseStream;
  22. /// <summary>
  23. /// The maximum bytes per second that can be transferred through the base stream.
  24. /// </summary>
  25. private long _maximumBytesPerSecond;
  26. /// <summary>
  27. /// The number of bytes that has been transferred since the last throttle.
  28. /// </summary>
  29. private long _byteCount;
  30. /// <summary>
  31. /// The start time in milliseconds of the last throttle.
  32. /// </summary>
  33. private long _start;
  34. #endregion
  35. #region Properties
  36. /// <summary>
  37. /// Gets the current milliseconds.
  38. /// </summary>
  39. /// <value>The current milliseconds.</value>
  40. protected long CurrentMilliseconds
  41. {
  42. get
  43. {
  44. return Environment.TickCount;
  45. }
  46. }
  47. /// <summary>
  48. /// Gets or sets the maximum bytes per second that can be transferred through the base stream.
  49. /// </summary>
  50. /// <value>The maximum bytes per second.</value>
  51. public long MaximumBytesPerSecond
  52. {
  53. get
  54. {
  55. return _maximumBytesPerSecond;
  56. }
  57. set
  58. {
  59. if (MaximumBytesPerSecond != value)
  60. {
  61. _maximumBytesPerSecond = value;
  62. Reset();
  63. }
  64. }
  65. }
  66. /// <summary>
  67. /// Gets a value indicating whether the current stream supports reading.
  68. /// </summary>
  69. /// <returns>true if the stream supports reading; otherwise, false.</returns>
  70. public override bool CanRead
  71. {
  72. get
  73. {
  74. return _baseStream.CanRead;
  75. }
  76. }
  77. /// <summary>
  78. /// Gets a value indicating whether the current stream supports seeking.
  79. /// </summary>
  80. /// <value></value>
  81. /// <returns>true if the stream supports seeking; otherwise, false.</returns>
  82. public override bool CanSeek
  83. {
  84. get
  85. {
  86. return _baseStream.CanSeek;
  87. }
  88. }
  89. /// <summary>
  90. /// Gets a value indicating whether the current stream supports writing.
  91. /// </summary>
  92. /// <value></value>
  93. /// <returns>true if the stream supports writing; otherwise, false.</returns>
  94. public override bool CanWrite
  95. {
  96. get
  97. {
  98. return _baseStream.CanWrite;
  99. }
  100. }
  101. /// <summary>
  102. /// Gets the length in bytes of the stream.
  103. /// </summary>
  104. /// <value></value>
  105. /// <returns>A long value representing the length of the stream in bytes.</returns>
  106. /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking. </exception>
  107. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  108. public override long Length
  109. {
  110. get
  111. {
  112. return _baseStream.Length;
  113. }
  114. }
  115. /// <summary>
  116. /// Gets or sets the position within the current stream.
  117. /// </summary>
  118. /// <value></value>
  119. /// <returns>The current position within the stream.</returns>
  120. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  121. /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking. </exception>
  122. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  123. public override long Position
  124. {
  125. get
  126. {
  127. return _baseStream.Position;
  128. }
  129. set
  130. {
  131. _baseStream.Position = value;
  132. }
  133. }
  134. #endregion
  135. public long MinThrottlePosition;
  136. #region Ctor
  137. /// <summary>
  138. /// Initializes a new instance of the <see cref="T:ThrottledStream"/> class.
  139. /// </summary>
  140. /// <param name="baseStream">The base stream.</param>
  141. /// <param name="maximumBytesPerSecond">The maximum bytes per second that can be transferred through the base stream.</param>
  142. /// <exception cref="ArgumentNullException">Thrown when <see cref="baseStream"/> is a null reference.</exception>
  143. /// <exception cref="ArgumentOutOfRangeException">Thrown when <see cref="maximumBytesPerSecond"/> is a negative value.</exception>
  144. public ThrottledStream(Stream baseStream, long maximumBytesPerSecond)
  145. {
  146. if (baseStream == null)
  147. {
  148. throw new ArgumentNullException("baseStream");
  149. }
  150. if (maximumBytesPerSecond < 0)
  151. {
  152. throw new ArgumentOutOfRangeException("maximumBytesPerSecond",
  153. maximumBytesPerSecond, "The maximum number of bytes per second can't be negative.");
  154. }
  155. _baseStream = baseStream;
  156. _maximumBytesPerSecond = maximumBytesPerSecond;
  157. _start = CurrentMilliseconds;
  158. _byteCount = 0;
  159. }
  160. #endregion
  161. #region Public methods
  162. /// <summary>
  163. /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
  164. /// </summary>
  165. /// <exception cref="T:System.IO.IOException">An I/O error occurs.</exception>
  166. public override void Flush()
  167. {
  168. _baseStream.Flush();
  169. }
  170. /// <summary>
  171. /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
  172. /// </summary>
  173. /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
  174. /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
  175. /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
  176. /// <returns>
  177. /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
  178. /// </returns>
  179. /// <exception cref="T:System.ArgumentException">The sum of offset and count is larger than the buffer length. </exception>
  180. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  181. /// <exception cref="T:System.NotSupportedException">The base stream does not support reading. </exception>
  182. /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception>
  183. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  184. /// <exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception>
  185. public override int Read(byte[] buffer, int offset, int count)
  186. {
  187. Throttle(count);
  188. return _baseStream.Read(buffer, offset, count);
  189. }
  190. /// <summary>
  191. /// Sets the position within the current stream.
  192. /// </summary>
  193. /// <param name="offset">A byte offset relative to the origin parameter.</param>
  194. /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"></see> indicating the reference point used to obtain the new position.</param>
  195. /// <returns>
  196. /// The new position within the current stream.
  197. /// </returns>
  198. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  199. /// <exception cref="T:System.NotSupportedException">The base stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
  200. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  201. public override long Seek(long offset, SeekOrigin origin)
  202. {
  203. return _baseStream.Seek(offset, origin);
  204. }
  205. /// <summary>
  206. /// Sets the length of the current stream.
  207. /// </summary>
  208. /// <param name="value">The desired length of the current stream in bytes.</param>
  209. /// <exception cref="T:System.NotSupportedException">The base stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. </exception>
  210. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  211. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  212. public override void SetLength(long value)
  213. {
  214. _baseStream.SetLength(value);
  215. }
  216. private long _bytesWritten;
  217. /// <summary>
  218. /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
  219. /// </summary>
  220. /// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
  221. /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
  222. /// <param name="count">The number of bytes to be written to the current stream.</param>
  223. /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
  224. /// <exception cref="T:System.NotSupportedException">The base stream does not support writing. </exception>
  225. /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
  226. /// <exception cref="T:System.ArgumentNullException">buffer is null. </exception>
  227. /// <exception cref="T:System.ArgumentException">The sum of offset and count is greater than the buffer length. </exception>
  228. /// <exception cref="T:System.ArgumentOutOfRangeException">offset or count is negative. </exception>
  229. public override void Write(byte[] buffer, int offset, int count)
  230. {
  231. Throttle(count);
  232. _baseStream.Write(buffer, offset, count);
  233. _bytesWritten += count;
  234. }
  235. public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  236. {
  237. await ThrottleAsync(count, cancellationToken).ConfigureAwait(false);
  238. await _baseStream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
  239. _bytesWritten += count;
  240. }
  241. /// <summary>
  242. /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
  243. /// </summary>
  244. /// <returns>
  245. /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
  246. /// </returns>
  247. public override string ToString()
  248. {
  249. return _baseStream.ToString();
  250. }
  251. #endregion
  252. private bool ThrottleCheck(int bufferSizeInBytes)
  253. {
  254. if (_bytesWritten < MinThrottlePosition)
  255. {
  256. return false;
  257. }
  258. // Make sure the buffer isn't empty.
  259. if (_maximumBytesPerSecond <= 0 || bufferSizeInBytes <= 0)
  260. {
  261. return false;
  262. }
  263. if (ThrottleCallback != null)
  264. {
  265. var val = ThrottleCallback(_maximumBytesPerSecond, _bytesWritten);
  266. if (val == 0)
  267. {
  268. return false;
  269. }
  270. }
  271. return true;
  272. }
  273. #region Protected methods
  274. /// <summary>
  275. /// Throttles for the specified buffer size in bytes.
  276. /// </summary>
  277. /// <param name="bufferSizeInBytes">The buffer size in bytes.</param>
  278. protected void Throttle(int bufferSizeInBytes)
  279. {
  280. if (!ThrottleCheck(bufferSizeInBytes))
  281. {
  282. return ;
  283. }
  284. _byteCount += bufferSizeInBytes;
  285. long elapsedMilliseconds = CurrentMilliseconds - _start;
  286. if (elapsedMilliseconds > 0)
  287. {
  288. // Calculate the current bps.
  289. long bps = _byteCount * 1000L / elapsedMilliseconds;
  290. // If the bps are more then the maximum bps, try to throttle.
  291. if (bps > _maximumBytesPerSecond)
  292. {
  293. // Calculate the time to sleep.
  294. long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond;
  295. int toSleep = (int)(wakeElapsed - elapsedMilliseconds);
  296. if (toSleep > 1)
  297. {
  298. try
  299. {
  300. // The time to sleep is more then a millisecond, so sleep.
  301. Thread.Sleep(toSleep);
  302. }
  303. catch (ThreadAbortException)
  304. {
  305. // Eatup ThreadAbortException.
  306. }
  307. // A sleep has been done, reset.
  308. Reset();
  309. }
  310. }
  311. }
  312. }
  313. protected async Task ThrottleAsync(int bufferSizeInBytes, CancellationToken cancellationToken)
  314. {
  315. if (!ThrottleCheck(bufferSizeInBytes))
  316. {
  317. return;
  318. }
  319. _byteCount += bufferSizeInBytes;
  320. long elapsedMilliseconds = CurrentMilliseconds - _start;
  321. if (elapsedMilliseconds > 0)
  322. {
  323. // Calculate the current bps.
  324. long bps = _byteCount * 1000L / elapsedMilliseconds;
  325. // If the bps are more then the maximum bps, try to throttle.
  326. if (bps > _maximumBytesPerSecond)
  327. {
  328. // Calculate the time to sleep.
  329. long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond;
  330. int toSleep = (int)(wakeElapsed - elapsedMilliseconds);
  331. if (toSleep > 1)
  332. {
  333. // The time to sleep is more then a millisecond, so sleep.
  334. await Task.Delay(toSleep, cancellationToken).ConfigureAwait(false);
  335. // A sleep has been done, reset.
  336. Reset();
  337. }
  338. }
  339. }
  340. }
  341. /// <summary>
  342. /// Will reset the bytecount to 0 and reset the start time to the current time.
  343. /// </summary>
  344. protected void Reset()
  345. {
  346. long difference = CurrentMilliseconds - _start;
  347. // Only reset counters when a known history is available of more then 1 second.
  348. if (difference > 1000)
  349. {
  350. _byteCount = 0;
  351. _start = CurrentMilliseconds;
  352. }
  353. }
  354. #endregion
  355. }
  356. }