LiveStream.cs 7.3 KB

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