LiveStream.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 IServerApplicationPaths AppPaths;
  31. protected string TempFilePath;
  32. protected readonly ILogger Logger;
  33. protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
  34. public LiveStream(MediaSourceInfo mediaSource, IEnvironmentInfo environment, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
  35. {
  36. OriginalMediaSource = mediaSource;
  37. Environment = environment;
  38. FileSystem = fileSystem;
  39. OpenedMediaSource = mediaSource;
  40. Logger = logger;
  41. EnableStreamSharing = true;
  42. SharedStreamIds = new List<string>();
  43. UniqueId = Guid.NewGuid().ToString("N");
  44. AppPaths = appPaths;
  45. SetTempFilePath("ts");
  46. }
  47. protected void SetTempFilePath(string extension)
  48. {
  49. TempFilePath = Path.Combine(AppPaths.GetTranscodingTempPath(), UniqueId + "." + extension);
  50. }
  51. public virtual Task Open(CancellationToken openCancellationToken)
  52. {
  53. return Task.FromResult(true);
  54. }
  55. public void Close()
  56. {
  57. EnableStreamSharing = false;
  58. Logger.Info("Closing " + GetType().Name);
  59. CloseInternal();
  60. }
  61. protected virtual void CloseInternal()
  62. {
  63. }
  64. protected Stream GetInputStream(string path, bool allowAsyncFileRead)
  65. {
  66. var fileOpenOptions = FileOpenOptions.SequentialScan;
  67. if (allowAsyncFileRead)
  68. {
  69. fileOpenOptions |= FileOpenOptions.Asynchronous;
  70. }
  71. return FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
  72. }
  73. protected async Task DeleteTempFile(string path, int retryCount = 0)
  74. {
  75. if (retryCount == 0)
  76. {
  77. Logger.Info("Deleting temp file {0}", path);
  78. }
  79. try
  80. {
  81. FileSystem.DeleteFile(path);
  82. return;
  83. }
  84. catch (DirectoryNotFoundException)
  85. {
  86. return;
  87. }
  88. catch (FileNotFoundException)
  89. {
  90. return;
  91. }
  92. catch
  93. {
  94. }
  95. if (retryCount > 20)
  96. {
  97. return;
  98. }
  99. await Task.Delay(500).ConfigureAwait(false);
  100. await DeleteTempFile(path, retryCount + 1).ConfigureAwait(false);
  101. }
  102. public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
  103. {
  104. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
  105. var allowAsync = false;//Environment.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows;
  106. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  107. using (var inputStream = (FileStream)GetInputStream(TempFilePath, allowAsync))
  108. {
  109. TrySeek(inputStream, -20000);
  110. await CopyTo(inputStream, stream, 81920, null, cancellationToken).ConfigureAwait(false);
  111. }
  112. }
  113. private static async Task CopyTo(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken)
  114. {
  115. byte[] buffer = new byte[bufferSize];
  116. var eofCount = 0;
  117. var emptyReadLimit = 1000;
  118. while (eofCount < emptyReadLimit)
  119. {
  120. cancellationToken.ThrowIfCancellationRequested();
  121. var bytesRead = source.Read(buffer, 0, buffer.Length);
  122. if (bytesRead == 0)
  123. {
  124. eofCount++;
  125. await Task.Delay(10, cancellationToken).ConfigureAwait(false);
  126. }
  127. else
  128. {
  129. eofCount = 0;
  130. //await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
  131. destination.Write(buffer, 0, bytesRead);
  132. if (onStarted != null)
  133. {
  134. onStarted();
  135. onStarted = null;
  136. }
  137. }
  138. }
  139. }
  140. private void TrySeek(FileStream stream, long offset)
  141. {
  142. try
  143. {
  144. stream.Seek(offset, SeekOrigin.End);
  145. }
  146. catch (IOException)
  147. {
  148. }
  149. catch (ArgumentException)
  150. {
  151. }
  152. catch (Exception ex)
  153. {
  154. Logger.ErrorException("Error seeking stream", ex);
  155. }
  156. }
  157. }
  158. }