ProgressiveStreamWriter.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Model.Logging;
  3. using ServiceStack.Service;
  4. using System;
  5. using System.IO;
  6. using System.Threading.Tasks;
  7. namespace MediaBrowser.Api.Playback.Progressive
  8. {
  9. public class ProgressiveStreamWriter : IStreamWriter
  10. {
  11. private string Path { get; set; }
  12. private StreamState State { get; set; }
  13. private ILogger Logger { get; set; }
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="ProgressiveStreamWriter" /> class.
  16. /// </summary>
  17. /// <param name="path">The path.</param>
  18. /// <param name="state">The state.</param>
  19. /// <param name="logger">The logger.</param>
  20. public ProgressiveStreamWriter(string path, StreamState state, ILogger logger)
  21. {
  22. Path = path;
  23. State = state;
  24. Logger = logger;
  25. }
  26. /// <summary>
  27. /// Writes to.
  28. /// </summary>
  29. /// <param name="responseStream">The response stream.</param>
  30. public void WriteTo(Stream responseStream)
  31. {
  32. var task = WriteToAsync(responseStream);
  33. Task.WaitAll(task);
  34. }
  35. /// <summary>
  36. /// Writes to async.
  37. /// </summary>
  38. /// <param name="responseStream">The response stream.</param>
  39. /// <returns>Task.</returns>
  40. public async Task WriteToAsync(Stream responseStream)
  41. {
  42. try
  43. {
  44. await StreamFile(Path, responseStream).ConfigureAwait(false);
  45. }
  46. catch (Exception ex)
  47. {
  48. Logger.ErrorException("Error streaming media", ex);
  49. throw;
  50. }
  51. finally
  52. {
  53. ApiEntryPoint.Instance.OnTranscodeEndRequest(Path, TranscodingJobType.Progressive);
  54. }
  55. }
  56. /// <summary>
  57. /// Streams the file.
  58. /// </summary>
  59. /// <param name="path">The path.</param>
  60. /// <param name="outputStream">The output stream.</param>
  61. /// <returns>Task{System.Boolean}.</returns>
  62. private async Task StreamFile(string path, Stream outputStream)
  63. {
  64. var eofCount = 0;
  65. long position = 0;
  66. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  67. {
  68. while (eofCount < 15)
  69. {
  70. await fs.CopyToAsync(outputStream).ConfigureAwait(false);
  71. var fsPosition = fs.Position;
  72. var bytesRead = fsPosition - position;
  73. //Logger.LogInfo("Streamed {0} bytes from file {1}", bytesRead, path);
  74. if (bytesRead == 0)
  75. {
  76. eofCount++;
  77. await Task.Delay(100).ConfigureAwait(false);
  78. }
  79. else
  80. {
  81. eofCount = 0;
  82. }
  83. position = fsPosition;
  84. }
  85. }
  86. }
  87. }
  88. }