ProgressiveStreamWriter.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Model.IO;
  7. using MediaBrowser.Controller.Net;
  8. using System.Collections.Generic;
  9. using MediaBrowser.Controller.IO;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Model.Services;
  12. using MediaBrowser.Model.System;
  13. namespace MediaBrowser.Api.Playback.Progressive
  14. {
  15. public class ProgressiveFileCopier : IAsyncStreamWriter, IHasHeaders
  16. {
  17. private readonly IFileSystem _fileSystem;
  18. private readonly TranscodingJob _job;
  19. private readonly ILogger _logger;
  20. private readonly string _path;
  21. private readonly CancellationToken _cancellationToken;
  22. private readonly Dictionary<string, string> _outputHeaders;
  23. const int StreamCopyToBufferSize = 81920;
  24. private long _bytesWritten = 0;
  25. public long StartPosition { get; set; }
  26. public bool AllowEndOfFile = true;
  27. private readonly IDirectStreamProvider _directStreamProvider;
  28. private readonly IEnvironmentInfo _environment;
  29. public ProgressiveFileCopier(IFileSystem fileSystem, string path, Dictionary<string, string> outputHeaders, TranscodingJob job, ILogger logger, IEnvironmentInfo environment, CancellationToken cancellationToken)
  30. {
  31. _fileSystem = fileSystem;
  32. _path = path;
  33. _outputHeaders = outputHeaders;
  34. _job = job;
  35. _logger = logger;
  36. _cancellationToken = cancellationToken;
  37. _environment = environment;
  38. }
  39. public ProgressiveFileCopier(IDirectStreamProvider directStreamProvider, Dictionary<string, string> outputHeaders, TranscodingJob job, ILogger logger, IEnvironmentInfo environment, CancellationToken cancellationToken)
  40. {
  41. _directStreamProvider = directStreamProvider;
  42. _outputHeaders = outputHeaders;
  43. _job = job;
  44. _logger = logger;
  45. _cancellationToken = cancellationToken;
  46. _environment = environment;
  47. }
  48. public IDictionary<string, string> Headers
  49. {
  50. get
  51. {
  52. return _outputHeaders;
  53. }
  54. }
  55. private Stream GetInputStream(bool allowAsyncFileRead)
  56. {
  57. var fileOpenOptions = StartPosition > 0
  58. ? FileOpenOptions.RandomAccess
  59. : FileOpenOptions.SequentialScan;
  60. if (allowAsyncFileRead)
  61. {
  62. fileOpenOptions |= FileOpenOptions.Asynchronous;
  63. }
  64. return _fileSystem.GetFileStream(_path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
  65. }
  66. public async Task WriteToAsync(Stream outputStream, CancellationToken cancellationToken)
  67. {
  68. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cancellationToken).Token;
  69. try
  70. {
  71. if (_directStreamProvider != null)
  72. {
  73. await _directStreamProvider.CopyToAsync(outputStream, cancellationToken).ConfigureAwait(false);
  74. return;
  75. }
  76. var eofCount = 0;
  77. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  78. var allowAsyncFileRead = _environment.OperatingSystem != OperatingSystem.Windows;
  79. using (var inputStream = GetInputStream(allowAsyncFileRead))
  80. {
  81. if (StartPosition > 0)
  82. {
  83. inputStream.Position = StartPosition;
  84. }
  85. while (eofCount < 20 || !AllowEndOfFile)
  86. {
  87. int bytesRead;
  88. if (allowAsyncFileRead)
  89. {
  90. bytesRead = await CopyToInternalAsync(inputStream, outputStream, cancellationToken).ConfigureAwait(false);
  91. }
  92. else
  93. {
  94. bytesRead = await CopyToInternalAsyncWithSyncRead(inputStream, outputStream, cancellationToken).ConfigureAwait(false);
  95. }
  96. //var position = fs.Position;
  97. //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
  98. if (bytesRead == 0)
  99. {
  100. if (_job == null || _job.HasExited)
  101. {
  102. eofCount++;
  103. }
  104. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  105. }
  106. else
  107. {
  108. eofCount = 0;
  109. }
  110. }
  111. }
  112. }
  113. finally
  114. {
  115. if (_job != null)
  116. {
  117. ApiEntryPoint.Instance.OnTranscodeEndRequest(_job);
  118. }
  119. }
  120. }
  121. private async Task<int> CopyToInternalAsyncWithSyncRead(Stream source, Stream destination, CancellationToken cancellationToken)
  122. {
  123. var array = new byte[StreamCopyToBufferSize];
  124. int bytesRead;
  125. int totalBytesRead = 0;
  126. while ((bytesRead = source.Read(array, 0, array.Length)) != 0)
  127. {
  128. var bytesToWrite = bytesRead;
  129. if (bytesToWrite > 0)
  130. {
  131. await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
  132. _bytesWritten += bytesRead;
  133. totalBytesRead += bytesRead;
  134. if (_job != null)
  135. {
  136. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  137. }
  138. }
  139. }
  140. return totalBytesRead;
  141. }
  142. private async Task<int> CopyToInternalAsync(Stream source, Stream destination, CancellationToken cancellationToken)
  143. {
  144. var array = new byte[StreamCopyToBufferSize];
  145. int bytesRead;
  146. int totalBytesRead = 0;
  147. while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
  148. {
  149. var bytesToWrite = bytesRead;
  150. if (bytesToWrite > 0)
  151. {
  152. await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
  153. _bytesWritten += bytesRead;
  154. totalBytesRead += bytesRead;
  155. if (_job != null)
  156. {
  157. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  158. }
  159. }
  160. }
  161. return totalBytesRead;
  162. }
  163. }
  164. }