LiveStream.cs 6.9 KB

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