LiveStream.cs 5.5 KB

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