ProgressiveStreamWriter.cs 5.8 KB

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