ProgressiveStreamWriter.cs 6.6 KB

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