From 6a9dbf6ae85b4e7abcf06f7f29ef9d8b0b890876 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 29 Aug 2014 08:14:41 -0400 Subject: update translations --- .../HttpServer/HttpResultFactory.cs | 68 +++- .../HttpServer/RangeRequestWriter.cs | 10 + .../HttpServer/StreamWriter.cs | 12 +- .../HttpServer/ThrottledStream.cs | 389 +++++++++++++++++++++ 4 files changed, 460 insertions(+), 19 deletions(-) create mode 100644 MediaBrowser.Server.Implementations/HttpServer/ThrottledStream.cs (limited to 'MediaBrowser.Server.Implementations/HttpServer') diff --git a/MediaBrowser.Server.Implementations/HttpServer/HttpResultFactory.cs b/MediaBrowser.Server.Implementations/HttpServer/HttpResultFactory.cs index 6a60e5ea6..be3e5f005 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -298,8 +298,13 @@ namespace MediaBrowser.Server.Implementations.HttpServer /// The response headers. /// if set to true [is head request]. /// System.Object. + /// path /// path - public object GetStaticFileResult(IRequest requestContext, string path, FileShare fileShare = FileShare.Read, IDictionary responseHeaders = null, bool isHeadRequest = false) + public object GetStaticFileResult(IRequest requestContext, + string path, + FileShare fileShare = FileShare.Read, + IDictionary responseHeaders = null, + bool isHeadRequest = false) { if (string.IsNullOrEmpty(path)) { @@ -309,13 +314,15 @@ namespace MediaBrowser.Server.Implementations.HttpServer return GetStaticFileResult(requestContext, path, MimeTypes.GetMimeType(path), null, fileShare, responseHeaders, isHeadRequest); } - public object GetStaticFileResult(IRequest requestContext, - string path, + public object GetStaticFileResult(IRequest requestContext, + string path, string contentType, TimeSpan? cacheCuration = null, - FileShare fileShare = FileShare.Read, + FileShare fileShare = FileShare.Read, IDictionary responseHeaders = null, - bool isHeadRequest = false) + bool isHeadRequest = false, + bool throttle = false, + long throttleLimit = 0) { if (string.IsNullOrEmpty(path)) { @@ -331,7 +338,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer var cacheKey = path + dateModified.Ticks; - return GetStaticResult(requestContext, cacheKey.GetMD5(), dateModified, cacheCuration, contentType, () => Task.FromResult(GetFileStream(path, fileShare)), responseHeaders, isHeadRequest); + return GetStaticResult(requestContext, cacheKey.GetMD5(), dateModified, cacheCuration, contentType, () => Task.FromResult(GetFileStream(path, fileShare)), responseHeaders, isHeadRequest, throttle, throttleLimit); } /// @@ -360,7 +367,29 @@ namespace MediaBrowser.Server.Implementations.HttpServer /// cacheKey /// or /// factoryFn - public object GetStaticResult(IRequest requestContext, Guid cacheKey, DateTime? lastDateModified, TimeSpan? cacheDuration, string contentType, Func> factoryFn, IDictionary responseHeaders = null, bool isHeadRequest = false) + public object GetStaticResult(IRequest requestContext, + Guid cacheKey, + DateTime? lastDateModified, + TimeSpan? cacheDuration, + string contentType, + Func> factoryFn, + IDictionary responseHeaders = null, + bool isHeadRequest = false) + { + return GetStaticResult(requestContext, cacheKey, lastDateModified, cacheDuration, contentType, factoryFn, + responseHeaders, isHeadRequest, false, 0); + } + + public object GetStaticResult(IRequest requestContext, + Guid cacheKey, + DateTime? lastDateModified, + TimeSpan? cacheDuration, + string contentType, + Func> factoryFn, + IDictionary responseHeaders = null, + bool isHeadRequest = false, + bool throttle = false, + long throttleLimit = 0) { if (cacheKey == Guid.Empty) { @@ -386,15 +415,8 @@ namespace MediaBrowser.Server.Implementations.HttpServer return result; } - return GetNonCachedResult(requestContext, contentType, factoryFn, responseHeaders, isHeadRequest); - } - - private async Task GetNonCachedResult(IRequest requestContext, string contentType, Func> factoryFn, IDictionary responseHeaders = null, bool isHeadRequest = false) - { var compress = ShouldCompressResponse(requestContext, contentType); - - var hasOptions = await GetStaticResult(requestContext, responseHeaders, contentType, factoryFn, compress, isHeadRequest).ConfigureAwait(false); - + var hasOptions = GetStaticResult(requestContext, responseHeaders, contentType, factoryFn, compress, isHeadRequest, throttle, throttleLimit).Result; AddResponseHeaders(hasOptions, responseHeaders); return hasOptions; @@ -460,8 +482,10 @@ namespace MediaBrowser.Server.Implementations.HttpServer /// The factory fn. /// if set to true [compress]. /// if set to true [is head request]. + /// if set to true [throttle]. + /// The throttle limit. /// Task{IHasOptions}. - private async Task GetStaticResult(IRequest requestContext, IDictionary responseHeaders, string contentType, Func> factoryFn, bool compress, bool isHeadRequest) + private async Task GetStaticResult(IRequest requestContext, IDictionary responseHeaders, string contentType, Func> factoryFn, bool compress, bool isHeadRequest, bool throttle, long throttleLimit = 0) { var requestedCompressionType = requestContext.GetCompressionType(); @@ -473,7 +497,11 @@ namespace MediaBrowser.Server.Implementations.HttpServer if (!string.IsNullOrEmpty(rangeHeader)) { - return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest); + return new RangeRequestWriter(rangeHeader, stream, contentType, isHeadRequest) + { + Throttle = throttle, + ThrottleLimit = throttleLimit + }; } responseHeaders["Content-Length"] = stream.Length.ToString(UsCulture); @@ -485,7 +513,11 @@ namespace MediaBrowser.Server.Implementations.HttpServer return GetHttpResult(new byte[] { }, contentType); } - return new StreamWriter(stream, contentType, _logger); + return new StreamWriter(stream, contentType, _logger) + { + Throttle = throttle, + ThrottleLimit = throttleLimit + }; } string content; diff --git a/MediaBrowser.Server.Implementations/HttpServer/RangeRequestWriter.cs b/MediaBrowser.Server.Implementations/HttpServer/RangeRequestWriter.cs index 2e2f5e9f8..5fd43aa76 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -24,6 +24,9 @@ namespace MediaBrowser.Server.Implementations.HttpServer private long RangeLength { get; set; } private long TotalContentLength { get; set; } + public bool Throttle { get; set; } + public long ThrottleLimit { get; set; } + /// /// The _options /// @@ -159,6 +162,13 @@ namespace MediaBrowser.Server.Implementations.HttpServer /// The response stream. public void WriteTo(Stream responseStream) { + if (Throttle) + { + responseStream = new ThrottledStream(responseStream, ThrottleLimit) + { + MinThrottlePosition = ThrottleLimit * 180 + }; + } var task = WriteToAsync(responseStream); Task.WaitAll(task); diff --git a/MediaBrowser.Server.Implementations/HttpServer/StreamWriter.cs b/MediaBrowser.Server.Implementations/HttpServer/StreamWriter.cs index a8774f1b7..f1112ae0b 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/StreamWriter.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/StreamWriter.cs @@ -36,6 +36,9 @@ namespace MediaBrowser.Server.Implementations.HttpServer get { return _options; } } + public bool Throttle { get; set; } + public long ThrottleLimit { get; set; } + /// /// Initializes a new instance of the class. /// @@ -77,6 +80,13 @@ namespace MediaBrowser.Server.Implementations.HttpServer /// The response stream. public void WriteTo(Stream responseStream) { + if (Throttle) + { + responseStream = new ThrottledStream(responseStream, ThrottleLimit) + { + MinThrottlePosition = ThrottleLimit * 180 + }; + } var task = WriteToAsync(responseStream); Task.WaitAll(task); @@ -98,7 +108,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer } catch (Exception ex) { - Logger.ErrorException("Error streaming media", ex); + Logger.ErrorException("Error streaming data", ex); throw; } diff --git a/MediaBrowser.Server.Implementations/HttpServer/ThrottledStream.cs b/MediaBrowser.Server.Implementations/HttpServer/ThrottledStream.cs new file mode 100644 index 000000000..067e53571 --- /dev/null +++ b/MediaBrowser.Server.Implementations/HttpServer/ThrottledStream.cs @@ -0,0 +1,389 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Server.Implementations.HttpServer +{ + /// + /// Class for streaming data with throttling support. + /// + public class ThrottledStream : Stream + { + /// + /// A constant used to specify an infinite number of bytes that can be transferred per second. + /// + public const long Infinite = 0; + + #region Private members + /// + /// The base stream. + /// + private readonly Stream _baseStream; + + /// + /// The maximum bytes per second that can be transferred through the base stream. + /// + private long _maximumBytesPerSecond; + + /// + /// The number of bytes that has been transferred since the last throttle. + /// + private long _byteCount; + + /// + /// The start time in milliseconds of the last throttle. + /// + private long _start; + #endregion + + #region Properties + /// + /// Gets the current milliseconds. + /// + /// The current milliseconds. + protected long CurrentMilliseconds + { + get + { + return Environment.TickCount; + } + } + + /// + /// Gets or sets the maximum bytes per second that can be transferred through the base stream. + /// + /// The maximum bytes per second. + public long MaximumBytesPerSecond + { + get + { + return _maximumBytesPerSecond; + } + set + { + if (MaximumBytesPerSecond != value) + { + _maximumBytesPerSecond = value; + Reset(); + } + } + } + + /// + /// Gets a value indicating whether the current stream supports reading. + /// + /// true if the stream supports reading; otherwise, false. + public override bool CanRead + { + get + { + return _baseStream.CanRead; + } + } + + /// + /// Gets a value indicating whether the current stream supports seeking. + /// + /// + /// true if the stream supports seeking; otherwise, false. + public override bool CanSeek + { + get + { + return _baseStream.CanSeek; + } + } + + /// + /// Gets a value indicating whether the current stream supports writing. + /// + /// + /// true if the stream supports writing; otherwise, false. + public override bool CanWrite + { + get + { + return _baseStream.CanWrite; + } + } + + /// + /// Gets the length in bytes of the stream. + /// + /// + /// A long value representing the length of the stream in bytes. + /// The base stream does not support seeking. + /// Methods were called after the stream was closed. + public override long Length + { + get + { + return _baseStream.Length; + } + } + + /// + /// Gets or sets the position within the current stream. + /// + /// + /// The current position within the stream. + /// An I/O error occurs. + /// The base stream does not support seeking. + /// Methods were called after the stream was closed. + public override long Position + { + get + { + return _baseStream.Position; + } + set + { + _baseStream.Position = value; + } + } + #endregion + + public long MinThrottlePosition; + + #region Ctor + /// + /// Initializes a new instance of the class. + /// + /// The base stream. + /// The maximum bytes per second that can be transferred through the base stream. + /// Thrown when is a null reference. + /// Thrown when is a negative value. + public ThrottledStream(Stream baseStream, long maximumBytesPerSecond) + { + if (baseStream == null) + { + throw new ArgumentNullException("baseStream"); + } + + if (maximumBytesPerSecond < 0) + { + throw new ArgumentOutOfRangeException("maximumBytesPerSecond", + maximumBytesPerSecond, "The maximum number of bytes per second can't be negative."); + } + + _baseStream = baseStream; + _maximumBytesPerSecond = maximumBytesPerSecond; + _start = CurrentMilliseconds; + _byteCount = 0; + } + #endregion + + #region Public methods + /// + /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. + /// + /// An I/O error occurs. + public override void Flush() + { + _baseStream.Flush(); + } + + /// + /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. + /// + /// 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. + /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. + /// The maximum number of bytes to be read from the current stream. + /// + /// 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. + /// + /// The sum of offset and count is larger than the buffer length. + /// Methods were called after the stream was closed. + /// The base stream does not support reading. + /// buffer is null. + /// An I/O error occurs. + /// offset or count is negative. + public override int Read(byte[] buffer, int offset, int count) + { + Throttle(count); + + return _baseStream.Read(buffer, offset, count); + } + + /// + /// Sets the position within the current stream. + /// + /// A byte offset relative to the origin parameter. + /// A value of type indicating the reference point used to obtain the new position. + /// + /// The new position within the current stream. + /// + /// An I/O error occurs. + /// The base stream does not support seeking, such as if the stream is constructed from a pipe or console output. + /// Methods were called after the stream was closed. + public override long Seek(long offset, SeekOrigin origin) + { + return _baseStream.Seek(offset, origin); + } + + /// + /// Sets the length of the current stream. + /// + /// The desired length of the current stream in bytes. + /// The base stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. + /// An I/O error occurs. + /// Methods were called after the stream was closed. + public override void SetLength(long value) + { + _baseStream.SetLength(value); + } + + private long _bytesWritten; + + /// + /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. + /// + /// An array of bytes. This method copies count bytes from buffer to the current stream. + /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. + /// The number of bytes to be written to the current stream. + /// An I/O error occurs. + /// The base stream does not support writing. + /// Methods were called after the stream was closed. + /// buffer is null. + /// The sum of offset and count is greater than the buffer length. + /// offset or count is negative. + public override void Write(byte[] buffer, int offset, int count) + { + Throttle(count); + + _baseStream.Write(buffer, offset, count); + + _bytesWritten += count; + } + + public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + await ThrottleAsync(count, cancellationToken).ConfigureAwait(false); + + await _baseStream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); + + _bytesWritten += count; + } + + /// + /// Returns a that represents the current . + /// + /// + /// A that represents the current . + /// + public override string ToString() + { + return _baseStream.ToString(); + } + #endregion + + #region Protected methods + /// + /// Throttles for the specified buffer size in bytes. + /// + /// The buffer size in bytes. + protected void Throttle(int bufferSizeInBytes) + { + if (_bytesWritten < MinThrottlePosition) + { + return; + } + + // Make sure the buffer isn't empty. + if (_maximumBytesPerSecond <= 0 || bufferSizeInBytes <= 0) + { + return; + } + + _byteCount += bufferSizeInBytes; + long elapsedMilliseconds = CurrentMilliseconds - _start; + + if (elapsedMilliseconds > 0) + { + // Calculate the current bps. + long bps = _byteCount * 1000L / elapsedMilliseconds; + + // If the bps are more then the maximum bps, try to throttle. + if (bps > _maximumBytesPerSecond) + { + // Calculate the time to sleep. + long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond; + int toSleep = (int)(wakeElapsed - elapsedMilliseconds); + + if (toSleep > 1) + { + try + { + // The time to sleep is more then a millisecond, so sleep. + Thread.Sleep(toSleep); + } + catch (ThreadAbortException) + { + // Eatup ThreadAbortException. + } + + // A sleep has been done, reset. + Reset(); + } + } + } + } + + protected async Task ThrottleAsync(int bufferSizeInBytes, CancellationToken cancellationToken) + { + if (_bytesWritten < MinThrottlePosition) + { + return; + } + + // Make sure the buffer isn't empty. + if (_maximumBytesPerSecond <= 0 || bufferSizeInBytes <= 0) + { + return; + } + + _byteCount += bufferSizeInBytes; + long elapsedMilliseconds = CurrentMilliseconds - _start; + + if (elapsedMilliseconds > 0) + { + // Calculate the current bps. + long bps = _byteCount * 1000L / elapsedMilliseconds; + + // If the bps are more then the maximum bps, try to throttle. + if (bps > _maximumBytesPerSecond) + { + // Calculate the time to sleep. + long wakeElapsed = _byteCount * 1000L / _maximumBytesPerSecond; + int toSleep = (int)(wakeElapsed - elapsedMilliseconds); + + if (toSleep > 1) + { + // The time to sleep is more then a millisecond, so sleep. + await Task.Delay(toSleep, cancellationToken).ConfigureAwait(false); + + // A sleep has been done, reset. + Reset(); + } + } + } + } + + /// + /// Will reset the bytecount to 0 and reset the start time to the current time. + /// + protected void Reset() + { + long difference = CurrentMilliseconds - _start; + + // Only reset counters when a known history is available of more then 1 second. + if (difference > 1000) + { + _byteCount = 0; + _start = CurrentMilliseconds; + } + } + #endregion + } +} \ No newline at end of file -- cgit v1.2.3