ProgressiveFileStream.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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 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. /// <param name="timeoutMs">The timeout duration in milliseconds.</param>
  28. public ProgressiveFileStream(string filePath, TranscodingJobDto? job, TranscodingJobHelper transcodingJobHelper, int timeoutMs = 30000)
  29. {
  30. _job = job;
  31. _transcodingJobHelper = transcodingJobHelper;
  32. _timeoutMs = timeoutMs;
  33. _stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
  34. }
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
  37. /// </summary>
  38. /// <param name="stream">The stream to progressively copy.</param>
  39. /// <param name="timeoutMs">The timeout duration in milliseconds.</param>
  40. public ProgressiveFileStream(Stream stream, int timeoutMs = 30000)
  41. {
  42. _job = null;
  43. _transcodingJobHelper = null;
  44. _timeoutMs = timeoutMs;
  45. _stream = stream;
  46. }
  47. /// <inheritdoc />
  48. public override bool CanRead => _stream.CanRead;
  49. /// <inheritdoc />
  50. public override bool CanSeek => false;
  51. /// <inheritdoc />
  52. public override bool CanWrite => false;
  53. /// <inheritdoc />
  54. public override long Length => throw new NotSupportedException();
  55. /// <inheritdoc />
  56. public override long Position
  57. {
  58. get => throw new NotSupportedException();
  59. set => throw new NotSupportedException();
  60. }
  61. /// <inheritdoc />
  62. public override void Flush()
  63. {
  64. _stream.Flush();
  65. }
  66. /// <inheritdoc />
  67. public override int Read(byte[] buffer, int offset, int count)
  68. {
  69. return _stream.Read(buffer, offset, count);
  70. }
  71. /// <inheritdoc />
  72. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  73. {
  74. int totalBytesRead = 0;
  75. int remainingBytesToRead = count;
  76. var stopwatch = Stopwatch.StartNew();
  77. int newOffset = offset;
  78. while (remainingBytesToRead > 0)
  79. {
  80. cancellationToken.ThrowIfCancellationRequested();
  81. int bytesRead = await _stream.ReadAsync(buffer, newOffset, remainingBytesToRead, cancellationToken).ConfigureAwait(false);
  82. remainingBytesToRead -= bytesRead;
  83. newOffset += bytesRead;
  84. if (bytesRead > 0)
  85. {
  86. _bytesWritten += bytesRead;
  87. totalBytesRead += bytesRead;
  88. if (_job != null)
  89. {
  90. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  91. }
  92. }
  93. else
  94. {
  95. // If the job is null it's a live stream and will require user action to close, but don't keep it open indefinitely
  96. if (_job?.HasExited ?? stopwatch.ElapsedMilliseconds > _timeoutMs)
  97. {
  98. break;
  99. }
  100. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  101. }
  102. }
  103. return totalBytesRead;
  104. }
  105. /// <inheritdoc />
  106. public override long Seek(long offset, SeekOrigin origin)
  107. => throw new NotSupportedException();
  108. /// <inheritdoc />
  109. public override void SetLength(long value)
  110. => throw new NotSupportedException();
  111. /// <inheritdoc />
  112. public override void Write(byte[] buffer, int offset, int count)
  113. => throw new NotSupportedException();
  114. /// <inheritdoc />
  115. protected override void Dispose(bool disposing)
  116. {
  117. if (_disposed)
  118. {
  119. return;
  120. }
  121. try
  122. {
  123. if (disposing)
  124. {
  125. _stream.Dispose();
  126. if (_job != null)
  127. {
  128. _transcodingJobHelper?.OnTranscodeEndRequest(_job);
  129. }
  130. }
  131. }
  132. finally
  133. {
  134. _disposed = true;
  135. base.Dispose(disposing);
  136. }
  137. }
  138. }
  139. }