ProgressiveFileStream.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Api.Models.PlaybackDtos;
  7. using MediaBrowser.Model.IO;
  8. namespace Jellyfin.Api.Helpers
  9. {
  10. /// <summary>
  11. /// A progressive file stream for transferring transcoded files as they are written to.
  12. /// </summary>
  13. public class ProgressiveFileStream : Stream
  14. {
  15. private readonly Stream _stream;
  16. private readonly TranscodingJobDto? _job;
  17. private readonly TranscodingJobHelper? _transcodingJobHelper;
  18. private readonly int _timeoutMs;
  19. private readonly bool _allowAsyncFileRead;
  20. private int _bytesWritten;
  21. private bool _disposed;
  22. /// <summary>
  23. /// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
  24. /// </summary>
  25. /// <param name="filePath">The path to the transcoded file.</param>
  26. /// <param name="job">The transcoding job information.</param>
  27. /// <param name="transcodingJobHelper">The transcoding job helper.</param>
  28. /// <param name="timeoutMs">The timeout duration in milliseconds.</param>
  29. public ProgressiveFileStream(string filePath, TranscodingJobDto? job, TranscodingJobHelper transcodingJobHelper, int timeoutMs = 30000)
  30. {
  31. _job = job;
  32. _transcodingJobHelper = transcodingJobHelper;
  33. _timeoutMs = timeoutMs;
  34. var fileOptions = FileOptions.SequentialScan;
  35. _allowAsyncFileRead = false;
  36. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  37. if (AsyncFile.UseAsyncIO)
  38. {
  39. fileOptions |= FileOptions.Asynchronous;
  40. _allowAsyncFileRead = true;
  41. }
  42. _stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions);
  43. }
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
  46. /// </summary>
  47. /// <param name="stream">The stream to progressively copy.</param>
  48. /// <param name="timeoutMs">The timeout duration in milliseconds.</param>
  49. public ProgressiveFileStream(Stream stream, int timeoutMs = 30000)
  50. {
  51. _job = null;
  52. _transcodingJobHelper = null;
  53. _timeoutMs = timeoutMs;
  54. _allowAsyncFileRead = AsyncFile.UseAsyncIO;
  55. _stream = stream;
  56. }
  57. /// <inheritdoc />
  58. public override bool CanRead => _stream.CanRead;
  59. /// <inheritdoc />
  60. public override bool CanSeek => false;
  61. /// <inheritdoc />
  62. public override bool CanWrite => false;
  63. /// <inheritdoc />
  64. public override long Length => throw new NotSupportedException();
  65. /// <inheritdoc />
  66. public override long Position
  67. {
  68. get => throw new NotSupportedException();
  69. set => throw new NotSupportedException();
  70. }
  71. /// <inheritdoc />
  72. public override void Flush()
  73. {
  74. _stream.Flush();
  75. }
  76. /// <inheritdoc />
  77. public override int Read(byte[] buffer, int offset, int count)
  78. {
  79. return _stream.Read(buffer, offset, count);
  80. }
  81. /// <inheritdoc />
  82. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  83. {
  84. int totalBytesRead = 0;
  85. int remainingBytesToRead = count;
  86. var stopwatch = Stopwatch.StartNew();
  87. int newOffset = offset;
  88. while (remainingBytesToRead > 0)
  89. {
  90. cancellationToken.ThrowIfCancellationRequested();
  91. int bytesRead;
  92. if (_allowAsyncFileRead)
  93. {
  94. bytesRead = await _stream.ReadAsync(buffer, newOffset, remainingBytesToRead, cancellationToken).ConfigureAwait(false);
  95. }
  96. else
  97. {
  98. bytesRead = _stream.Read(buffer, newOffset, remainingBytesToRead);
  99. }
  100. remainingBytesToRead -= bytesRead;
  101. newOffset += bytesRead;
  102. if (bytesRead > 0)
  103. {
  104. _bytesWritten += bytesRead;
  105. totalBytesRead += bytesRead;
  106. if (_job != null)
  107. {
  108. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  109. }
  110. }
  111. else
  112. {
  113. // If the job is null it's a live stream and will require user action to close, but don't keep it open indefinitely
  114. if (_job?.HasExited ?? stopwatch.ElapsedMilliseconds > _timeoutMs)
  115. {
  116. break;
  117. }
  118. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  119. }
  120. }
  121. return totalBytesRead;
  122. }
  123. /// <inheritdoc />
  124. public override long Seek(long offset, SeekOrigin origin)
  125. => throw new NotSupportedException();
  126. /// <inheritdoc />
  127. public override void SetLength(long value)
  128. => throw new NotSupportedException();
  129. /// <inheritdoc />
  130. public override void Write(byte[] buffer, int offset, int count)
  131. => throw new NotSupportedException();
  132. /// <inheritdoc />
  133. protected override void Dispose(bool disposing)
  134. {
  135. if (_disposed)
  136. {
  137. return;
  138. }
  139. try
  140. {
  141. if (disposing)
  142. {
  143. _stream.Dispose();
  144. if (_job != null)
  145. {
  146. _transcodingJobHelper?.OnTranscodeEndRequest(_job);
  147. }
  148. }
  149. }
  150. finally
  151. {
  152. _disposed = true;
  153. base.Dispose(disposing);
  154. }
  155. }
  156. }
  157. }