LiveStream.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Controller;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.IO;
  11. using MediaBrowser.Model.LiveTv;
  12. using Microsoft.Extensions.Logging;
  13. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  14. {
  15. public class LiveStream : ILiveStream
  16. {
  17. public MediaSourceInfo OriginalMediaSource { get; set; }
  18. public MediaSourceInfo MediaSource { get; set; }
  19. public int ConsumerCount { get; set; }
  20. public string OriginalStreamId { get; set; }
  21. public bool EnableStreamSharing { get; set; }
  22. public string UniqueId { get; }
  23. protected readonly IFileSystem FileSystem;
  24. protected readonly IServerApplicationPaths AppPaths;
  25. protected string TempFilePath;
  26. protected readonly ILogger Logger;
  27. protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
  28. public string TunerHostId { get; }
  29. public DateTime DateOpened { get; protected set; }
  30. public LiveStream(MediaSourceInfo mediaSource, TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
  31. {
  32. OriginalMediaSource = mediaSource;
  33. FileSystem = fileSystem;
  34. MediaSource = mediaSource;
  35. Logger = logger;
  36. EnableStreamSharing = true;
  37. UniqueId = Guid.NewGuid().ToString("N");
  38. if (tuner != null)
  39. {
  40. TunerHostId = tuner.Id;
  41. }
  42. AppPaths = appPaths;
  43. ConsumerCount = 1;
  44. SetTempFilePath("ts");
  45. }
  46. protected void SetTempFilePath(string extension)
  47. {
  48. TempFilePath = Path.Combine(AppPaths.GetTranscodingTempPath(), UniqueId + "." + extension);
  49. }
  50. public virtual Task Open(CancellationToken openCancellationToken)
  51. {
  52. DateOpened = DateTime.UtcNow;
  53. return Task.CompletedTask;
  54. }
  55. public Task Close()
  56. {
  57. EnableStreamSharing = false;
  58. Logger.LogInformation("Closing " + GetType().Name);
  59. LiveStreamCancellationTokenSource.Cancel();
  60. return Task.CompletedTask;
  61. }
  62. protected Stream GetInputStream(string path, bool allowAsyncFileRead)
  63. {
  64. var fileOpenOptions = FileOpenOptions.SequentialScan;
  65. if (allowAsyncFileRead)
  66. {
  67. fileOpenOptions |= FileOpenOptions.Asynchronous;
  68. }
  69. return FileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, fileOpenOptions);
  70. }
  71. public Task DeleteTempFiles()
  72. {
  73. return DeleteTempFiles(GetStreamFilePaths());
  74. }
  75. protected async Task DeleteTempFiles(IEnumerable<string> paths, int retryCount = 0)
  76. {
  77. if (retryCount == 0)
  78. {
  79. Logger.LogInformation("Deleting temp files {0}", paths);
  80. }
  81. var failedFiles = new List<string>();
  82. foreach (var path in paths)
  83. {
  84. if (!File.Exists(path))
  85. {
  86. continue;
  87. }
  88. try
  89. {
  90. FileSystem.DeleteFile(path);
  91. }
  92. catch (Exception ex)
  93. {
  94. Logger.LogError(ex, "Error deleting file {path}", path);
  95. failedFiles.Add(path);
  96. }
  97. }
  98. if (failedFiles.Count > 0 && retryCount <= 40)
  99. {
  100. await Task.Delay(500).ConfigureAwait(false);
  101. await DeleteTempFiles(failedFiles, retryCount + 1).ConfigureAwait(false);
  102. }
  103. }
  104. protected virtual List<string> GetStreamFilePaths()
  105. {
  106. return new List<string> { TempFilePath };
  107. }
  108. public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
  109. {
  110. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
  111. // use non-async filestream on windows along with read due to https://github.com/dotnet/corefx/issues/6039
  112. var allowAsync = Environment.OSVersion.Platform != PlatformID.Win32NT;
  113. bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
  114. var nextFileInfo = GetNextFile(null);
  115. var nextFile = nextFileInfo.Item1;
  116. var isLastFile = nextFileInfo.Item2;
  117. while (!string.IsNullOrEmpty(nextFile))
  118. {
  119. var emptyReadLimit = isLastFile ? EmptyReadLimit : 1;
  120. await CopyFile(nextFile, seekFile, emptyReadLimit, allowAsync, stream, cancellationToken).ConfigureAwait(false);
  121. seekFile = false;
  122. nextFileInfo = GetNextFile(nextFile);
  123. nextFile = nextFileInfo.Item1;
  124. isLastFile = nextFileInfo.Item2;
  125. }
  126. Logger.LogInformation("Live Stream ended.");
  127. }
  128. private (string file, bool isLastFile) GetNextFile(string currentFile)
  129. {
  130. var files = GetStreamFilePaths();
  131. if (string.IsNullOrEmpty(currentFile))
  132. {
  133. return (files.Last(), true);
  134. }
  135. var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1;
  136. var isLastFile = nextIndex == files.Count - 1;
  137. return (files.ElementAtOrDefault(nextIndex), isLastFile);
  138. }
  139. private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
  140. {
  141. using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
  142. {
  143. if (seekFile)
  144. {
  145. TrySeek(inputStream, -20000);
  146. }
  147. await ApplicationHost.StreamHelper.CopyToAsync(inputStream, stream, 81920, emptyReadLimit, cancellationToken).ConfigureAwait(false);
  148. }
  149. }
  150. protected virtual int EmptyReadLimit => 1000;
  151. private void TrySeek(FileStream stream, long offset)
  152. {
  153. if (!stream.CanSeek)
  154. {
  155. return;
  156. }
  157. try
  158. {
  159. stream.Seek(offset, SeekOrigin.End);
  160. }
  161. catch (IOException)
  162. {
  163. }
  164. catch (ArgumentException)
  165. {
  166. }
  167. catch (Exception ex)
  168. {
  169. Logger.LogError(ex, "Error seeking stream");
  170. }
  171. }
  172. }
  173. }