ProgressiveStreamWriter.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. 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. new ProgressiveFileCopier(_fileSystem, _job)
  59. .StreamFile(Path, responseStream);
  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. // 256k
  86. private const int BufferSize = 262144;
  87. private long _bytesWritten = 0;
  88. public ProgressiveFileCopier(IFileSystem fileSystem, TranscodingJob job)
  89. {
  90. _fileSystem = fileSystem;
  91. _job = job;
  92. }
  93. public void StreamFile(string path, Stream outputStream)
  94. {
  95. var eofCount = 0;
  96. long position = 0;
  97. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, false))
  98. {
  99. while (eofCount < 15)
  100. {
  101. CopyToInternal(fs, outputStream, BufferSize);
  102. var fsPosition = fs.Position;
  103. var bytesRead = fsPosition - position;
  104. //Logger.Debug("Streamed {0} bytes from file {1}", bytesRead, path);
  105. if (bytesRead == 0)
  106. {
  107. if (_job == null || _job.HasExited)
  108. {
  109. eofCount++;
  110. }
  111. var task = Task.Delay(100);
  112. Task.WaitAll(task);
  113. }
  114. else
  115. {
  116. eofCount = 0;
  117. }
  118. position = fsPosition;
  119. }
  120. }
  121. }
  122. private void CopyToInternal(Stream source, Stream destination, int bufferSize)
  123. {
  124. var array = new byte[bufferSize];
  125. int count;
  126. while ((count = source.Read(array, 0, array.Length)) != 0)
  127. {
  128. destination.Write(array, 0, count);
  129. _bytesWritten += count;
  130. if (_job != null)
  131. {
  132. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  133. }
  134. }
  135. }
  136. }
  137. }