LiveStream.cs 5.7 KB

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