LiveStream.cs 7.5 KB

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