ProgressiveStreamWriter.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. WriteToInternal(responseStream);
  48. }
  49. /// <summary>
  50. /// Writes to async.
  51. /// </summary>
  52. /// <param name="responseStream">The response stream.</param>
  53. /// <returns>Task.</returns>
  54. private void WriteToInternal(Stream responseStream)
  55. {
  56. try
  57. {
  58. var task = new ProgressiveFileCopier(_fileSystem, _job, Logger).StreamFile(Path, responseStream);
  59. Task.WaitAll(task);
  60. }
  61. catch (IOException)
  62. {
  63. // These error are always the same so don't dump the whole stack trace
  64. Logger.Error("Error streaming media. The client has most likely disconnected or transcoding has failed.");
  65. throw;
  66. }
  67. catch (Exception ex)
  68. {
  69. Logger.ErrorException("Error streaming media. The client has most likely disconnected or transcoding has failed.", ex);
  70. throw;
  71. }
  72. finally
  73. {
  74. if (_job != null)
  75. {
  76. ApiEntryPoint.Instance.OnTranscodeEndRequest(_job);
  77. }
  78. }
  79. }
  80. }
  81. public class ProgressiveFileCopier
  82. {
  83. private readonly IFileSystem _fileSystem;
  84. private readonly TranscodingJob _job;
  85. private readonly ILogger _logger;
  86. // 256k
  87. private const int BufferSize = 262144;
  88. private long _bytesWritten = 0;
  89. public ProgressiveFileCopier(IFileSystem fileSystem, TranscodingJob job, ILogger logger)
  90. {
  91. _fileSystem = fileSystem;
  92. _job = job;
  93. _logger = logger;
  94. }
  95. public async Task StreamFile(string path, Stream outputStream)
  96. {
  97. var eofCount = 0;
  98. long position = 0;
  99. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, false))
  100. {
  101. while (eofCount < 15)
  102. {
  103. CopyToInternal(fs, outputStream, BufferSize);
  104. var fsPosition = fs.Position;
  105. var bytesRead = fsPosition - position;
  106. //Logger.Debug("Streamed {0} bytes from file {1}", bytesRead, path);
  107. if (bytesRead == 0)
  108. {
  109. if (_job == null || _job.HasExited)
  110. {
  111. eofCount++;
  112. }
  113. await Task.Delay(100).ConfigureAwait(false);
  114. }
  115. else
  116. {
  117. eofCount = 0;
  118. }
  119. position = fsPosition;
  120. }
  121. }
  122. }
  123. private void CopyToInternal(Stream source, Stream destination, int bufferSize)
  124. {
  125. var array = new byte[bufferSize];
  126. int count;
  127. while ((count = source.Read(array, 0, array.Length)) != 0)
  128. {
  129. //if (_job != null)
  130. //{
  131. // var didPause = false;
  132. // var totalPauseTime = 0;
  133. // if (_job.IsUserPaused)
  134. // {
  135. // _logger.Debug("Pausing writing to network stream while user has paused playback.");
  136. // while (_job.IsUserPaused && totalPauseTime < 30000)
  137. // {
  138. // didPause = true;
  139. // var pauseTime = 500;
  140. // totalPauseTime += pauseTime;
  141. // await Task.Delay(pauseTime).ConfigureAwait(false);
  142. // }
  143. // }
  144. // if (didPause)
  145. // {
  146. // _logger.Debug("Resuming writing to network stream due to user unpausing playback.");
  147. // }
  148. //}
  149. destination.Write(array, 0, count);
  150. _bytesWritten += count;
  151. if (_job != null)
  152. {
  153. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  154. }
  155. }
  156. }
  157. }
  158. }