ProgressiveFileStream.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  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 bool _allowAsyncFileRead;
  19. private int _bytesWritten;
  20. private bool _disposed;
  21. /// <summary>
  22. /// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
  23. /// </summary>
  24. /// <param name="filePath">The path to the transcoded file.</param>
  25. /// <param name="job">The transcoding job information.</param>
  26. /// <param name="transcodingJobHelper">The transcoding job helper.</param>
  27. public ProgressiveFileStream(string filePath, TranscodingJobDto? job, TranscodingJobHelper transcodingJobHelper)
  28. {
  29. _job = job;
  30. _transcodingJobHelper = transcodingJobHelper;
  31. _bytesWritten = 0;
  32. var fileOptions = FileOptions.SequentialScan;
  33. _allowAsyncFileRead = false;
  34. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  35. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  36. {
  37. fileOptions |= FileOptions.Asynchronous;
  38. _allowAsyncFileRead = true;
  39. }
  40. _fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, fileOptions);
  41. }
  42. /// <inheritdoc />
  43. public override bool CanRead => _fileStream.CanRead;
  44. /// <inheritdoc />
  45. public override bool CanSeek => false;
  46. /// <inheritdoc />
  47. public override bool CanWrite => false;
  48. /// <inheritdoc />
  49. public override long Length => throw new NotSupportedException();
  50. /// <inheritdoc />
  51. public override long Position
  52. {
  53. get => throw new NotSupportedException();
  54. set => throw new NotSupportedException();
  55. }
  56. /// <inheritdoc />
  57. public override void Flush()
  58. {
  59. _fileStream.Flush();
  60. }
  61. /// <inheritdoc />
  62. public override int Read(byte[] buffer, int offset, int count)
  63. {
  64. return _fileStream.Read(buffer, offset, count);
  65. }
  66. /// <inheritdoc />
  67. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  68. {
  69. var eofCount = 0;
  70. const int EmptyReadLimit = 20;
  71. int totalBytesRead = 0;
  72. int remainingBytesToRead = count;
  73. while (eofCount < EmptyReadLimit && remainingBytesToRead > 0)
  74. {
  75. cancellationToken.ThrowIfCancellationRequested();
  76. int bytesRead;
  77. if (_allowAsyncFileRead)
  78. {
  79. bytesRead = await _fileStream.ReadAsync(buffer, offset, remainingBytesToRead, cancellationToken).ConfigureAwait(false);
  80. }
  81. else
  82. {
  83. bytesRead = _fileStream.Read(buffer, offset, remainingBytesToRead);
  84. }
  85. remainingBytesToRead -= bytesRead;
  86. if (bytesRead > 0)
  87. {
  88. _bytesWritten += bytesRead;
  89. totalBytesRead += bytesRead;
  90. if (_job != null)
  91. {
  92. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  93. }
  94. }
  95. if (bytesRead == 0)
  96. {
  97. if (_job == null || _job.HasExited)
  98. {
  99. eofCount++;
  100. }
  101. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  102. }
  103. else
  104. {
  105. eofCount = 0;
  106. }
  107. }
  108. return totalBytesRead;
  109. }
  110. /// <inheritdoc />
  111. public override long Seek(long offset, SeekOrigin origin)
  112. => throw new NotSupportedException();
  113. /// <inheritdoc />
  114. public override void SetLength(long value)
  115. => throw new NotSupportedException();
  116. /// <inheritdoc />
  117. public override void Write(byte[] buffer, int offset, int count)
  118. => throw new NotSupportedException();
  119. /// <inheritdoc />
  120. protected override void Dispose(bool disposing)
  121. {
  122. if (_disposed)
  123. {
  124. return;
  125. }
  126. if (disposing)
  127. {
  128. _fileStream.Dispose();
  129. if (_job != null)
  130. {
  131. _transcodingJobHelper.OnTranscodeEndRequest(_job);
  132. }
  133. }
  134. _disposed = true;
  135. }
  136. }
  137. }