RangeRequestWriter.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Buffers;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Net;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Model.Services;
  11. using Microsoft.Net.Http.Headers;
  12. namespace Emby.Server.Implementations.HttpServer
  13. {
  14. public class RangeRequestWriter : IAsyncStreamWriter, IHttpResult
  15. {
  16. private const int BufferSize = 81920;
  17. private readonly Dictionary<string, string> _options = new Dictionary<string, string>();
  18. private List<KeyValuePair<long, long?>> _requestedRanges;
  19. /// <summary>
  20. /// Initializes a new instance of the <see cref="RangeRequestWriter" /> class.
  21. /// </summary>
  22. /// <param name="rangeHeader">The range header.</param>
  23. /// <param name="contentLength">The content length.</param>
  24. /// <param name="source">The source.</param>
  25. /// <param name="contentType">Type of the content.</param>
  26. /// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
  27. public RangeRequestWriter(string rangeHeader, long contentLength, Stream source, string contentType, bool isHeadRequest)
  28. {
  29. if (string.IsNullOrEmpty(contentType))
  30. {
  31. throw new ArgumentNullException(nameof(contentType));
  32. }
  33. RangeHeader = rangeHeader;
  34. SourceStream = source;
  35. IsHeadRequest = isHeadRequest;
  36. ContentType = contentType;
  37. Headers[HeaderNames.ContentType] = contentType;
  38. Headers[HeaderNames.AcceptRanges] = "bytes";
  39. StatusCode = HttpStatusCode.PartialContent;
  40. SetRangeValues(contentLength);
  41. }
  42. /// <summary>
  43. /// Gets or sets the source stream.
  44. /// </summary>
  45. /// <value>The source stream.</value>
  46. private Stream SourceStream { get; set; }
  47. private string RangeHeader { get; set; }
  48. private bool IsHeadRequest { get; set; }
  49. private long RangeStart { get; set; }
  50. private long RangeEnd { get; set; }
  51. private long RangeLength { get; set; }
  52. private long TotalContentLength { get; set; }
  53. public Action OnComplete { get; set; }
  54. /// <summary>
  55. /// Additional HTTP Headers
  56. /// </summary>
  57. /// <value>The headers.</value>
  58. public IDictionary<string, string> Headers => _options;
  59. /// <summary>
  60. /// Gets the requested ranges.
  61. /// </summary>
  62. /// <value>The requested ranges.</value>
  63. protected List<KeyValuePair<long, long?>> RequestedRanges
  64. {
  65. get
  66. {
  67. if (_requestedRanges == null)
  68. {
  69. _requestedRanges = new List<KeyValuePair<long, long?>>();
  70. // Example: bytes=0-,32-63
  71. var ranges = RangeHeader.Split('=')[1].Split(',');
  72. foreach (var range in ranges)
  73. {
  74. var vals = range.Split('-');
  75. long start = 0;
  76. long? end = null;
  77. if (!string.IsNullOrEmpty(vals[0]))
  78. {
  79. start = long.Parse(vals[0], CultureInfo.InvariantCulture);
  80. }
  81. if (!string.IsNullOrEmpty(vals[1]))
  82. {
  83. end = long.Parse(vals[1], CultureInfo.InvariantCulture);
  84. }
  85. _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
  86. }
  87. }
  88. return _requestedRanges;
  89. }
  90. }
  91. public string ContentType { get; set; }
  92. public IRequest RequestContext { get; set; }
  93. public object Response { get; set; }
  94. public int Status { get; set; }
  95. public HttpStatusCode StatusCode
  96. {
  97. get => (HttpStatusCode)Status;
  98. set => Status = (int)value;
  99. }
  100. /// <summary>
  101. /// Sets the range values.
  102. /// </summary>
  103. private void SetRangeValues(long contentLength)
  104. {
  105. var requestedRange = RequestedRanges[0];
  106. TotalContentLength = contentLength;
  107. // If the requested range is "0-", we can optimize by just doing a stream copy
  108. if (!requestedRange.Value.HasValue)
  109. {
  110. RangeEnd = TotalContentLength - 1;
  111. }
  112. else
  113. {
  114. RangeEnd = requestedRange.Value.Value;
  115. }
  116. RangeStart = requestedRange.Key;
  117. RangeLength = 1 + RangeEnd - RangeStart;
  118. Headers[HeaderNames.ContentLength] = RangeLength.ToString(CultureInfo.InvariantCulture);
  119. Headers[HeaderNames.ContentRange] = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
  120. if (RangeStart > 0 && SourceStream.CanSeek)
  121. {
  122. SourceStream.Position = RangeStart;
  123. }
  124. }
  125. public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)
  126. {
  127. try
  128. {
  129. // Headers only
  130. if (IsHeadRequest)
  131. {
  132. return;
  133. }
  134. using (var source = SourceStream)
  135. {
  136. // If the requested range is "0-", we can optimize by just doing a stream copy
  137. if (RangeEnd >= TotalContentLength - 1)
  138. {
  139. await source.CopyToAsync(responseStream, BufferSize, cancellationToken).ConfigureAwait(false);
  140. }
  141. else
  142. {
  143. await CopyToInternalAsync(source, responseStream, RangeLength, cancellationToken).ConfigureAwait(false);
  144. }
  145. }
  146. }
  147. finally
  148. {
  149. OnComplete?.Invoke();
  150. }
  151. }
  152. private static async Task CopyToInternalAsync(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
  153. {
  154. var array = ArrayPool<byte>.Shared.Rent(BufferSize);
  155. try
  156. {
  157. int bytesRead;
  158. while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
  159. {
  160. var bytesToCopy = Math.Min(bytesRead, copyLength);
  161. await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToCopy), cancellationToken).ConfigureAwait(false);
  162. copyLength -= bytesToCopy;
  163. if (copyLength <= 0)
  164. {
  165. break;
  166. }
  167. }
  168. }
  169. finally
  170. {
  171. ArrayPool<byte>.Shared.Return(array);
  172. }
  173. }
  174. }
  175. }