LiveStream.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Controller;
  7. using MediaBrowser.Controller.IO;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.IO;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.System;
  13. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  14. {
  15. public class LiveStream : ILiveStream
  16. {
  17. public MediaSourceInfo OriginalMediaSource { get; set; }
  18. public MediaSourceInfo OpenedMediaSource { get; set; }
  19. public int ConsumerCount
  20. {
  21. get { return SharedStreamIds.Count; }
  22. }
  23. public ITunerHost TunerHost { get; set; }
  24. public string OriginalStreamId { get; set; }
  25. public bool EnableStreamSharing { get; set; }
  26. public string UniqueId { get; private set; }
  27. public List<string> SharedStreamIds { get; private set; }
  28. protected readonly IEnvironmentInfo Environment;
  29. protected readonly IFileSystem FileSystem;
  30. protected readonly string TempFilePath;
  31. protected readonly ILogger Logger;
  32. protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
  33. public LiveStream(MediaSourceInfo mediaSource, IEnvironmentInfo environment, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
  34. {
  35. OriginalMediaSource = mediaSource;
  36. Environment = environment;
  37. FileSystem = fileSystem;
  38. OpenedMediaSource = mediaSource;
  39. Logger = logger;
  40. EnableStreamSharing = true;
  41. SharedStreamIds = new List<string>();
  42. UniqueId = Guid.NewGuid().ToString("N");
  43. TempFilePath = Path.Combine(appPaths.TranscodingTempPath, UniqueId + ".ts");
  44. }
  45. public virtual Task Open(CancellationToken openCancellationToken)
  46. {
  47. return Task.FromResult(true);
  48. }
  49. public virtual void Close()
  50. {
  51. }
  52. protected Stream GetInputStream(string path, bool allowAsyncFileRead)
  53. {
  54. var fileOpenOptions = FileOpenOptions.SequentialScan;
  55. if (allowAsyncFileRead)
  56. {
  57. fileOpenOptions |= FileOpenOptions.Asynchronous;
  58. }
  59. return FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
  60. }
  61. protected async Task DeleteTempFile(string path, int retryCount = 0)
  62. {
  63. if (retryCount == 0)
  64. {
  65. Logger.Info("Deleting temp file {0}", path);
  66. }
  67. try
  68. {
  69. FileSystem.DeleteFile(path);
  70. return;
  71. }
  72. catch (DirectoryNotFoundException)
  73. {
  74. return;
  75. }
  76. catch (FileNotFoundException)
  77. {
  78. return;
  79. }
  80. catch
  81. {
  82. }
  83. if (retryCount > 20)
  84. {
  85. return;
  86. }
  87. await Task.Delay(500).ConfigureAwait(false);
  88. await DeleteTempFile(path, retryCount + 1).ConfigureAwait(false);
  89. }
  90. public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
  91. {
  92. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
  93. var allowAsync = false;//Environment.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows;
  94. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  95. using (var inputStream = (FileStream)GetInputStream(TempFilePath, allowAsync))
  96. {
  97. TrySeek(inputStream, -20000);
  98. await CopyTo(inputStream, stream, 81920, null, cancellationToken).ConfigureAwait(false);
  99. }
  100. }
  101. private static async Task CopyTo(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken)
  102. {
  103. byte[] buffer = new byte[bufferSize];
  104. var eofCount = 0;
  105. var emptyReadLimit = 1000;
  106. while (eofCount < emptyReadLimit)
  107. {
  108. cancellationToken.ThrowIfCancellationRequested();
  109. var bytesRead = source.Read(buffer, 0, buffer.Length);
  110. if (bytesRead == 0)
  111. {
  112. eofCount++;
  113. await Task.Delay(10, cancellationToken).ConfigureAwait(false);
  114. }
  115. else
  116. {
  117. eofCount = 0;
  118. //await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
  119. destination.Write(buffer, 0, bytesRead);
  120. if (onStarted != null)
  121. {
  122. onStarted();
  123. onStarted = null;
  124. }
  125. }
  126. }
  127. }
  128. private void TrySeek(FileStream stream, long offset)
  129. {
  130. try
  131. {
  132. stream.Seek(offset, SeekOrigin.End);
  133. }
  134. catch (IOException)
  135. {
  136. }
  137. catch (ArgumentException)
  138. {
  139. }
  140. catch (Exception ex)
  141. {
  142. Logger.ErrorException("Error seeking stream", ex);
  143. }
  144. }
  145. }
  146. }