ProgressiveFileStream.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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 FileStream _fileStream;
  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. _bytesWritten = 0;
  35. var fileOptions = FileOptions.SequentialScan;
  36. _allowAsyncFileRead = false;
  37. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  38. if (AsyncFile.UseAsyncIO)
  39. {
  40. fileOptions |= FileOptions.Asynchronous;
  41. _allowAsyncFileRead = true;
  42. }
  43. _fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions);
  44. }
  45. /// <inheritdoc />
  46. public override bool CanRead => _fileStream.CanRead;
  47. /// <inheritdoc />
  48. public override bool CanSeek => false;
  49. /// <inheritdoc />
  50. public override bool CanWrite => false;
  51. /// <inheritdoc />
  52. public override long Length => throw new NotSupportedException();
  53. /// <inheritdoc />
  54. public override long Position
  55. {
  56. get => throw new NotSupportedException();
  57. set => throw new NotSupportedException();
  58. }
  59. /// <inheritdoc />
  60. public override void Flush()
  61. {
  62. _fileStream.Flush();
  63. }
  64. /// <inheritdoc />
  65. public override int Read(byte[] buffer, int offset, int count)
  66. {
  67. return _fileStream.Read(buffer, offset, count);
  68. }
  69. /// <inheritdoc />
  70. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  71. {
  72. int totalBytesRead = 0;
  73. int remainingBytesToRead = count;
  74. var stopwatch = Stopwatch.StartNew();
  75. int newOffset = offset;
  76. while (remainingBytesToRead > 0)
  77. {
  78. cancellationToken.ThrowIfCancellationRequested();
  79. int bytesRead;
  80. if (_allowAsyncFileRead)
  81. {
  82. bytesRead = await _fileStream.ReadAsync(buffer, newOffset, remainingBytesToRead, cancellationToken).ConfigureAwait(false);
  83. }
  84. else
  85. {
  86. bytesRead = _fileStream.Read(buffer, newOffset, remainingBytesToRead);
  87. }
  88. remainingBytesToRead -= bytesRead;
  89. newOffset += bytesRead;
  90. if (bytesRead > 0)
  91. {
  92. _bytesWritten += bytesRead;
  93. totalBytesRead += bytesRead;
  94. if (_job != null)
  95. {
  96. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  97. }
  98. }
  99. else
  100. {
  101. // If the job is null it's a live stream and will require user action to close, but don't keep it open indefinitely
  102. if (_job?.HasExited ?? stopwatch.ElapsedMilliseconds > _timeoutMs)
  103. {
  104. break;
  105. }
  106. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  107. }
  108. }
  109. return totalBytesRead;
  110. }
  111. /// <inheritdoc />
  112. public override long Seek(long offset, SeekOrigin origin)
  113. => throw new NotSupportedException();
  114. /// <inheritdoc />
  115. public override void SetLength(long value)
  116. => throw new NotSupportedException();
  117. /// <inheritdoc />
  118. public override void Write(byte[] buffer, int offset, int count)
  119. => throw new NotSupportedException();
  120. /// <inheritdoc />
  121. protected override void Dispose(bool disposing)
  122. {
  123. if (_disposed)
  124. {
  125. return;
  126. }
  127. try
  128. {
  129. if (disposing)
  130. {
  131. _fileStream.Dispose();
  132. if (_job != null)
  133. {
  134. _transcodingJobHelper.OnTranscodeEndRequest(_job);
  135. }
  136. }
  137. }
  138. finally
  139. {
  140. _disposed = true;
  141. base.Dispose(disposing);
  142. }
  143. }
  144. }
  145. }