ProgressiveFileStream.cs 5.6 KB

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