LiveStream.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
  121. // use non-async filestream on windows along with read due to https://github.com/dotnet/corefx/issues/6039
  122. var allowAsync = Environment.OSVersion.Platform != PlatformID.Win32NT;
  123. bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
  124. var nextFileInfo = GetNextFile(null);
  125. var nextFile = nextFileInfo.file;
  126. var isLastFile = nextFileInfo.isLastFile;
  127. while (!string.IsNullOrEmpty(nextFile))
  128. {
  129. var emptyReadLimit = isLastFile ? EmptyReadLimit : 1;
  130. await CopyFile(nextFile, seekFile, emptyReadLimit, allowAsync, stream, cancellationToken).ConfigureAwait(false);
  131. seekFile = false;
  132. nextFileInfo = GetNextFile(nextFile);
  133. nextFile = nextFileInfo.file;
  134. isLastFile = nextFileInfo.isLastFile;
  135. }
  136. Logger.LogInformation("Live Stream ended.");
  137. }
  138. private (string file, bool isLastFile) GetNextFile(string currentFile)
  139. {
  140. var files = GetStreamFilePaths();
  141. if (string.IsNullOrEmpty(currentFile))
  142. {
  143. return (files.Last(), true);
  144. }
  145. var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1;
  146. var isLastFile = nextIndex == files.Count - 1;
  147. return (files.ElementAtOrDefault(nextIndex), isLastFile);
  148. }
  149. private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
  150. {
  151. using (var inputStream = GetInputStream(path, allowAsync))
  152. {
  153. if (seekFile)
  154. {
  155. TrySeek(inputStream, -20000);
  156. }
  157. await StreamHelper.CopyToAsync(
  158. inputStream,
  159. stream,
  160. IODefaults.CopyToBufferSize,
  161. emptyReadLimit,
  162. cancellationToken).ConfigureAwait(false);
  163. }
  164. }
  165. private void TrySeek(FileStream stream, long offset)
  166. {
  167. if (!stream.CanSeek)
  168. {
  169. return;
  170. }
  171. try
  172. {
  173. stream.Seek(offset, SeekOrigin.End);
  174. }
  175. catch (IOException)
  176. {
  177. }
  178. catch (ArgumentException)
  179. {
  180. }
  181. catch (Exception ex)
  182. {
  183. Logger.LogError(ex, "Error seeking stream");
  184. }
  185. }
  186. }
  187. }