2
0

ProgressiveFileStream.cs 6.0 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 bool _disposed;
  20. /// <summary>
  21. /// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
  22. /// </summary>
  23. /// <param name="filePath">The path to the transcoded file.</param>
  24. /// <param name="job">The transcoding job information.</param>
  25. /// <param name="transcodingJobHelper">The transcoding job helper.</param>
  26. /// <param name="timeoutMs">The timeout duration in milliseconds.</param>
  27. public ProgressiveFileStream(string filePath, TranscodingJobDto? job, TranscodingJobHelper transcodingJobHelper, int timeoutMs = 30000)
  28. {
  29. _job = job;
  30. _transcodingJobHelper = transcodingJobHelper;
  31. _timeoutMs = timeoutMs;
  32. _stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
  33. }
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="ProgressiveFileStream"/> class.
  36. /// </summary>
  37. /// <param name="stream">The stream to progressively copy.</param>
  38. /// <param name="timeoutMs">The timeout duration in milliseconds.</param>
  39. public ProgressiveFileStream(Stream stream, int timeoutMs = 30000)
  40. {
  41. _job = null;
  42. _transcodingJobHelper = null;
  43. _timeoutMs = timeoutMs;
  44. _stream = stream;
  45. }
  46. /// <inheritdoc />
  47. public override bool CanRead => _stream.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. // Not supported
  64. }
  65. /// <inheritdoc />
  66. public override int Read(byte[] buffer, int offset, int count)
  67. => Read(buffer.AsSpan(offset, count));
  68. /// <inheritdoc />
  69. public override int Read(Span<byte> buffer)
  70. {
  71. int totalBytesRead = 0;
  72. var stopwatch = Stopwatch.StartNew();
  73. while (true)
  74. {
  75. totalBytesRead += _stream.Read(buffer);
  76. if (StopReading(totalBytesRead, stopwatch.ElapsedMilliseconds))
  77. {
  78. break;
  79. }
  80. Thread.Sleep(50);
  81. }
  82. UpdateBytesWritten(totalBytesRead);
  83. return totalBytesRead;
  84. }
  85. /// <inheritdoc />
  86. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  87. => await ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);
  88. /// <inheritdoc />
  89. public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
  90. {
  91. int totalBytesRead = 0;
  92. var stopwatch = Stopwatch.StartNew();
  93. while (true)
  94. {
  95. totalBytesRead += await _stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
  96. if (StopReading(totalBytesRead, stopwatch.ElapsedMilliseconds))
  97. {
  98. break;
  99. }
  100. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  101. }
  102. UpdateBytesWritten(totalBytesRead);
  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. private void UpdateBytesWritten(int totalBytesRead)
  139. {
  140. if (_job != null)
  141. {
  142. _job.BytesDownloaded += totalBytesRead;
  143. }
  144. }
  145. private bool StopReading(int bytesRead, long elapsed)
  146. {
  147. // It should stop reading when anything has been successfully read or if the job has exited
  148. // If the job is null, however, it's a live stream and will require user action to close,
  149. // but don't keep it open indefinitely if it isn't reading anything
  150. return bytesRead > 0 || (_job?.HasExited ?? elapsed >= _timeoutMs);
  151. }
  152. }
  153. }