LiveStream.cs 7.3 KB

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