ProgressiveStreamWriter.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. using MediaBrowser.Model.Logging;
  2. using ServiceStack.Web;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Threading.Tasks;
  7. using CommonIO;
  8. namespace MediaBrowser.Api.Playback.Progressive
  9. {
  10. public class ProgressiveStreamWriter : IStreamWriter, IHasOptions
  11. {
  12. private string Path { get; set; }
  13. private ILogger Logger { get; set; }
  14. private readonly IFileSystem _fileSystem;
  15. private readonly TranscodingJob _job;
  16. /// <summary>
  17. /// The _options
  18. /// </summary>
  19. private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
  20. /// <summary>
  21. /// Gets the options.
  22. /// </summary>
  23. /// <value>The options.</value>
  24. public IDictionary<string, string> Options
  25. {
  26. get { return _options; }
  27. }
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="ProgressiveStreamWriter" /> class.
  30. /// </summary>
  31. /// <param name="path">The path.</param>
  32. /// <param name="logger">The logger.</param>
  33. /// <param name="fileSystem">The file system.</param>
  34. public ProgressiveStreamWriter(string path, ILogger logger, IFileSystem fileSystem, TranscodingJob job)
  35. {
  36. Path = path;
  37. Logger = logger;
  38. _fileSystem = fileSystem;
  39. _job = job;
  40. }
  41. /// <summary>
  42. /// Writes to.
  43. /// </summary>
  44. /// <param name="responseStream">The response stream.</param>
  45. public void WriteTo(Stream responseStream)
  46. {
  47. var task = WriteToAsync(responseStream);
  48. Task.WaitAll(task);
  49. }
  50. /// <summary>
  51. /// Writes to.
  52. /// </summary>
  53. /// <param name="responseStream">The response stream.</param>
  54. public async Task WriteToAsync(Stream responseStream)
  55. {
  56. try
  57. {
  58. await new ProgressiveFileCopier(_fileSystem, _job, Logger).StreamFile(Path, responseStream).ConfigureAwait(false);
  59. }
  60. catch (IOException)
  61. {
  62. // These error are always the same so don't dump the whole stack trace
  63. Logger.Error("Error streaming media. The client has most likely disconnected or transcoding has failed.");
  64. throw;
  65. }
  66. catch (Exception ex)
  67. {
  68. Logger.ErrorException("Error streaming media. The client has most likely disconnected or transcoding has failed.", ex);
  69. throw;
  70. }
  71. finally
  72. {
  73. if (_job != null)
  74. {
  75. ApiEntryPoint.Instance.OnTranscodeEndRequest(_job);
  76. }
  77. }
  78. }
  79. }
  80. public class ProgressiveFileCopier
  81. {
  82. private readonly IFileSystem _fileSystem;
  83. private readonly TranscodingJob _job;
  84. private readonly ILogger _logger;
  85. // 256k
  86. private const int BufferSize = 262144;
  87. private long _bytesWritten = 0;
  88. public ProgressiveFileCopier(IFileSystem fileSystem, TranscodingJob job, ILogger logger)
  89. {
  90. _fileSystem = fileSystem;
  91. _job = job;
  92. _logger = logger;
  93. }
  94. public async Task StreamFile(string path, Stream outputStream)
  95. {
  96. var eofCount = 0;
  97. long position = 0;
  98. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  99. {
  100. while (eofCount < 15)
  101. {
  102. await CopyToInternal(fs, outputStream, BufferSize).ConfigureAwait(false);
  103. var fsPosition = fs.Position;
  104. var bytesRead = fsPosition - position;
  105. //Logger.Debug("Streamed {0} bytes from file {1}", bytesRead, path);
  106. if (bytesRead == 0)
  107. {
  108. if (_job == null || _job.HasExited)
  109. {
  110. eofCount++;
  111. }
  112. await Task.Delay(100).ConfigureAwait(false);
  113. }
  114. else
  115. {
  116. eofCount = 0;
  117. }
  118. position = fsPosition;
  119. }
  120. }
  121. }
  122. private async Task CopyToInternal(Stream source, Stream destination, int bufferSize)
  123. {
  124. var array = new byte[bufferSize];
  125. int count;
  126. while ((count = await source.ReadAsync(array, 0, array.Length).ConfigureAwait(false)) != 0)
  127. {
  128. //if (_job != null)
  129. //{
  130. // var didPause = false;
  131. // var totalPauseTime = 0;
  132. // if (_job.IsUserPaused)
  133. // {
  134. // _logger.Debug("Pausing writing to network stream while user has paused playback.");
  135. // while (_job.IsUserPaused && totalPauseTime < 30000)
  136. // {
  137. // didPause = true;
  138. // var pauseTime = 500;
  139. // totalPauseTime += pauseTime;
  140. // await Task.Delay(pauseTime).ConfigureAwait(false);
  141. // }
  142. // }
  143. // if (didPause)
  144. // {
  145. // _logger.Debug("Resuming writing to network stream due to user unpausing playback.");
  146. // }
  147. //}
  148. await destination.WriteAsync(array, 0, count).ConfigureAwait(false);
  149. _bytesWritten += count;
  150. if (_job != null)
  151. {
  152. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  153. }
  154. }
  155. }
  156. }
  157. }