LiveStream.cs 7.7 KB

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