ProgressiveStreamWriter.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. new ProgressiveFileCopier(_fileSystem, _job)
  60. .StreamFile(Path, responseStream);
  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. // 256k
  87. private const int BufferSize = 262144;
  88. private long _bytesWritten = 0;
  89. public ProgressiveFileCopier(IFileSystem fileSystem, TranscodingJob job)
  90. {
  91. _fileSystem = fileSystem;
  92. _job = job;
  93. }
  94. public void 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, false))
  99. {
  100. while (eofCount < 15)
  101. {
  102. CopyToInternal(fs, outputStream, BufferSize);
  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. var task = Task.Delay(100);
  113. Task.WaitAll(task);
  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. destination.Write(array, 0, count);
  130. _bytesWritten += count;
  131. if (_job != null)
  132. {
  133. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  134. }
  135. }
  136. }
  137. }
  138. }