ProgressiveStreamWriter.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. using System.Threading;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Model.Logging;
  4. using ServiceStack.Web;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Threading.Tasks;
  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. var task = WriteToAsync(responseStream);
  49. Task.WaitAll(task);
  50. }
  51. /// <summary>
  52. /// Writes to async.
  53. /// </summary>
  54. /// <param name="responseStream">The response stream.</param>
  55. /// <returns>Task.</returns>
  56. public async Task WriteToAsync(Stream responseStream)
  57. {
  58. try
  59. {
  60. await new ProgressiveFileCopier(_fileSystem, _job)
  61. .StreamFile(Path, responseStream).ConfigureAwait(false);
  62. }
  63. catch (Exception ex)
  64. {
  65. Logger.ErrorException("Error streaming media. The client has most likely disconnected or transcoding has failed.", ex);
  66. throw;
  67. }
  68. finally
  69. {
  70. if (_job != null)
  71. {
  72. ApiEntryPoint.Instance.OnTranscodeEndRequest(_job);
  73. }
  74. }
  75. }
  76. }
  77. public class ProgressiveFileCopier
  78. {
  79. private readonly IFileSystem _fileSystem;
  80. private readonly TranscodingJob _job;
  81. private long _bytesWritten = 0;
  82. public ProgressiveFileCopier(IFileSystem fileSystem, TranscodingJob job)
  83. {
  84. _fileSystem = fileSystem;
  85. _job = job;
  86. }
  87. public async Task StreamFile(string path, Stream outputStream)
  88. {
  89. var eofCount = 0;
  90. long position = 0;
  91. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  92. {
  93. while (eofCount < 15)
  94. {
  95. await CopyToAsyncInternal(fs, outputStream, 81920, CancellationToken.None).ConfigureAwait(false);
  96. var fsPosition = fs.Position;
  97. var bytesRead = fsPosition - position;
  98. //Logger.Debug("Streamed {0} bytes from file {1}", bytesRead, path);
  99. if (bytesRead == 0)
  100. {
  101. if (_job == null || _job.HasExited)
  102. {
  103. eofCount++;
  104. }
  105. await Task.Delay(100).ConfigureAwait(false);
  106. }
  107. else
  108. {
  109. eofCount = 0;
  110. }
  111. position = fsPosition;
  112. }
  113. }
  114. }
  115. private async Task CopyToAsyncInternal(Stream source, Stream destination, int bufferSize, CancellationToken cancellationToken)
  116. {
  117. byte[] array = new byte[bufferSize];
  118. int count;
  119. while ((count = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
  120. {
  121. await destination.WriteAsync(array, 0, count, cancellationToken).ConfigureAwait(false);
  122. _bytesWritten += count;
  123. if (_job != null)
  124. {
  125. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  126. }
  127. }
  128. }
  129. }
  130. }