ProgressiveStreamWriter.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. public string Path { get; set; }
  12. public StreamState State { get; set; }
  13. public ILogger Logger { get; set; }
  14. /// <summary>
  15. /// Writes to.
  16. /// </summary>
  17. /// <param name="responseStream">The response stream.</param>
  18. public void WriteTo(Stream responseStream)
  19. {
  20. var task = WriteToAsync(responseStream);
  21. Task.WaitAll(task);
  22. }
  23. /// <summary>
  24. /// Writes to async.
  25. /// </summary>
  26. /// <param name="responseStream">The response stream.</param>
  27. /// <returns>Task.</returns>
  28. public async Task WriteToAsync(Stream responseStream)
  29. {
  30. try
  31. {
  32. await StreamFile(Path, responseStream).ConfigureAwait(false);
  33. }
  34. catch (Exception ex)
  35. {
  36. Logger.ErrorException("Error streaming media", ex);
  37. }
  38. finally
  39. {
  40. ApiEntryPoint.Instance.OnTranscodeEndRequest(Path, TranscodingJobType.Progressive);
  41. }
  42. }
  43. /// <summary>
  44. /// Streams the file.
  45. /// </summary>
  46. /// <param name="path">The path.</param>
  47. /// <param name="outputStream">The output stream.</param>
  48. /// <returns>Task{System.Boolean}.</returns>
  49. private async Task StreamFile(string path, Stream outputStream)
  50. {
  51. var eofCount = 0;
  52. long position = 0;
  53. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  54. {
  55. while (eofCount < 15)
  56. {
  57. await fs.CopyToAsync(outputStream).ConfigureAwait(false);
  58. var fsPosition = fs.Position;
  59. var bytesRead = fsPosition - position;
  60. //Logger.LogInfo("Streamed {0} bytes from file {1}", bytesRead, path);
  61. if (bytesRead == 0)
  62. {
  63. eofCount++;
  64. await Task.Delay(100).ConfigureAwait(false);
  65. }
  66. else
  67. {
  68. eofCount = 0;
  69. }
  70. position = fsPosition;
  71. }
  72. }
  73. }
  74. }
  75. }